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
|
|---|---|---|---|---|---|---|---|---|---|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/model/XfaFile.java
|
XfaFile
|
writeTo
|
class XfaFile implements OutputStreamResource {
/**
* The X4J Document object (XML).
*/
protected Document xfaDocument;
/**
* Constructs an XFA file from an OutputStreamResource. This resource can be an XML file or a node in a RUPS
* application.
*
* @param resource the XFA resource
* @throws IOException thrown when an I/O operation goes wrong
* @throws DocumentException thrown when something goes wrong with a Document
*/
public XfaFile(OutputStreamResource resource) throws IOException, DocumentException {
// Is there a way to avoid loading everything in memory?
// Can we somehow get the XML from the PDF as an InputSource, Reader or InputStream?
ByteArrayOutputStream baos = new ByteArrayOutputStream();
resource.writeTo(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
SAXReader reader = new SAXReader();
xfaDocument = reader.read(bais);
}
/**
* Getter for the XFA Document object.
*
* @return a Document object (X4J)
*/
public Document getXfaDocument() {
return xfaDocument;
}
/**
* Writes a formatted XML file to the OutputStream.
*
* @see com.lowagie.rups.io.OutputStreamResource#writeTo(java.io.OutputStream)
*/
public void writeTo(OutputStream os) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (xfaDocument == null) {
return;
}
OutputFormat format = new OutputFormat(" ", true);
XMLWriter writer = new XMLWriter(os, format);
writer.write(xfaDocument);
| 381
| 59
| 440
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/Console.java
|
Console
|
update
|
class Console implements Observer {
/**
* Single Console instance.
*/
private static Console console = null;
/**
* Custom PrintStream.
*/
PrintStream printStream;
/**
* Custom OutputStream.
*/
PipedOutputStream poCustom;
/**
* Custom InputStream.
*/
PipedInputStream piCustom;
/**
* OutputStream for System.out.
*/
PipedOutputStream poOut;
/**
* InputStream for System.out.
*/
PipedInputStream piOut;
/**
* OutputStream for System.err.
*/
PipedOutputStream poErr;
/**
* InputStream for System.err.
*/
PipedInputStream piErr;
/**
* The StyleContext for the Console.
*/
ConsoleStyleContext styleContext = new ConsoleStyleContext();
/**
* The text area to which everything is written.
*/
JTextPane textArea = new JTextPane(new DefaultStyledDocument(styleContext));
/**
* Creates a new Console object.
*
* @throws IOException
*/
private Console() throws IOException {
// Set up Custom
piCustom = new PipedInputStream();
poCustom = new PipedOutputStream();
printStream = new PrintStream(poCustom);
// Set up System.out
piOut = new PipedInputStream();
poOut = new PipedOutputStream(piOut);
System.setOut(new PrintStream(poOut, true));
// Set up System.err
piErr = new PipedInputStream();
poErr = new PipedOutputStream(piErr);
System.setErr(new PrintStream(poErr, true));
// Add a scrolling text area
textArea.setEditable(false);
// Create reader threads
new ReadWriteThread(piCustom, ConsoleStyleContext.CUSTOM).start();
new ReadWriteThread(piOut, ConsoleStyleContext.SYSTEMOUT).start();
new ReadWriteThread(piErr, ConsoleStyleContext.SYSTEMERR).start();
}
/**
* Console is a Singleton class: you can only get one Console.
*
* @return the Console
*/
public static synchronized Console getInstance() {
if (console == null) {
try {
console = new Console();
} catch (IOException e) {
console = null;
}
}
return console;
}
/**
* Allows you to print something to the custom PrintStream.
*
* @param s the message you want to send to the Console
*/
public static void println(String s) {
PrintStream ps = getInstance().getPrintStream();
if (ps == null) {
System.out.println(s);
} else {
ps.println(s);
ps.flush();
}
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
/**
* Get the custom PrintStream of the console.
*
* @return the PrintStream
*/
public PrintStream getPrintStream() {
return printStream;
}
/**
* Get the JTextArea to which everything is written.
*
* @return the JTextArea
*/
public JTextPane getTextArea() {
return textArea;
}
/**
* The thread that will write everything to the text area.
*/
class ReadWriteThread extends Thread {
/**
* The InputStream of this Thread
*/
PipedInputStream pi;
/**
* The type (CUSTOM, SYSTEMOUT, SYSTEMERR) of this Thread
*/
String type;
/**
* Create the ReaderThread.
*/
ReadWriteThread(PipedInputStream pi, String type) {
super();
this.pi = pi;
this.type = type;
}
/**
* @see java.lang.Thread#run()
*/
public void run() {
final byte[] buf = new byte[1024];
while (true) {
try {
final int len = pi.read(buf);
if (len == -1) {
break;
}
Document doc = textArea.getDocument();
AttributeSet attset = styleContext.getStyle(type);
String snippet = new String(buf, 0, len);
doc.insertString(doc.getLength(),
snippet, attset);
printStream.print(snippet);
textArea.setCaretPosition(textArea.getDocument().getLength());
} catch (BadLocationException | IOException ignored) {
// ignored
}
}
}
}
/**
* The style context defining the styles of each type of PrintStream.
*/
class ConsoleStyleContext extends StyleContext {
/**
* The name of the Style used for Custom messages
*/
public static final String CUSTOM = "Custom";
/**
* The name of the Style used for System.out
*/
public static final String SYSTEMOUT = "SystemOut";
/**
* The name of the Style used for System.err
*/
public static final String SYSTEMERR = "SystemErr";
/**
* A Serial Version UID.
*/
private static final long serialVersionUID = 7253870053566811171L;
/**
* Creates the style context for the Console.
*/
public ConsoleStyleContext() {
super();
Style root = getStyle(DEFAULT_STYLE);
Style s = addStyle(CUSTOM, root);
StyleConstants.setForeground(s, Color.BLACK);
s = addStyle(SYSTEMOUT, root);
StyleConstants.setForeground(s, Color.GREEN);
s = addStyle(SYSTEMERR, root);
StyleConstants.setForeground(s, Color.RED);
}
}
}
|
if (RupsMenuBar.CLOSE.equals(obj)) {
textArea.setText("");
}
if (RupsMenuBar.OPEN.equals(obj)) {
textArea.setText("");
}
| 1,562
| 60
| 1,622
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/MessageAction.java
|
MessageAction
|
actionPerformed
|
class MessageAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {<FILL_FUNCTION_BODY>}
}
|
String message = "Unspecified message";
if (RupsMenuBar.ABOUT.equals(evt.getActionCommand())) {
message = "RUPS is a tool by 1T3XT BVBA.\nIt uses iText, a Free Java-PDF Library.\nVisit http://www.1t3xt.com/ for more info.";
} else if (RupsMenuBar.VERSION.equals(evt.getActionCommand())) {
message = "iText version: " + Document.getVersion();
}
JOptionPane.showMessageDialog(null, message);
| 38
| 144
| 182
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/RupsMenuBar.java
|
RupsMenuBar
|
update
|
class RupsMenuBar extends JMenuBar implements Observer {
/**
* Caption for the file menu.
*/
public static final String FILE_MENU = "File";
/**
* Caption for "Open file".
*/
public static final String OPEN = "Open";
/**
* Caption for "Close file".
*/
public static final String CLOSE = "Close";
/**
* Caption for the help menu.
*/
public static final String HELP_MENU = "Help";
/**
* Caption for "Help about".
*/
public static final String ABOUT = "About";
/**
* Caption for "Help versions".
*
* @since iText 5.0.0 (renamed from VERSIONS)
*/
public static final String VERSION = "Version";
/**
* A Serial Version UID.
*/
private static final long serialVersionUID = 6403040037592308742L;
/**
* The Observable object.
*/
protected Observable observable;
/**
* The action needed to open a file.
*/
protected FileChooserAction fileChooserAction;
/**
* The HashMap with all the actions.
*/
protected HashMap<String, JMenuItem> items;
/**
* Creates a JMenuBar.
*
* @param observable the controller to which this menu bar is added
*/
public RupsMenuBar(Observable observable) {
this.observable = observable;
items = new HashMap<>();
fileChooserAction = new FileChooserAction(observable, "Open", PdfFilter.INSTANCE, false);
MessageAction message = new MessageAction();
JMenu file = new JMenu(FILE_MENU);
addItem(file, OPEN, fileChooserAction);
addItem(file, CLOSE, new FileCloseAction(observable));
add(file);
add(Box.createGlue());
JMenu help = new JMenu(HELP_MENU);
addItem(help, ABOUT, message);
addItem(help, VERSION, message);
add(help);
enableItems(false);
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
/**
* Create an item with a certain caption and a certain action, then add the item to a menu.
*
* @param menu the menu to which the item has to be added
* @param caption the caption of the item
* @param action the action corresponding with the caption
*/
protected void addItem(JMenu menu, String caption, ActionListener action) {
JMenuItem item = new JMenuItem(caption);
item.addActionListener(action);
menu.add(item);
items.put(caption, item);
}
/**
* Enables/Disables a series of menu items.
*
* @param enabled true for enabling; false for disabling
*/
protected void enableItems(boolean enabled) {
enableItem(CLOSE, enabled);
}
/**
* Enables/disables a specific menu item
*
* @param caption the caption of the item that needs to be enabled/disabled
* @param enabled true for enabling; false for disabling
*/
protected void enableItem(String caption, boolean enabled) {
items.get(caption).setEnabled(enabled);
}
}
|
if (OPEN.equals(obj)) {
enableItems(true);
return;
}
if (CLOSE.equals(obj)) {
enableItems(false);
return;
}
if (FILE_MENU.equals(obj)) {
fileChooserAction.actionPerformed(null);
}
| 939
| 88
| 1,027
|
<methods>public void <init>() ,public javax.swing.JMenu add(javax.swing.JMenu) ,public void addNotify() ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Component getComponent() ,public java.awt.Component getComponentAtIndex(int) ,public int getComponentIndex(java.awt.Component) ,public javax.swing.JMenu getHelpMenu() ,public java.awt.Insets getMargin() ,public javax.swing.JMenu getMenu(int) ,public int getMenuCount() ,public javax.swing.SingleSelectionModel getSelectionModel() ,public javax.swing.MenuElement[] getSubElements() ,public javax.swing.plaf.MenuBarUI getUI() ,public java.lang.String getUIClassID() ,public boolean isBorderPainted() ,public boolean isSelected() ,public void menuSelectionChanged(boolean) ,public void processKeyEvent(java.awt.event.KeyEvent, javax.swing.MenuElement[], javax.swing.MenuSelectionManager) ,public void processMouseEvent(java.awt.event.MouseEvent, javax.swing.MenuElement[], javax.swing.MenuSelectionManager) ,public void removeNotify() ,public void setBorderPainted(boolean) ,public void setHelpMenu(javax.swing.JMenu) ,public void setMargin(java.awt.Insets) ,public void setSelected(java.awt.Component) ,public void setSelectionModel(javax.swing.SingleSelectionModel) ,public void setUI(javax.swing.plaf.MenuBarUI) ,public void updateUI() <variables>private static final boolean DEBUG,private static final boolean TRACE,private static final boolean VERBOSE,private java.awt.Insets margin,private boolean paintBorder,private transient javax.swing.SingleSelectionModel selectionModel,private static final java.lang.String uiClassID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/icons/IconFetcher.java
|
IconFetcher
|
getIcon
|
class IconFetcher {
/**
* Cache with icons.
*/
protected static HashMap<String, Icon> cache = new HashMap<>();
/**
* Gets an Icon with a specific name.
*
* @param filename the filename of the Icon.
* @return an Icon
*/
public static Icon getIcon(String filename) {<FILL_FUNCTION_BODY>}
}
|
if (filename == null) {
return null;
}
Icon icon = cache.get(filename);
if (icon == null) {
try {
icon = new ImageIcon(IconFetcher.class.getResource(filename));
cache.put(filename, icon);
} catch (Exception e) {
System.err.println("Can't find file: " + filename);
return null;
}
}
return icon;
| 111
| 118
| 229
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/icons/IconTreeCellRenderer.java
|
IconTreeCellRenderer
|
getTreeCellRendererComponent
|
class IconTreeCellRenderer extends DefaultTreeCellRenderer {
/**
* a serial version UID.
*/
private static final long serialVersionUID = 6513462839504342074L;
/**
* @see javax.swing.tree.DefaultTreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object,
* boolean, boolean, boolean, int, boolean)
*/
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {<FILL_FUNCTION_BODY>}
}
|
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
if (value instanceof IconTreeNode) {
IconTreeNode node = (IconTreeNode) value;
setIcon(node.getIcon());
}
return this;
| 168
| 73
| 241
|
<methods>public void <init>() ,public void firePropertyChange(java.lang.String, byte, byte) ,public void firePropertyChange(java.lang.String, char, char) ,public void firePropertyChange(java.lang.String, short, short) ,public void firePropertyChange(java.lang.String, int, int) ,public void firePropertyChange(java.lang.String, long, long) ,public void firePropertyChange(java.lang.String, float, float) ,public void firePropertyChange(java.lang.String, double, double) ,public void firePropertyChange(java.lang.String, boolean, boolean) ,public java.awt.Color getBackgroundNonSelectionColor() ,public java.awt.Color getBackgroundSelectionColor() ,public java.awt.Color getBorderSelectionColor() ,public javax.swing.Icon getClosedIcon() ,public javax.swing.Icon getDefaultClosedIcon() ,public javax.swing.Icon getDefaultLeafIcon() ,public javax.swing.Icon getDefaultOpenIcon() ,public java.awt.Font getFont() ,public javax.swing.Icon getLeafIcon() ,public javax.swing.Icon getOpenIcon() ,public java.awt.Dimension getPreferredSize() ,public java.awt.Color getTextNonSelectionColor() ,public java.awt.Color getTextSelectionColor() ,public java.awt.Component getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean) ,public void invalidate() ,public void paint(java.awt.Graphics) ,public void repaint() ,public void repaint(java.awt.Rectangle) ,public void repaint(long, int, int, int, int) ,public void revalidate() ,public void setBackground(java.awt.Color) ,public void setBackgroundNonSelectionColor(java.awt.Color) ,public void setBackgroundSelectionColor(java.awt.Color) ,public void setBorderSelectionColor(java.awt.Color) ,public void setClosedIcon(javax.swing.Icon) ,public void setFont(java.awt.Font) ,public void setLeafIcon(javax.swing.Icon) ,public void setOpenIcon(javax.swing.Icon) ,public void setTextNonSelectionColor(java.awt.Color) ,public void setTextSelectionColor(java.awt.Color) ,public void updateUI() ,public void validate() <variables>protected java.awt.Color backgroundNonSelectionColor,protected java.awt.Color backgroundSelectionColor,protected java.awt.Color borderSelectionColor,protected transient javax.swing.Icon closedIcon,private boolean drawDashedFocusIndicator,private boolean drawsFocusBorderAroundIcon,private boolean fillBackground,private java.awt.Color focusBGColor,protected boolean hasFocus,private boolean inited,private boolean isDropCell,protected transient javax.swing.Icon leafIcon,protected transient javax.swing.Icon openIcon,protected boolean selected,protected java.awt.Color textNonSelectionColor,protected java.awt.Color textSelectionColor,private javax.swing.JTree tree,private java.awt.Color treeBGColor
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/FormTree.java
|
FormTree
|
valueChanged
|
class FormTree extends JTree implements TreeSelectionListener, Observer {
/**
* A serial version UID.
*/
private static final long serialVersionUID = -3584003547303700407L;
/**
* Nodes in the FormTree correspond with nodes in the main PdfTree.
*/
protected PdfReaderController controller;
/**
* If the form is an XFA form, the XML file is stored in this object.
*/
protected XfaFile xfaFile;
/**
* Treeview of the XFA file.
*/
protected XfaTree xfaTree;
/**
* Textview of the XFA file.
*/
protected XfaTextArea xfaTextArea;
/**
* Creates a new FormTree.
*
* @param controller The renderer that will render an object when selected in the table.
*/
public FormTree(PdfReaderController controller) {
super();
this.controller = controller;
setCellRenderer(new IconTreeCellRenderer());
setModel(new DefaultTreeModel(new FormTreeNode()));
addTreeSelectionListener(this);
xfaTree = new XfaTree();
xfaTextArea = new XfaTextArea();
}
/**
* Loads the fields of a PDF document into the FormTree.
*
* @param observable the observable object
* @param obj the object
*/
public void update(Observable observable, Object obj) {
if (obj == null) {
setModel(new DefaultTreeModel(new FormTreeNode()));
xfaFile = null;
xfaTree.clear();
xfaTextArea.clear();
repaint();
return;
}
if (obj instanceof ObjectLoader) {
ObjectLoader loader = (ObjectLoader) obj;
TreeNodeFactory factory = loader.getNodes();
PdfTrailerTreeNode trailer = controller.getPdfTree().getRoot();
PdfObjectTreeNode catalog = factory.getChildNode(trailer, PdfName.ROOT);
PdfObjectTreeNode form = factory.getChildNode(catalog, PdfName.ACROFORM);
if (form == null) {
return;
}
PdfObjectTreeNode fields = factory.getChildNode(form, PdfName.FIELDS);
FormTreeNode root = new FormTreeNode();
if (fields != null) {
FormTreeNode node = new FormTreeNode(fields);
node.setUserObject("Fields");
loadFields(factory, node, fields);
root.add(node);
}
PdfObjectTreeNode xfa = factory.getChildNode(form, PdfName.XFA);
if (xfa != null) {
XfaTreeNode node = new XfaTreeNode(xfa);
node.setUserObject("XFA");
loadXfa(factory, node, xfa);
root.add(node);
try {
xfaFile = new XfaFile(node);
xfaTree.load(xfaFile);
xfaTextArea.load(xfaFile);
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
setModel(new DefaultTreeModel(root));
}
}
/**
* Method that can be used recursively to load the fields hierarchy into the tree.
*
* @param factory a factory that can produce new PDF object nodes
* @param form_node the parent node in the form tree
* @param object_node the object node that will be used to create a child node
*/
private void loadFields(TreeNodeFactory factory, FormTreeNode form_node, PdfObjectTreeNode object_node) {
if (object_node == null) {
return;
}
factory.expandNode(object_node);
if (object_node.isIndirectReference()) {
loadFields(factory, form_node, (PdfObjectTreeNode) object_node.getFirstChild());
} else if (object_node.isArray()) {
Enumeration children = object_node.children();
while (children.hasMoreElements()) {
loadFields(factory, form_node, (PdfObjectTreeNode) children.nextElement());
}
} else if (object_node.isDictionary()) {
FormTreeNode leaf = new FormTreeNode(object_node);
form_node.add(leaf);
PdfObjectTreeNode kids = factory.getChildNode(object_node, PdfName.KIDS);
loadFields(factory, leaf, kids);
}
}
/**
* Method that will load the nodes that refer to XFA streams.
*
* @param form_node the parent node in the form tree
* @param object_node the object node that will be used to create a child node
*/
private void loadXfa(TreeNodeFactory factory, XfaTreeNode form_node, PdfObjectTreeNode object_node) {
if (object_node == null) {
return;
}
factory.expandNode(object_node);
if (object_node.isIndirectReference()) {
loadXfa(factory, form_node, (PdfObjectTreeNode) object_node.getFirstChild());
} else if (object_node.isArray()) {
Enumeration children = object_node.children();
PdfObjectTreeNode key;
PdfObjectTreeNode value;
while (children.hasMoreElements()) {
key = (PdfObjectTreeNode) children.nextElement();
value = (PdfObjectTreeNode) children.nextElement();
if (value.isIndirectReference()) {
factory.expandNode(value);
value = (PdfObjectTreeNode) value.getFirstChild();
}
form_node.addPacket(key.getPdfObject().toString(), value);
}
} else if (object_node.isStream()) {
form_node.addPacket("xdp", object_node);
}
}
/**
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent evt) {<FILL_FUNCTION_BODY>}
public XfaTree getXfaTree() {
return xfaTree;
}
public XfaTextArea getXfaTextArea() {
return xfaTextArea;
}
}
|
if (controller == null) {
return;
}
FormTreeNode selectednode = (FormTreeNode) this.getLastSelectedPathComponent();
if (selectednode == null) {
return;
}
PdfObjectTreeNode node = selectednode.getCorrespondingPdfObjectNode();
if (node != null) {
controller.selectNode(node);
}
| 1,616
| 100
| 1,716
|
<methods>public void <init>() ,public void <init>(java.lang.Object[]) ,public void <init>(Vector<?>) ,public void <init>(Hashtable<?,?>) ,public void <init>(javax.swing.tree.TreeNode) ,public void <init>(javax.swing.tree.TreeModel) ,public void <init>(javax.swing.tree.TreeNode, boolean) ,public void addSelectionInterval(int, int) ,public void addSelectionPath(javax.swing.tree.TreePath) ,public void addSelectionPaths(javax.swing.tree.TreePath[]) ,public void addSelectionRow(int) ,public void addSelectionRows(int[]) ,public void addTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void addTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void addTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void cancelEditing() ,public void clearSelection() ,public void collapsePath(javax.swing.tree.TreePath) ,public void collapseRow(int) ,public java.lang.String convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean) ,public void expandPath(javax.swing.tree.TreePath) ,public void expandRow(int) ,public void fireTreeCollapsed(javax.swing.tree.TreePath) ,public void fireTreeExpanded(javax.swing.tree.TreePath) ,public void fireTreeWillCollapse(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public void fireTreeWillExpand(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.tree.TreePath getAnchorSelectionPath() ,public javax.swing.tree.TreeCellEditor getCellEditor() ,public javax.swing.tree.TreeCellRenderer getCellRenderer() ,public javax.swing.tree.TreePath getClosestPathForLocation(int, int) ,public int getClosestRowForLocation(int, int) ,public boolean getDragEnabled() ,public final javax.swing.JTree.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public javax.swing.tree.TreePath getEditingPath() ,public Enumeration<javax.swing.tree.TreePath> getExpandedDescendants(javax.swing.tree.TreePath) ,public boolean getExpandsSelectedPaths() ,public boolean getInvokesStopCellEditing() ,public java.lang.Object getLastSelectedPathComponent() ,public javax.swing.tree.TreePath getLeadSelectionPath() ,public int getLeadSelectionRow() ,public int getMaxSelectionRow() ,public int getMinSelectionRow() ,public javax.swing.tree.TreeModel getModel() ,public javax.swing.tree.TreePath getNextMatch(java.lang.String, int, javax.swing.text.Position.Bias) ,public java.awt.Rectangle getPathBounds(javax.swing.tree.TreePath) ,public javax.swing.tree.TreePath getPathForLocation(int, int) ,public javax.swing.tree.TreePath getPathForRow(int) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.Rectangle getRowBounds(int) ,public int getRowCount() ,public int getRowForLocation(int, int) ,public int getRowForPath(javax.swing.tree.TreePath) ,public int getRowHeight() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollsOnExpand() ,public int getSelectionCount() ,public javax.swing.tree.TreeSelectionModel getSelectionModel() ,public javax.swing.tree.TreePath getSelectionPath() ,public javax.swing.tree.TreePath[] getSelectionPaths() ,public int[] getSelectionRows() ,public boolean getShowsRootHandles() ,public int getToggleClickCount() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.event.TreeExpansionListener[] getTreeExpansionListeners() ,public javax.swing.event.TreeSelectionListener[] getTreeSelectionListeners() ,public javax.swing.event.TreeWillExpandListener[] getTreeWillExpandListeners() ,public javax.swing.plaf.TreeUI getUI() ,public java.lang.String getUIClassID() ,public int getVisibleRowCount() ,public boolean hasBeenExpanded(javax.swing.tree.TreePath) ,public boolean isCollapsed(javax.swing.tree.TreePath) ,public boolean isCollapsed(int) ,public boolean isEditable() ,public boolean isEditing() ,public boolean isExpanded(javax.swing.tree.TreePath) ,public boolean isExpanded(int) ,public boolean isFixedRowHeight() ,public boolean isLargeModel() ,public boolean isPathEditable(javax.swing.tree.TreePath) ,public boolean isPathSelected(javax.swing.tree.TreePath) ,public boolean isRootVisible() ,public boolean isRowSelected(int) ,public boolean isSelectionEmpty() ,public boolean isVisible(javax.swing.tree.TreePath) ,public void makeVisible(javax.swing.tree.TreePath) ,public void removeSelectionInterval(int, int) ,public void removeSelectionPath(javax.swing.tree.TreePath) ,public void removeSelectionPaths(javax.swing.tree.TreePath[]) ,public void removeSelectionRow(int) ,public void removeSelectionRows(int[]) ,public void removeTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void removeTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void removeTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void scrollPathToVisible(javax.swing.tree.TreePath) ,public void scrollRowToVisible(int) ,public void setAnchorSelectionPath(javax.swing.tree.TreePath) ,public void setCellEditor(javax.swing.tree.TreeCellEditor) ,public void setCellRenderer(javax.swing.tree.TreeCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditable(boolean) ,public void setExpandsSelectedPaths(boolean) ,public void setInvokesStopCellEditing(boolean) ,public void setLargeModel(boolean) ,public void setLeadSelectionPath(javax.swing.tree.TreePath) ,public void setModel(javax.swing.tree.TreeModel) ,public void setRootVisible(boolean) ,public void setRowHeight(int) ,public void setScrollsOnExpand(boolean) ,public void setSelectionInterval(int, int) ,public void setSelectionModel(javax.swing.tree.TreeSelectionModel) ,public void setSelectionPath(javax.swing.tree.TreePath) ,public void setSelectionPaths(javax.swing.tree.TreePath[]) ,public void setSelectionRow(int) ,public void setSelectionRows(int[]) ,public void setShowsRootHandles(boolean) ,public void setToggleClickCount(int) ,public void setUI(javax.swing.plaf.TreeUI) ,public void setVisibleRowCount(int) ,public void startEditingAtPath(javax.swing.tree.TreePath) ,public boolean stopEditing() ,public void treeDidChange() ,public void updateUI() <variables>static final boolean $assertionsDisabled,public static final java.lang.String ANCHOR_SELECTION_PATH_PROPERTY,public static final java.lang.String CELL_EDITOR_PROPERTY,public static final java.lang.String CELL_RENDERER_PROPERTY,public static final java.lang.String EDITABLE_PROPERTY,public static final java.lang.String EXPANDS_SELECTED_PATHS_PROPERTY,public static final java.lang.String INVOKES_STOP_CELL_EDITING_PROPERTY,public static final java.lang.String LARGE_MODEL_PROPERTY,public static final java.lang.String LEAD_SELECTION_PATH_PROPERTY,public static final java.lang.String ROOT_VISIBLE_PROPERTY,public static final java.lang.String ROW_HEIGHT_PROPERTY,public static final java.lang.String SCROLLS_ON_EXPAND_PROPERTY,public static final java.lang.String SELECTION_MODEL_PROPERTY,public static final java.lang.String SHOWS_ROOT_HANDLES_PROPERTY,private static int TEMP_STACK_SIZE,public static final java.lang.String TOGGLE_CLICK_COUNT_PROPERTY,public static final java.lang.String TREE_MODEL_PROPERTY,public static final java.lang.String VISIBLE_ROW_COUNT_PROPERTY,private javax.swing.tree.TreePath anchorPath,protected transient javax.swing.tree.TreeCellEditor cellEditor,protected transient javax.swing.tree.TreeCellRenderer cellRenderer,private boolean dragEnabled,private transient javax.swing.JTree.DropLocation dropLocation,private javax.swing.DropMode dropMode,private javax.swing.JTree.TreeTimer dropTimer,protected boolean editable,private int expandRow,private transient Stack<Stack<javax.swing.tree.TreePath>> expandedStack,private transient Hashtable<javax.swing.tree.TreePath,java.lang.Boolean> expandedState,private boolean expandsSelectedPaths,protected boolean invokesStopCellEditing,protected boolean largeModel,private javax.swing.tree.TreePath leadPath,protected boolean rootVisible,protected int rowHeight,private boolean rowHeightSet,protected boolean scrollsOnExpand,private boolean scrollsOnExpandSet,protected transient javax.swing.tree.TreeSelectionModel selectionModel,protected transient javax.swing.JTree.TreeSelectionRedirector selectionRedirector,private boolean settingUI,protected boolean showsRootHandles,private boolean showsRootHandlesSet,protected int toggleClickCount,protected transient javax.swing.tree.TreeModel treeModel,protected transient javax.swing.event.TreeModelListener treeModelListener,private static final java.lang.String uiClassID,private transient javax.swing.event.TreeExpansionListener uiTreeExpansionListener,private transient boolean updateInProgress,protected int visibleRowCount
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/OutlineTree.java
|
OutlineTree
|
valueChanged
|
class OutlineTree extends JTree implements TreeSelectionListener, Observer {
/**
* A serial version uid.
*/
private static final long serialVersionUID = 5646572654823301007L;
/**
* Nodes in the FormTree correspond with nodes in the main PdfTree.
*/
protected PdfReaderController controller;
/**
* Creates a new outline tree.
*
* @param controller The renderer that will render an object when selected in the table.
*/
public OutlineTree(PdfReaderController controller) {
super();
this.controller = controller;
setCellRenderer(new IconTreeCellRenderer());
setModel(new DefaultTreeModel(new OutlineTreeNode()));
addTreeSelectionListener(this);
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {
if (obj == null) {
setModel(new DefaultTreeModel(new OutlineTreeNode()));
repaint();
return;
}
if (obj instanceof ObjectLoader) {
ObjectLoader loader = (ObjectLoader) obj;
TreeNodeFactory factory = loader.getNodes();
PdfTrailerTreeNode trailer = controller.getPdfTree().getRoot();
PdfObjectTreeNode catalog = factory.getChildNode(trailer, PdfName.ROOT);
PdfObjectTreeNode outline = factory.getChildNode(catalog, PdfName.OUTLINES);
if (outline == null) {
return;
}
OutlineTreeNode root = new OutlineTreeNode();
loadOutline(factory, root, factory.getChildNode(outline, PdfName.FIRST));
setModel(new DefaultTreeModel(root));
}
}
/**
* Method that can be used recursively to load the outline hierarchy into the tree.
*/
private void loadOutline(TreeNodeFactory factory, OutlineTreeNode parent, PdfObjectTreeNode child) {
OutlineTreeNode childnode = new OutlineTreeNode(child);
parent.add(childnode);
PdfObjectTreeNode first = factory.getChildNode(child, PdfName.FIRST);
if (first != null) {
loadOutline(factory, childnode, first);
}
PdfObjectTreeNode next = factory.getChildNode(child, PdfName.NEXT);
if (next != null) {
loadOutline(factory, parent, next);
}
}
/**
* @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
*/
public void valueChanged(TreeSelectionEvent evt) {<FILL_FUNCTION_BODY>}
}
|
if (controller == null) {
return;
}
OutlineTreeNode selectednode = (OutlineTreeNode) this.getLastSelectedPathComponent();
PdfObjectTreeNode node = selectednode.getCorrespondingPdfObjectNode();
if (node != null) {
controller.selectNode(node);
}
| 714
| 85
| 799
|
<methods>public void <init>() ,public void <init>(java.lang.Object[]) ,public void <init>(Vector<?>) ,public void <init>(Hashtable<?,?>) ,public void <init>(javax.swing.tree.TreeNode) ,public void <init>(javax.swing.tree.TreeModel) ,public void <init>(javax.swing.tree.TreeNode, boolean) ,public void addSelectionInterval(int, int) ,public void addSelectionPath(javax.swing.tree.TreePath) ,public void addSelectionPaths(javax.swing.tree.TreePath[]) ,public void addSelectionRow(int) ,public void addSelectionRows(int[]) ,public void addTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void addTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void addTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void cancelEditing() ,public void clearSelection() ,public void collapsePath(javax.swing.tree.TreePath) ,public void collapseRow(int) ,public java.lang.String convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean) ,public void expandPath(javax.swing.tree.TreePath) ,public void expandRow(int) ,public void fireTreeCollapsed(javax.swing.tree.TreePath) ,public void fireTreeExpanded(javax.swing.tree.TreePath) ,public void fireTreeWillCollapse(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public void fireTreeWillExpand(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.tree.TreePath getAnchorSelectionPath() ,public javax.swing.tree.TreeCellEditor getCellEditor() ,public javax.swing.tree.TreeCellRenderer getCellRenderer() ,public javax.swing.tree.TreePath getClosestPathForLocation(int, int) ,public int getClosestRowForLocation(int, int) ,public boolean getDragEnabled() ,public final javax.swing.JTree.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public javax.swing.tree.TreePath getEditingPath() ,public Enumeration<javax.swing.tree.TreePath> getExpandedDescendants(javax.swing.tree.TreePath) ,public boolean getExpandsSelectedPaths() ,public boolean getInvokesStopCellEditing() ,public java.lang.Object getLastSelectedPathComponent() ,public javax.swing.tree.TreePath getLeadSelectionPath() ,public int getLeadSelectionRow() ,public int getMaxSelectionRow() ,public int getMinSelectionRow() ,public javax.swing.tree.TreeModel getModel() ,public javax.swing.tree.TreePath getNextMatch(java.lang.String, int, javax.swing.text.Position.Bias) ,public java.awt.Rectangle getPathBounds(javax.swing.tree.TreePath) ,public javax.swing.tree.TreePath getPathForLocation(int, int) ,public javax.swing.tree.TreePath getPathForRow(int) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.Rectangle getRowBounds(int) ,public int getRowCount() ,public int getRowForLocation(int, int) ,public int getRowForPath(javax.swing.tree.TreePath) ,public int getRowHeight() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollsOnExpand() ,public int getSelectionCount() ,public javax.swing.tree.TreeSelectionModel getSelectionModel() ,public javax.swing.tree.TreePath getSelectionPath() ,public javax.swing.tree.TreePath[] getSelectionPaths() ,public int[] getSelectionRows() ,public boolean getShowsRootHandles() ,public int getToggleClickCount() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.event.TreeExpansionListener[] getTreeExpansionListeners() ,public javax.swing.event.TreeSelectionListener[] getTreeSelectionListeners() ,public javax.swing.event.TreeWillExpandListener[] getTreeWillExpandListeners() ,public javax.swing.plaf.TreeUI getUI() ,public java.lang.String getUIClassID() ,public int getVisibleRowCount() ,public boolean hasBeenExpanded(javax.swing.tree.TreePath) ,public boolean isCollapsed(javax.swing.tree.TreePath) ,public boolean isCollapsed(int) ,public boolean isEditable() ,public boolean isEditing() ,public boolean isExpanded(javax.swing.tree.TreePath) ,public boolean isExpanded(int) ,public boolean isFixedRowHeight() ,public boolean isLargeModel() ,public boolean isPathEditable(javax.swing.tree.TreePath) ,public boolean isPathSelected(javax.swing.tree.TreePath) ,public boolean isRootVisible() ,public boolean isRowSelected(int) ,public boolean isSelectionEmpty() ,public boolean isVisible(javax.swing.tree.TreePath) ,public void makeVisible(javax.swing.tree.TreePath) ,public void removeSelectionInterval(int, int) ,public void removeSelectionPath(javax.swing.tree.TreePath) ,public void removeSelectionPaths(javax.swing.tree.TreePath[]) ,public void removeSelectionRow(int) ,public void removeSelectionRows(int[]) ,public void removeTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void removeTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void removeTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void scrollPathToVisible(javax.swing.tree.TreePath) ,public void scrollRowToVisible(int) ,public void setAnchorSelectionPath(javax.swing.tree.TreePath) ,public void setCellEditor(javax.swing.tree.TreeCellEditor) ,public void setCellRenderer(javax.swing.tree.TreeCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditable(boolean) ,public void setExpandsSelectedPaths(boolean) ,public void setInvokesStopCellEditing(boolean) ,public void setLargeModel(boolean) ,public void setLeadSelectionPath(javax.swing.tree.TreePath) ,public void setModel(javax.swing.tree.TreeModel) ,public void setRootVisible(boolean) ,public void setRowHeight(int) ,public void setScrollsOnExpand(boolean) ,public void setSelectionInterval(int, int) ,public void setSelectionModel(javax.swing.tree.TreeSelectionModel) ,public void setSelectionPath(javax.swing.tree.TreePath) ,public void setSelectionPaths(javax.swing.tree.TreePath[]) ,public void setSelectionRow(int) ,public void setSelectionRows(int[]) ,public void setShowsRootHandles(boolean) ,public void setToggleClickCount(int) ,public void setUI(javax.swing.plaf.TreeUI) ,public void setVisibleRowCount(int) ,public void startEditingAtPath(javax.swing.tree.TreePath) ,public boolean stopEditing() ,public void treeDidChange() ,public void updateUI() <variables>static final boolean $assertionsDisabled,public static final java.lang.String ANCHOR_SELECTION_PATH_PROPERTY,public static final java.lang.String CELL_EDITOR_PROPERTY,public static final java.lang.String CELL_RENDERER_PROPERTY,public static final java.lang.String EDITABLE_PROPERTY,public static final java.lang.String EXPANDS_SELECTED_PATHS_PROPERTY,public static final java.lang.String INVOKES_STOP_CELL_EDITING_PROPERTY,public static final java.lang.String LARGE_MODEL_PROPERTY,public static final java.lang.String LEAD_SELECTION_PATH_PROPERTY,public static final java.lang.String ROOT_VISIBLE_PROPERTY,public static final java.lang.String ROW_HEIGHT_PROPERTY,public static final java.lang.String SCROLLS_ON_EXPAND_PROPERTY,public static final java.lang.String SELECTION_MODEL_PROPERTY,public static final java.lang.String SHOWS_ROOT_HANDLES_PROPERTY,private static int TEMP_STACK_SIZE,public static final java.lang.String TOGGLE_CLICK_COUNT_PROPERTY,public static final java.lang.String TREE_MODEL_PROPERTY,public static final java.lang.String VISIBLE_ROW_COUNT_PROPERTY,private javax.swing.tree.TreePath anchorPath,protected transient javax.swing.tree.TreeCellEditor cellEditor,protected transient javax.swing.tree.TreeCellRenderer cellRenderer,private boolean dragEnabled,private transient javax.swing.JTree.DropLocation dropLocation,private javax.swing.DropMode dropMode,private javax.swing.JTree.TreeTimer dropTimer,protected boolean editable,private int expandRow,private transient Stack<Stack<javax.swing.tree.TreePath>> expandedStack,private transient Hashtable<javax.swing.tree.TreePath,java.lang.Boolean> expandedState,private boolean expandsSelectedPaths,protected boolean invokesStopCellEditing,protected boolean largeModel,private javax.swing.tree.TreePath leadPath,protected boolean rootVisible,protected int rowHeight,private boolean rowHeightSet,protected boolean scrollsOnExpand,private boolean scrollsOnExpandSet,protected transient javax.swing.tree.TreeSelectionModel selectionModel,protected transient javax.swing.JTree.TreeSelectionRedirector selectionRedirector,private boolean settingUI,protected boolean showsRootHandles,private boolean showsRootHandlesSet,protected int toggleClickCount,protected transient javax.swing.tree.TreeModel treeModel,protected transient javax.swing.event.TreeModelListener treeModelListener,private static final java.lang.String uiClassID,private transient javax.swing.event.TreeExpansionListener uiTreeExpansionListener,private transient boolean updateInProgress,protected int visibleRowCount
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/PagesTable.java
|
PagesTable
|
update
|
class PagesTable extends JTable implements JTableAutoModelInterface, Observer {
/**
* A serial version UID.
*/
private static final long serialVersionUID = -6523261089453886508L;
/**
* A list with page nodes.
*/
protected ArrayList<PdfPageTreeNode> list = new ArrayList<>();
/**
* Nodes in the FormTree correspond with nodes in the main PdfTree.
*/
protected PdfReaderController controller;
/***/
protected PageSelectionListener listener;
/**
* Constructs a PagesTable.
*
* @param listener the page navigation listener.
* @param controller The renderer that will render an object when selected in the table.
*/
public PagesTable(PdfReaderController controller, PageSelectionListener listener) {
this.controller = controller;
this.listener = listener;
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
/**
* @see javax.swing.JTable#getColumnCount()
*/
public int getColumnCount() {
return 2;
}
/**
* @see javax.swing.JTable#getRowCount()
*/
public int getRowCount() {
return list.size();
}
/**
* @see javax.swing.JTable#getValueAt(int, int)
*/
public Object getValueAt(int rowIndex, int columnIndex) {
if (getRowCount() == 0) {
return null;
}
switch (columnIndex) {
case 0:
return "Object " + list.get(rowIndex).getNumber();
case 1:
return list.get(rowIndex);
}
return null;
}
/**
* @see javax.swing.JTable#getColumnName(int)
*/
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Object";
case 1:
return "Page";
default:
return null;
}
}
/**
* @see javax.swing.JTable#valueChanged(javax.swing.event.ListSelectionEvent)
*/
@Override
public void valueChanged(ListSelectionEvent evt) {
if (evt != null) {
super.valueChanged(evt);
}
if (controller == null) {
return;
}
if (getRowCount() > 0) {
controller.selectNode(list.get(getSelectedRow()));
if (listener != null) {
listener.gotoPage(getSelectedRow() + 1);
}
}
}
}
|
if (obj == null) {
list = new ArrayList<>();
repaint();
return;
}
if (obj instanceof ObjectLoader) {
ObjectLoader loader = (ObjectLoader) obj;
String[] pagelabels = PdfPageLabels.getPageLabels(loader.getReader());
int i = 0;
TreeNodeFactory factory = loader.getNodes();
PdfTrailerTreeNode trailer = controller.getPdfTree().getRoot();
PdfObjectTreeNode catalog = factory.getChildNode(trailer, PdfName.ROOT);
PdfPagesTreeNode pages = (PdfPagesTreeNode) factory.getChildNode(catalog, PdfName.PAGES);
if (pages == null) {
return;
}
Enumeration p = pages.depthFirstEnumeration();
PdfObjectTreeNode child;
StringBuffer buf;
while (p.hasMoreElements()) {
child = (PdfObjectTreeNode) p.nextElement();
if (child instanceof PdfPageTreeNode) {
buf = new StringBuffer("Page ");
buf.append(++i);
if (pagelabels != null) {
buf.append(" ( ");
buf.append(pagelabels[i - 1]);
buf.append(" )");
}
child.setUserObject(buf.toString());
list.add((PdfPageTreeNode) child);
}
}
}
setModel(new JTableAutoModel(this));
| 735
| 377
| 1,112
|
<methods>public void <init>() ,public void <init>(javax.swing.table.TableModel) ,public void <init>(javax.swing.table.TableModel, javax.swing.table.TableColumnModel) ,public void <init>(int, int) ,public void <init>(Vector<? extends Vector#RAW>, Vector<?>) ,public void <init>(java.lang.Object[][], java.lang.Object[]) ,public void <init>(javax.swing.table.TableModel, javax.swing.table.TableColumnModel, javax.swing.ListSelectionModel) ,public void addColumn(javax.swing.table.TableColumn) ,public void addColumnSelectionInterval(int, int) ,public void addNotify() ,public void addRowSelectionInterval(int, int) ,public void changeSelection(int, int, boolean, boolean) ,public void clearSelection() ,public void columnAdded(javax.swing.event.TableColumnModelEvent) ,public int columnAtPoint(java.awt.Point) ,public void columnMarginChanged(javax.swing.event.ChangeEvent) ,public void columnMoved(javax.swing.event.TableColumnModelEvent) ,public void columnRemoved(javax.swing.event.TableColumnModelEvent) ,public void columnSelectionChanged(javax.swing.event.ListSelectionEvent) ,public int convertColumnIndexToModel(int) ,public int convertColumnIndexToView(int) ,public int convertRowIndexToModel(int) ,public int convertRowIndexToView(int) ,public void createDefaultColumnsFromModel() ,public static javax.swing.JScrollPane createScrollPaneForTable(javax.swing.JTable) ,public void doLayout() ,public boolean editCellAt(int, int) ,public boolean editCellAt(int, int, java.util.EventObject) ,public void editingCanceled(javax.swing.event.ChangeEvent) ,public void editingStopped(javax.swing.event.ChangeEvent) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public boolean getAutoCreateColumnsFromModel() ,public boolean getAutoCreateRowSorter() ,public int getAutoResizeMode() ,public javax.swing.table.TableCellEditor getCellEditor() ,public javax.swing.table.TableCellEditor getCellEditor(int, int) ,public java.awt.Rectangle getCellRect(int, int, boolean) ,public javax.swing.table.TableCellRenderer getCellRenderer(int, int) ,public boolean getCellSelectionEnabled() ,public javax.swing.table.TableColumn getColumn(java.lang.Object) ,public Class<?> getColumnClass(int) ,public int getColumnCount() ,public javax.swing.table.TableColumnModel getColumnModel() ,public java.lang.String getColumnName(int) ,public boolean getColumnSelectionAllowed() ,public javax.swing.table.TableCellEditor getDefaultEditor(Class<?>) ,public javax.swing.table.TableCellRenderer getDefaultRenderer(Class<?>) ,public boolean getDragEnabled() ,public final javax.swing.JTable.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public int getEditingColumn() ,public int getEditingRow() ,public java.awt.Component getEditorComponent() ,public boolean getFillsViewportHeight() ,public java.awt.Color getGridColor() ,public java.awt.Dimension getIntercellSpacing() ,public javax.swing.table.TableModel getModel() ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.print.Printable getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) ,public int getRowCount() ,public int getRowHeight() ,public int getRowHeight(int) ,public int getRowMargin() ,public boolean getRowSelectionAllowed() ,public RowSorter<? extends javax.swing.table.TableModel> getRowSorter() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public int getSelectedColumn() ,public int getSelectedColumnCount() ,public int[] getSelectedColumns() ,public int getSelectedRow() ,public int getSelectedRowCount() ,public int[] getSelectedRows() ,public java.awt.Color getSelectionBackground() ,public java.awt.Color getSelectionForeground() ,public javax.swing.ListSelectionModel getSelectionModel() ,public boolean getShowHorizontalLines() ,public boolean getShowVerticalLines() ,public boolean getSurrendersFocusOnKeystroke() ,public javax.swing.table.JTableHeader getTableHeader() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.plaf.TableUI getUI() ,public java.lang.String getUIClassID() ,public boolean getUpdateSelectionOnSort() ,public java.lang.Object getValueAt(int, int) ,public boolean isCellEditable(int, int) ,public boolean isCellSelected(int, int) ,public boolean isColumnSelected(int) ,public boolean isEditing() ,public boolean isRowSelected(int) ,public void moveColumn(int, int) ,public java.awt.Component prepareEditor(javax.swing.table.TableCellEditor, int, int) ,public java.awt.Component prepareRenderer(javax.swing.table.TableCellRenderer, int, int) ,public boolean print() throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode) throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat, boolean, javax.print.attribute.PrintRequestAttributeSet, boolean) throws java.awt.print.PrinterException, java.awt.HeadlessException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat, boolean, javax.print.attribute.PrintRequestAttributeSet, boolean, javax.print.PrintService) throws java.awt.print.PrinterException, java.awt.HeadlessException,public void removeColumn(javax.swing.table.TableColumn) ,public void removeColumnSelectionInterval(int, int) ,public void removeEditor() ,public void removeNotify() ,public void removeRowSelectionInterval(int, int) ,public int rowAtPoint(java.awt.Point) ,public void selectAll() ,public void setAutoCreateColumnsFromModel(boolean) ,public void setAutoCreateRowSorter(boolean) ,public void setAutoResizeMode(int) ,public void setCellEditor(javax.swing.table.TableCellEditor) ,public void setCellSelectionEnabled(boolean) ,public void setColumnModel(javax.swing.table.TableColumnModel) ,public void setColumnSelectionAllowed(boolean) ,public void setColumnSelectionInterval(int, int) ,public void setDefaultEditor(Class<?>, javax.swing.table.TableCellEditor) ,public void setDefaultRenderer(Class<?>, javax.swing.table.TableCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditingColumn(int) ,public void setEditingRow(int) ,public void setFillsViewportHeight(boolean) ,public void setGridColor(java.awt.Color) ,public void setIntercellSpacing(java.awt.Dimension) ,public void setModel(javax.swing.table.TableModel) ,public void setPreferredScrollableViewportSize(java.awt.Dimension) ,public void setRowHeight(int) ,public void setRowHeight(int, int) ,public void setRowMargin(int) ,public void setRowSelectionAllowed(boolean) ,public void setRowSelectionInterval(int, int) ,public void setRowSorter(RowSorter<? extends javax.swing.table.TableModel>) ,public void setSelectionBackground(java.awt.Color) ,public void setSelectionForeground(java.awt.Color) ,public void setSelectionMode(int) ,public void setSelectionModel(javax.swing.ListSelectionModel) ,public void setShowGrid(boolean) ,public void setShowHorizontalLines(boolean) ,public void setShowVerticalLines(boolean) ,public void setSurrendersFocusOnKeystroke(boolean) ,public void setTableHeader(javax.swing.table.JTableHeader) ,public void setUI(javax.swing.plaf.TableUI) ,public void setUpdateSelectionOnSort(boolean) ,public void setValueAt(java.lang.Object, int, int) ,public void sizeColumnsToFit(boolean) ,public void sizeColumnsToFit(int) ,public void sorterChanged(javax.swing.event.RowSorterEvent) ,public void tableChanged(javax.swing.event.TableModelEvent) ,public void updateUI() ,public void valueChanged(javax.swing.event.ListSelectionEvent) <variables>static final boolean $assertionsDisabled,public static final int AUTO_RESIZE_ALL_COLUMNS,public static final int AUTO_RESIZE_LAST_COLUMN,public static final int AUTO_RESIZE_NEXT_COLUMN,public static final int AUTO_RESIZE_OFF,public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNS,protected boolean autoCreateColumnsFromModel,private boolean autoCreateRowSorter,protected int autoResizeMode,protected transient javax.swing.table.TableCellEditor cellEditor,protected boolean cellSelectionEnabled,protected javax.swing.table.TableColumnModel columnModel,private boolean columnSelectionAdjusting,protected javax.swing.table.TableModel dataModel,protected transient Hashtable<java.lang.Object,java.lang.Object> defaultEditorsByColumnClass,protected transient Hashtable<java.lang.Object,java.lang.Object> defaultRenderersByColumnClass,private boolean dragEnabled,private transient javax.swing.JTable.DropLocation dropLocation,private javax.swing.DropMode dropMode,protected transient int editingColumn,protected transient int editingRow,protected transient java.awt.Component editorComp,private java.beans.PropertyChangeListener editorRemover,private boolean fillsViewportHeight,protected java.awt.Color gridColor,private boolean ignoreSortChange,private boolean isRowHeightSet,protected java.awt.Dimension preferredViewportSize,private java.lang.Throwable printError,protected int rowHeight,protected int rowMargin,private javax.swing.SizeSequence rowModel,private boolean rowSelectionAdjusting,protected boolean rowSelectionAllowed,protected java.awt.Color selectionBackground,protected java.awt.Color selectionForeground,protected javax.swing.ListSelectionModel selectionModel,protected boolean showHorizontalLines,protected boolean showVerticalLines,private transient javax.swing.JTable.SortManager sortManager,private boolean sorterChanged,private boolean surrendersFocusOnKeystroke,protected javax.swing.table.JTableHeader tableHeader,private static final java.lang.String uiClassID,private transient boolean updateInProgress,private boolean updateSelectionOnSort
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/PdfObjectPanel.java
|
PdfObjectPanel
|
render
|
class PdfObjectPanel extends JPanel implements Observer {
/**
* Name of a panel in the CardLayout.
*/
private static final String TEXT = "text";
/**
* Name of a panel in the CardLayout.
*/
private static final String TABLE = "table";
/**
* a serial version id.
*/
private static final long serialVersionUID = 1302283071087762494L;
/**
* The layout that will show the info about the PDF object that is being analyzed.
*/
protected CardLayout layout = new CardLayout();
/**
* Table with dictionary entries.
*/
JTable table = new JTable();
/**
* The text pane with the info about a PDF object in the bottom panel.
*/
JTextArea text = new JTextArea();
/**
* Creates a PDF object panel.
*/
public PdfObjectPanel() {
// layout
setLayout(layout);
// dictionary / array / stream
JScrollPane dict_scrollpane = new JScrollPane();
dict_scrollpane.setViewportView(table);
add(dict_scrollpane, TABLE);
// number / string / ...
JScrollPane text_scrollpane = new JScrollPane();
text_scrollpane.setViewportView(text);
add(text_scrollpane, TEXT);
}
/**
* Clear the object panel.
*/
public void clear() {
text.setText(null);
layout.show(this, TEXT);
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {
clear();
}
/**
* Shows a PdfObject as text or in a table.
*
* @param object the object that needs to be shown.
*/
public void render(PdfObject object) {<FILL_FUNCTION_BODY>}
}
|
if (object == null) {
text.setText(null);
layout.show(this, TEXT);
this.repaint();
text.repaint();
return;
}
switch (object.type()) {
case PdfObject.DICTIONARY:
case PdfObject.STREAM:
table.setModel(new DictionaryTableModel((PdfDictionary) object));
layout.show(this, TABLE);
this.repaint();
break;
case PdfObject.ARRAY:
table.setModel(new PdfArrayTableModel((PdfArray) object));
layout.show(this, TABLE);
this.repaint();
break;
default:
text.setText(object.toString());
layout.show(this, TEXT);
break;
}
| 525
| 205
| 730
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/PdfTree.java
|
PdfTree
|
update
|
class PdfTree extends JTree implements Observer {
/**
* a serial version UID
*/
private static final long serialVersionUID = 7545804447512085734L;
/**
* The root of the PDF tree.
*/
protected PdfTrailerTreeNode root;
/**
* Constructs a PDF tree.
*/
public PdfTree() {
super();
root = new PdfTrailerTreeNode();
setCellRenderer(new IconTreeCellRenderer());
update(null, null);
}
/**
* Getter for the root node
*
* @return the PDF Trailer node
*/
public PdfTrailerTreeNode getRoot() {
return root;
}
/**
* Updates the PdfTree when a file is closed or when a ObjectLoader has finished loading objects.
*
* @param observable the Observable class that started the update
* @param obj the object that has all the updates
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
/**
* Select a specific node in the tree. Typically this method will be called from a different tree, such as the
* pages, outlines or form tree.
*
* @param node the node that has to be selected
*/
public void selectNode(PdfObjectTreeNode node) {
TreePath path = new TreePath(node.getPath());
setSelectionPath(path);
scrollPathToVisible(path);
}
}
|
if (obj == null) {
root = new PdfTrailerTreeNode();
}
setModel(new DefaultTreeModel(root));
repaint();
| 426
| 44
| 470
|
<methods>public void <init>() ,public void <init>(java.lang.Object[]) ,public void <init>(Vector<?>) ,public void <init>(Hashtable<?,?>) ,public void <init>(javax.swing.tree.TreeNode) ,public void <init>(javax.swing.tree.TreeModel) ,public void <init>(javax.swing.tree.TreeNode, boolean) ,public void addSelectionInterval(int, int) ,public void addSelectionPath(javax.swing.tree.TreePath) ,public void addSelectionPaths(javax.swing.tree.TreePath[]) ,public void addSelectionRow(int) ,public void addSelectionRows(int[]) ,public void addTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void addTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void addTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void cancelEditing() ,public void clearSelection() ,public void collapsePath(javax.swing.tree.TreePath) ,public void collapseRow(int) ,public java.lang.String convertValueToText(java.lang.Object, boolean, boolean, boolean, int, boolean) ,public void expandPath(javax.swing.tree.TreePath) ,public void expandRow(int) ,public void fireTreeCollapsed(javax.swing.tree.TreePath) ,public void fireTreeExpanded(javax.swing.tree.TreePath) ,public void fireTreeWillCollapse(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public void fireTreeWillExpand(javax.swing.tree.TreePath) throws javax.swing.tree.ExpandVetoException,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.tree.TreePath getAnchorSelectionPath() ,public javax.swing.tree.TreeCellEditor getCellEditor() ,public javax.swing.tree.TreeCellRenderer getCellRenderer() ,public javax.swing.tree.TreePath getClosestPathForLocation(int, int) ,public int getClosestRowForLocation(int, int) ,public boolean getDragEnabled() ,public final javax.swing.JTree.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public javax.swing.tree.TreePath getEditingPath() ,public Enumeration<javax.swing.tree.TreePath> getExpandedDescendants(javax.swing.tree.TreePath) ,public boolean getExpandsSelectedPaths() ,public boolean getInvokesStopCellEditing() ,public java.lang.Object getLastSelectedPathComponent() ,public javax.swing.tree.TreePath getLeadSelectionPath() ,public int getLeadSelectionRow() ,public int getMaxSelectionRow() ,public int getMinSelectionRow() ,public javax.swing.tree.TreeModel getModel() ,public javax.swing.tree.TreePath getNextMatch(java.lang.String, int, javax.swing.text.Position.Bias) ,public java.awt.Rectangle getPathBounds(javax.swing.tree.TreePath) ,public javax.swing.tree.TreePath getPathForLocation(int, int) ,public javax.swing.tree.TreePath getPathForRow(int) ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.Rectangle getRowBounds(int) ,public int getRowCount() ,public int getRowForLocation(int, int) ,public int getRowForPath(javax.swing.tree.TreePath) ,public int getRowHeight() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollsOnExpand() ,public int getSelectionCount() ,public javax.swing.tree.TreeSelectionModel getSelectionModel() ,public javax.swing.tree.TreePath getSelectionPath() ,public javax.swing.tree.TreePath[] getSelectionPaths() ,public int[] getSelectionRows() ,public boolean getShowsRootHandles() ,public int getToggleClickCount() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.event.TreeExpansionListener[] getTreeExpansionListeners() ,public javax.swing.event.TreeSelectionListener[] getTreeSelectionListeners() ,public javax.swing.event.TreeWillExpandListener[] getTreeWillExpandListeners() ,public javax.swing.plaf.TreeUI getUI() ,public java.lang.String getUIClassID() ,public int getVisibleRowCount() ,public boolean hasBeenExpanded(javax.swing.tree.TreePath) ,public boolean isCollapsed(javax.swing.tree.TreePath) ,public boolean isCollapsed(int) ,public boolean isEditable() ,public boolean isEditing() ,public boolean isExpanded(javax.swing.tree.TreePath) ,public boolean isExpanded(int) ,public boolean isFixedRowHeight() ,public boolean isLargeModel() ,public boolean isPathEditable(javax.swing.tree.TreePath) ,public boolean isPathSelected(javax.swing.tree.TreePath) ,public boolean isRootVisible() ,public boolean isRowSelected(int) ,public boolean isSelectionEmpty() ,public boolean isVisible(javax.swing.tree.TreePath) ,public void makeVisible(javax.swing.tree.TreePath) ,public void removeSelectionInterval(int, int) ,public void removeSelectionPath(javax.swing.tree.TreePath) ,public void removeSelectionPaths(javax.swing.tree.TreePath[]) ,public void removeSelectionRow(int) ,public void removeSelectionRows(int[]) ,public void removeTreeExpansionListener(javax.swing.event.TreeExpansionListener) ,public void removeTreeSelectionListener(javax.swing.event.TreeSelectionListener) ,public void removeTreeWillExpandListener(javax.swing.event.TreeWillExpandListener) ,public void scrollPathToVisible(javax.swing.tree.TreePath) ,public void scrollRowToVisible(int) ,public void setAnchorSelectionPath(javax.swing.tree.TreePath) ,public void setCellEditor(javax.swing.tree.TreeCellEditor) ,public void setCellRenderer(javax.swing.tree.TreeCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditable(boolean) ,public void setExpandsSelectedPaths(boolean) ,public void setInvokesStopCellEditing(boolean) ,public void setLargeModel(boolean) ,public void setLeadSelectionPath(javax.swing.tree.TreePath) ,public void setModel(javax.swing.tree.TreeModel) ,public void setRootVisible(boolean) ,public void setRowHeight(int) ,public void setScrollsOnExpand(boolean) ,public void setSelectionInterval(int, int) ,public void setSelectionModel(javax.swing.tree.TreeSelectionModel) ,public void setSelectionPath(javax.swing.tree.TreePath) ,public void setSelectionPaths(javax.swing.tree.TreePath[]) ,public void setSelectionRow(int) ,public void setSelectionRows(int[]) ,public void setShowsRootHandles(boolean) ,public void setToggleClickCount(int) ,public void setUI(javax.swing.plaf.TreeUI) ,public void setVisibleRowCount(int) ,public void startEditingAtPath(javax.swing.tree.TreePath) ,public boolean stopEditing() ,public void treeDidChange() ,public void updateUI() <variables>static final boolean $assertionsDisabled,public static final java.lang.String ANCHOR_SELECTION_PATH_PROPERTY,public static final java.lang.String CELL_EDITOR_PROPERTY,public static final java.lang.String CELL_RENDERER_PROPERTY,public static final java.lang.String EDITABLE_PROPERTY,public static final java.lang.String EXPANDS_SELECTED_PATHS_PROPERTY,public static final java.lang.String INVOKES_STOP_CELL_EDITING_PROPERTY,public static final java.lang.String LARGE_MODEL_PROPERTY,public static final java.lang.String LEAD_SELECTION_PATH_PROPERTY,public static final java.lang.String ROOT_VISIBLE_PROPERTY,public static final java.lang.String ROW_HEIGHT_PROPERTY,public static final java.lang.String SCROLLS_ON_EXPAND_PROPERTY,public static final java.lang.String SELECTION_MODEL_PROPERTY,public static final java.lang.String SHOWS_ROOT_HANDLES_PROPERTY,private static int TEMP_STACK_SIZE,public static final java.lang.String TOGGLE_CLICK_COUNT_PROPERTY,public static final java.lang.String TREE_MODEL_PROPERTY,public static final java.lang.String VISIBLE_ROW_COUNT_PROPERTY,private javax.swing.tree.TreePath anchorPath,protected transient javax.swing.tree.TreeCellEditor cellEditor,protected transient javax.swing.tree.TreeCellRenderer cellRenderer,private boolean dragEnabled,private transient javax.swing.JTree.DropLocation dropLocation,private javax.swing.DropMode dropMode,private javax.swing.JTree.TreeTimer dropTimer,protected boolean editable,private int expandRow,private transient Stack<Stack<javax.swing.tree.TreePath>> expandedStack,private transient Hashtable<javax.swing.tree.TreePath,java.lang.Boolean> expandedState,private boolean expandsSelectedPaths,protected boolean invokesStopCellEditing,protected boolean largeModel,private javax.swing.tree.TreePath leadPath,protected boolean rootVisible,protected int rowHeight,private boolean rowHeightSet,protected boolean scrollsOnExpand,private boolean scrollsOnExpandSet,protected transient javax.swing.tree.TreeSelectionModel selectionModel,protected transient javax.swing.JTree.TreeSelectionRedirector selectionRedirector,private boolean settingUI,protected boolean showsRootHandles,private boolean showsRootHandlesSet,protected int toggleClickCount,protected transient javax.swing.tree.TreeModel treeModel,protected transient javax.swing.event.TreeModelListener treeModelListener,private static final java.lang.String uiClassID,private transient javax.swing.event.TreeExpansionListener uiTreeExpansionListener,private transient boolean updateInProgress,protected int visibleRowCount
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/StreamTextArea.java
|
StreamTextArea
|
render
|
class StreamTextArea extends JScrollPane implements Observer {
/**
* a serial version id.
*/
private static final long serialVersionUID = 1302283071087762494L;
/**
* The text area with the content stream.
*/
protected JTextArea text;
/**
* Constructs a StreamTextArea.
*/
public StreamTextArea() {
super();
text = new JTextArea();
setViewportView(text);
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {
text.setText(null);
}
/**
* Renders the content stream of a PdfObject or empties the text area.
*
* @param object the object of which the content stream needs to be rendered
*/
public void render(PdfObject object) {<FILL_FUNCTION_BODY>}
}
|
if (object instanceof PRStream) {
PRStream stream = (PRStream) object;
try {
TextAreaOutputStream taos = new TextAreaOutputStream(text);
taos.write(PdfReader.getStreamBytes(stream));
//text.addMouseListener(new StreamEditorAction(stream));
} catch (IOException e) {
text.setText("The stream could not be read: " + e.getMessage());
}
} else {
update(null, null);
return;
}
text.repaint();
repaint();
| 267
| 140
| 407
|
<methods>public void <init>() ,public void <init>(java.awt.Component) ,public void <init>(int, int) ,public void <init>(java.awt.Component, int, int) ,public javax.swing.JScrollBar createHorizontalScrollBar() ,public javax.swing.JScrollBar createVerticalScrollBar() ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.JViewport getColumnHeader() ,public java.awt.Component getCorner(java.lang.String) ,public javax.swing.JScrollBar getHorizontalScrollBar() ,public int getHorizontalScrollBarPolicy() ,public javax.swing.JViewport getRowHeader() ,public javax.swing.plaf.ScrollPaneUI getUI() ,public java.lang.String getUIClassID() ,public javax.swing.JScrollBar getVerticalScrollBar() ,public int getVerticalScrollBarPolicy() ,public javax.swing.JViewport getViewport() ,public javax.swing.border.Border getViewportBorder() ,public java.awt.Rectangle getViewportBorderBounds() ,public boolean isValidateRoot() ,public boolean isWheelScrollingEnabled() ,public void setColumnHeader(javax.swing.JViewport) ,public void setColumnHeaderView(java.awt.Component) ,public void setComponentOrientation(java.awt.ComponentOrientation) ,public void setCorner(java.lang.String, java.awt.Component) ,public void setHorizontalScrollBar(javax.swing.JScrollBar) ,public void setHorizontalScrollBarPolicy(int) ,public void setLayout(java.awt.LayoutManager) ,public void setRowHeader(javax.swing.JViewport) ,public void setRowHeaderView(java.awt.Component) ,public void setUI(javax.swing.plaf.ScrollPaneUI) ,public void setVerticalScrollBar(javax.swing.JScrollBar) ,public void setVerticalScrollBarPolicy(int) ,public void setViewport(javax.swing.JViewport) ,public void setViewportBorder(javax.swing.border.Border) ,public void setViewportView(java.awt.Component) ,public void setWheelScrollingEnabled(boolean) ,public void updateUI() <variables>protected javax.swing.JViewport columnHeader,protected javax.swing.JScrollBar horizontalScrollBar,protected int horizontalScrollBarPolicy,protected java.awt.Component lowerLeft,protected java.awt.Component lowerRight,protected javax.swing.JViewport rowHeader,private static final java.lang.String uiClassID,protected java.awt.Component upperLeft,protected java.awt.Component upperRight,protected javax.swing.JScrollBar verticalScrollBar,protected int verticalScrollBarPolicy,protected javax.swing.JViewport viewport,private javax.swing.border.Border viewportBorder,private boolean wheelScrollState
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/XRefTable.java
|
XRefTable
|
update
|
class XRefTable extends JTable implements JTableAutoModelInterface, Observer {
/**
* A serial version UID.
*/
private static final long serialVersionUID = -382184619041375537L;
/**
* The factory that can produce all the indirect objects.
*/
protected IndirectObjectFactory objects;
/**
* The renderer that will render an object when selected in the table.
*/
protected PdfReaderController controller;
/**
* Creates a JTable visualizing xref table.
*
* @param controller The renderer that will render an object when selected in the table.
*/
public XRefTable(PdfReaderController controller) {
super();
this.controller = controller;
}
/**
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void update(Observable observable, Object obj) {<FILL_FUNCTION_BODY>}
/**
* @see javax.swing.JTable#getColumnCount()
*/
public int getColumnCount() {
return 2;
}
/**
* @see javax.swing.JTable#getRowCount()
*/
public int getRowCount() {
if (objects == null) {
return 0;
}
return objects.size();
}
/**
* @see javax.swing.JTable#getValueAt(int, int)
*/
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return getObjectReferenceByRow(rowIndex);
case 1:
return getObjectDescriptionByRow(rowIndex);
default:
return null;
}
}
/**
* Gets the reference number of an indirect object based on the row index.
*
* @param rowIndex a row number
* @return a reference number
*/
protected int getObjectReferenceByRow(int rowIndex) {
return objects.getRefByIndex(rowIndex);
}
/**
* Gets the object that is shown in a row.
*
* @param rowIndex the row number containing the object
* @return a PDF object
*/
protected String getObjectDescriptionByRow(int rowIndex) {
PdfObject object = objects.getObjectByIndex(rowIndex);
if (object instanceof PdfNull) {
return "Indirect object";
}
return object.toString();
}
/**
* @see javax.swing.JTable#getColumnName(int)
*/
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Number";
case 1:
return "Object";
default:
return null;
}
}
/**
* Gets the object that is shown in a row.
*
* @param rowIndex the row number containing the object
* @return a PDF object
*/
protected PdfObject getObjectByRow(int rowIndex) {
return objects.loadObjectByReference(getObjectReferenceByRow(rowIndex));
}
/**
* Selects a row containing information about an indirect object.
*
* @param ref the reference number of the indirect object
*/
public void selectRowByReference(int ref) {
int row = objects.getIndexByRef(ref);
setRowSelectionInterval(row, row);
scrollRectToVisible(getCellRect(row, 1, true));
valueChanged(null);
}
/**
* @see javax.swing.JTable#valueChanged(javax.swing.event.ListSelectionEvent)
*/
@Override
public void valueChanged(ListSelectionEvent evt) {
if (evt != null) {
super.valueChanged(evt);
}
if (controller != null && objects != null) {
controller.render(getObjectByRow(this.getSelectedRow()));
controller.selectNode(getObjectReferenceByRow(getSelectedRow()));
}
}
}
|
if (obj == null) {
objects = null;
repaint();
return;
}
if (observable instanceof PdfReaderController
&& obj instanceof ObjectLoader) {
ObjectLoader loader = (ObjectLoader) obj;
objects = loader.getObjects();
setModel(new JTableAutoModel(this));
TableColumn col = getColumnModel().getColumn(0);
col.setPreferredWidth(5);
}
| 1,047
| 113
| 1,160
|
<methods>public void <init>() ,public void <init>(javax.swing.table.TableModel) ,public void <init>(javax.swing.table.TableModel, javax.swing.table.TableColumnModel) ,public void <init>(int, int) ,public void <init>(Vector<? extends Vector#RAW>, Vector<?>) ,public void <init>(java.lang.Object[][], java.lang.Object[]) ,public void <init>(javax.swing.table.TableModel, javax.swing.table.TableColumnModel, javax.swing.ListSelectionModel) ,public void addColumn(javax.swing.table.TableColumn) ,public void addColumnSelectionInterval(int, int) ,public void addNotify() ,public void addRowSelectionInterval(int, int) ,public void changeSelection(int, int, boolean, boolean) ,public void clearSelection() ,public void columnAdded(javax.swing.event.TableColumnModelEvent) ,public int columnAtPoint(java.awt.Point) ,public void columnMarginChanged(javax.swing.event.ChangeEvent) ,public void columnMoved(javax.swing.event.TableColumnModelEvent) ,public void columnRemoved(javax.swing.event.TableColumnModelEvent) ,public void columnSelectionChanged(javax.swing.event.ListSelectionEvent) ,public int convertColumnIndexToModel(int) ,public int convertColumnIndexToView(int) ,public int convertRowIndexToModel(int) ,public int convertRowIndexToView(int) ,public void createDefaultColumnsFromModel() ,public static javax.swing.JScrollPane createScrollPaneForTable(javax.swing.JTable) ,public void doLayout() ,public boolean editCellAt(int, int) ,public boolean editCellAt(int, int, java.util.EventObject) ,public void editingCanceled(javax.swing.event.ChangeEvent) ,public void editingStopped(javax.swing.event.ChangeEvent) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public boolean getAutoCreateColumnsFromModel() ,public boolean getAutoCreateRowSorter() ,public int getAutoResizeMode() ,public javax.swing.table.TableCellEditor getCellEditor() ,public javax.swing.table.TableCellEditor getCellEditor(int, int) ,public java.awt.Rectangle getCellRect(int, int, boolean) ,public javax.swing.table.TableCellRenderer getCellRenderer(int, int) ,public boolean getCellSelectionEnabled() ,public javax.swing.table.TableColumn getColumn(java.lang.Object) ,public Class<?> getColumnClass(int) ,public int getColumnCount() ,public javax.swing.table.TableColumnModel getColumnModel() ,public java.lang.String getColumnName(int) ,public boolean getColumnSelectionAllowed() ,public javax.swing.table.TableCellEditor getDefaultEditor(Class<?>) ,public javax.swing.table.TableCellRenderer getDefaultRenderer(Class<?>) ,public boolean getDragEnabled() ,public final javax.swing.JTable.DropLocation getDropLocation() ,public final javax.swing.DropMode getDropMode() ,public int getEditingColumn() ,public int getEditingRow() ,public java.awt.Component getEditorComponent() ,public boolean getFillsViewportHeight() ,public java.awt.Color getGridColor() ,public java.awt.Dimension getIntercellSpacing() ,public javax.swing.table.TableModel getModel() ,public java.awt.Dimension getPreferredScrollableViewportSize() ,public java.awt.print.Printable getPrintable(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) ,public int getRowCount() ,public int getRowHeight() ,public int getRowHeight(int) ,public int getRowMargin() ,public boolean getRowSelectionAllowed() ,public RowSorter<? extends javax.swing.table.TableModel> getRowSorter() ,public int getScrollableBlockIncrement(java.awt.Rectangle, int, int) ,public boolean getScrollableTracksViewportHeight() ,public boolean getScrollableTracksViewportWidth() ,public int getScrollableUnitIncrement(java.awt.Rectangle, int, int) ,public int getSelectedColumn() ,public int getSelectedColumnCount() ,public int[] getSelectedColumns() ,public int getSelectedRow() ,public int getSelectedRowCount() ,public int[] getSelectedRows() ,public java.awt.Color getSelectionBackground() ,public java.awt.Color getSelectionForeground() ,public javax.swing.ListSelectionModel getSelectionModel() ,public boolean getShowHorizontalLines() ,public boolean getShowVerticalLines() ,public boolean getSurrendersFocusOnKeystroke() ,public javax.swing.table.JTableHeader getTableHeader() ,public java.lang.String getToolTipText(java.awt.event.MouseEvent) ,public javax.swing.plaf.TableUI getUI() ,public java.lang.String getUIClassID() ,public boolean getUpdateSelectionOnSort() ,public java.lang.Object getValueAt(int, int) ,public boolean isCellEditable(int, int) ,public boolean isCellSelected(int, int) ,public boolean isColumnSelected(int) ,public boolean isEditing() ,public boolean isRowSelected(int) ,public void moveColumn(int, int) ,public java.awt.Component prepareEditor(javax.swing.table.TableCellEditor, int, int) ,public java.awt.Component prepareRenderer(javax.swing.table.TableCellRenderer, int, int) ,public boolean print() throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode) throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat) throws java.awt.print.PrinterException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat, boolean, javax.print.attribute.PrintRequestAttributeSet, boolean) throws java.awt.print.PrinterException, java.awt.HeadlessException,public boolean print(javax.swing.JTable.PrintMode, java.text.MessageFormat, java.text.MessageFormat, boolean, javax.print.attribute.PrintRequestAttributeSet, boolean, javax.print.PrintService) throws java.awt.print.PrinterException, java.awt.HeadlessException,public void removeColumn(javax.swing.table.TableColumn) ,public void removeColumnSelectionInterval(int, int) ,public void removeEditor() ,public void removeNotify() ,public void removeRowSelectionInterval(int, int) ,public int rowAtPoint(java.awt.Point) ,public void selectAll() ,public void setAutoCreateColumnsFromModel(boolean) ,public void setAutoCreateRowSorter(boolean) ,public void setAutoResizeMode(int) ,public void setCellEditor(javax.swing.table.TableCellEditor) ,public void setCellSelectionEnabled(boolean) ,public void setColumnModel(javax.swing.table.TableColumnModel) ,public void setColumnSelectionAllowed(boolean) ,public void setColumnSelectionInterval(int, int) ,public void setDefaultEditor(Class<?>, javax.swing.table.TableCellEditor) ,public void setDefaultRenderer(Class<?>, javax.swing.table.TableCellRenderer) ,public void setDragEnabled(boolean) ,public final void setDropMode(javax.swing.DropMode) ,public void setEditingColumn(int) ,public void setEditingRow(int) ,public void setFillsViewportHeight(boolean) ,public void setGridColor(java.awt.Color) ,public void setIntercellSpacing(java.awt.Dimension) ,public void setModel(javax.swing.table.TableModel) ,public void setPreferredScrollableViewportSize(java.awt.Dimension) ,public void setRowHeight(int) ,public void setRowHeight(int, int) ,public void setRowMargin(int) ,public void setRowSelectionAllowed(boolean) ,public void setRowSelectionInterval(int, int) ,public void setRowSorter(RowSorter<? extends javax.swing.table.TableModel>) ,public void setSelectionBackground(java.awt.Color) ,public void setSelectionForeground(java.awt.Color) ,public void setSelectionMode(int) ,public void setSelectionModel(javax.swing.ListSelectionModel) ,public void setShowGrid(boolean) ,public void setShowHorizontalLines(boolean) ,public void setShowVerticalLines(boolean) ,public void setSurrendersFocusOnKeystroke(boolean) ,public void setTableHeader(javax.swing.table.JTableHeader) ,public void setUI(javax.swing.plaf.TableUI) ,public void setUpdateSelectionOnSort(boolean) ,public void setValueAt(java.lang.Object, int, int) ,public void sizeColumnsToFit(boolean) ,public void sizeColumnsToFit(int) ,public void sorterChanged(javax.swing.event.RowSorterEvent) ,public void tableChanged(javax.swing.event.TableModelEvent) ,public void updateUI() ,public void valueChanged(javax.swing.event.ListSelectionEvent) <variables>static final boolean $assertionsDisabled,public static final int AUTO_RESIZE_ALL_COLUMNS,public static final int AUTO_RESIZE_LAST_COLUMN,public static final int AUTO_RESIZE_NEXT_COLUMN,public static final int AUTO_RESIZE_OFF,public static final int AUTO_RESIZE_SUBSEQUENT_COLUMNS,protected boolean autoCreateColumnsFromModel,private boolean autoCreateRowSorter,protected int autoResizeMode,protected transient javax.swing.table.TableCellEditor cellEditor,protected boolean cellSelectionEnabled,protected javax.swing.table.TableColumnModel columnModel,private boolean columnSelectionAdjusting,protected javax.swing.table.TableModel dataModel,protected transient Hashtable<java.lang.Object,java.lang.Object> defaultEditorsByColumnClass,protected transient Hashtable<java.lang.Object,java.lang.Object> defaultRenderersByColumnClass,private boolean dragEnabled,private transient javax.swing.JTable.DropLocation dropLocation,private javax.swing.DropMode dropMode,protected transient int editingColumn,protected transient int editingRow,protected transient java.awt.Component editorComp,private java.beans.PropertyChangeListener editorRemover,private boolean fillsViewportHeight,protected java.awt.Color gridColor,private boolean ignoreSortChange,private boolean isRowHeightSet,protected java.awt.Dimension preferredViewportSize,private java.lang.Throwable printError,protected int rowHeight,protected int rowMargin,private javax.swing.SizeSequence rowModel,private boolean rowSelectionAdjusting,protected boolean rowSelectionAllowed,protected java.awt.Color selectionBackground,protected java.awt.Color selectionForeground,protected javax.swing.ListSelectionModel selectionModel,protected boolean showHorizontalLines,protected boolean showVerticalLines,private transient javax.swing.JTable.SortManager sortManager,private boolean sorterChanged,private boolean surrendersFocusOnKeystroke,protected javax.swing.table.JTableHeader tableHeader,private static final java.lang.String uiClassID,private transient boolean updateInProgress,private boolean updateSelectionOnSort
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/treenodes/XdpTreeNode.java
|
XdpTreeNode
|
toString
|
class XdpTreeNode extends IconTreeNode {
/**
* A serial version UID.
*/
private static final long serialVersionUID = -6431790925424045933L;
/**
* Constructs an XdpTreeNode
*
* @param node the XML node
*/
public XdpTreeNode(Node node) {
super(null, node);
if (node instanceof Element) {
Element element = (Element) node;
addChildNodes(element.attributes());
}
if (node instanceof Branch) {
Branch branch = (Branch) node;
addChildNodes(branch.content());
}
if (node instanceof Attribute) {
icon = IconFetcher.getIcon("attribute.png");
return;
}
if (node instanceof Text) {
icon = IconFetcher.getIcon("text.png");
return;
}
if (node instanceof ProcessingInstruction) {
icon = IconFetcher.getIcon("pi.png");
return;
}
if (node instanceof Document) {
icon = IconFetcher.getIcon("xfa.png");
return;
}
icon = IconFetcher.getIcon("tag.png");
}
private void addChildNodes(List list) {
for (Object o : list) {
Node n = (Node) o;
if (n instanceof Namespace) {
continue;
}
if (n instanceof Comment) {
continue;
}
this.add(new XdpTreeNode(n));
}
}
public Node getNode() {
return (Node) getUserObject();
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
Node node = getNode();
if (node instanceof Element) {
Element e = (Element) node;
return e.getName();
}
if (node instanceof Attribute) {
Attribute a = (Attribute) node;
StringBuilder buf = new StringBuilder();
buf.append(a.getName());
buf.append("=\"");
buf.append(a.getValue());
buf.append('"');
return buf.toString();
}
if (node instanceof Text) {
Text t = (Text) node;
return t.getText();
}
if (node instanceof ProcessingInstruction) {
ProcessingInstruction pi = (ProcessingInstruction) node;
StringBuilder buf = new StringBuilder("<?");
buf.append(pi.getName());
buf.append(' ');
buf.append(pi.getText());
buf.append("?>");
return buf.toString();
}
if (node instanceof Document) {
return "XFA Document";
}
return getNode().toString();
| 464
| 263
| 727
|
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.lang.Object) ,public javax.swing.Icon getIcon() <variables>protected javax.swing.Icon icon,private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/itext/treenodes/XfaTreeNode.java
|
XfaTreeNode
|
writeTo
|
class XfaTreeNode extends FormTreeNode implements OutputStreamResource {
/**
* Start sequence of an artificial boundary between XFA fragments added by RUPS
*/
public static final byte[] BOUNDARY_START = "<!--\nRUPS XFA individual packet: end of [".getBytes();
/**
* Middle sequence of an artificial boundary between XFA fragments added by RUPS
*/
public static final byte[] BOUNDARY_MIDDLE = "]; start of [".getBytes();
/**
* End sequence of an artificial boundary between XFA fragments added by RUPS
*/
public static final byte[] BOUNDARY_END = "]\n-->".getBytes();
/**
* A serial version UID.
*/
private static final long serialVersionUID = 2463297568233643790L;
/**
* Creates the root node of the XFA tree. This will be a child of the FormTree root node.
*
* @param xfa the XFA node in the PdfTree (a child of the AcroForm node in the PDF catalog)
*/
public XfaTreeNode(PdfObjectTreeNode xfa) {
super(xfa);
}
/**
* Writes (part of) the XFA resource to an OutputStream. If key is <code>null</code>, the complete resource is
* written; if key refers to an individual package, this package only is written to the OutputStream.
*
* @param os the OutputStream to which the XML is written.
* @throws IOException usual exception when there's a problem writing to an OutputStream
*/
public void writeTo(OutputStream os) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Adds a child node to the XFA root. The child node either corresponds with the complete XDP stream (if the XFA
* root only has one child) or with individual packet.
*
* @param key the name of the packet
* @param value the corresponding stream node in the PdfTree
*/
public void addPacket(String key, PdfObjectTreeNode value) {
FormTreeNode node = new FormTreeNode(value);
node.setUserObject(key);
this.add(node);
}
}
|
Enumeration children = this.children();
FormTreeNode node;
PRStream stream;
String key = null;
String tmp = null;
while (children.hasMoreElements()) {
node = (FormTreeNode) children.nextElement();
if (key != null) {
os.write(BOUNDARY_START);
os.write(key.getBytes());
os.write(BOUNDARY_MIDDLE);
tmp = (String) node.getUserObject();
os.write(tmp.getBytes());
os.write(BOUNDARY_END);
}
key = tmp;
stream = (PRStream) node.getCorrespondingPdfObjectNode().getPdfObject();
os.write(PdfReader.getStreamBytes(stream));
}
os.flush();
os.close();
| 575
| 214
| 789
|
<methods>public void <init>() ,public void <init>(com.lowagie.rups.view.itext.treenodes.PdfObjectTreeNode) ,public com.lowagie.rups.view.itext.treenodes.PdfObjectTreeNode getCorrespondingPdfObjectNode() <variables>protected com.lowagie.rups.view.itext.treenodes.PdfObjectTreeNode object_node,private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/models/DictionaryTableModel.java
|
DictionaryTableModel
|
getValueAt
|
class DictionaryTableModel extends AbstractTableModel {
/**
* A serial version UID.
*/
private static final long serialVersionUID = -8835275996639701776L;
/**
* The PDF dictionary.
*/
protected PdfDictionary dictionary;
/**
* An ArrayList with the dictionary keys.
*/
protected ArrayList<PdfName> keys = new ArrayList<>();
/**
* Creates the TableModel.
*
* @param dictionary the dictionary we want to show
*/
public DictionaryTableModel(PdfDictionary dictionary) {
this.dictionary = dictionary;
this.keys.addAll(dictionary.getKeys());
}
/**
* @see javax.swing.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return 2;
}
/**
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount() {
return dictionary.size();
}
/**
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int rowIndex, int columnIndex) {<FILL_FUNCTION_BODY>}
/**
* @see javax.swing.table.AbstractTableModel#getColumnName(int)
*/
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Key";
case 1:
return "Value";
default:
return null;
}
}
}
|
switch (columnIndex) {
case 0:
return keys.get(rowIndex);
case 1:
return dictionary.get(keys.get(rowIndex));
default:
return null;
}
| 416
| 59
| 475
|
<methods>public void addTableModelListener(javax.swing.event.TableModelListener) ,public int findColumn(java.lang.String) ,public void fireTableCellUpdated(int, int) ,public void fireTableChanged(javax.swing.event.TableModelEvent) ,public void fireTableDataChanged() ,public void fireTableRowsDeleted(int, int) ,public void fireTableRowsInserted(int, int) ,public void fireTableRowsUpdated(int, int) ,public void fireTableStructureChanged() ,public Class<?> getColumnClass(int) ,public java.lang.String getColumnName(int) ,public T[] getListeners(Class<T>) ,public javax.swing.event.TableModelListener[] getTableModelListeners() ,public boolean isCellEditable(int, int) ,public void removeTableModelListener(javax.swing.event.TableModelListener) ,public void setValueAt(java.lang.Object, int, int) <variables>protected javax.swing.event.EventListenerList listenerList
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-swing/src/main/java/com/lowagie/rups/view/models/PdfArrayTableModel.java
|
PdfArrayTableModel
|
getValueAt
|
class PdfArrayTableModel extends AbstractTableModel {
/**
* A serial version UID.
*/
private static final long serialVersionUID = 4665485782853993708L;
/**
* The PDF array.
*/
protected PdfArray array;
/**
* Creates the TableModel.
*
* @param array a PDF array
*/
public PdfArrayTableModel(PdfArray array) {
this.array = array;
}
/**
* @see javax.swing.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return 1;
}
/**
* @see javax.swing.table.TableModel#getRowCount()
*/
public int getRowCount() {
return array.size();
}
/**
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int rowIndex, int columnIndex) {<FILL_FUNCTION_BODY>}
/**
* @see javax.swing.table.AbstractTableModel#getColumnName(int)
*/
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:
return "Array";
default:
return null;
}
}
}
|
switch (columnIndex) {
case 0:
return array.getPdfObject(rowIndex);
default:
return null;
}
| 357
| 42
| 399
|
<methods>public void addTableModelListener(javax.swing.event.TableModelListener) ,public int findColumn(java.lang.String) ,public void fireTableCellUpdated(int, int) ,public void fireTableChanged(javax.swing.event.TableModelEvent) ,public void fireTableDataChanged() ,public void fireTableRowsDeleted(int, int) ,public void fireTableRowsInserted(int, int) ,public void fireTableRowsUpdated(int, int) ,public void fireTableStructureChanged() ,public Class<?> getColumnClass(int) ,public java.lang.String getColumnName(int) ,public T[] getListeners(Class<T>) ,public javax.swing.event.TableModelListener[] getTableModelListeners() ,public boolean isCellEditable(int, int) ,public void removeTableModelListener(javax.swing.event.TableModelListener) ,public void setValueAt(java.lang.Object, int, int) <variables>protected javax.swing.event.EventListenerList listenerList
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/Versions.java
|
Versions
|
initialize
|
class Versions
extends JFrame {
/**
* The serial version UID of this class.
*/
private static final long serialVersionUID = 2925242862240301106L;
/**
* A label with info about the library, JVM,...
*/
JLabel library_versions = new JLabel();
/**
* The table with all the plug-ins (name, version and date).
*/
JTable plugin_versions = new JTable();
/**
* A scrollpane for the plugin_versions table.
*/
JScrollPane scroll_versions = new JScrollPane();
/**
* Constructs a Versions object.
*/
public Versions() {
super("Plugins and their version");
try {
initialize();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Main method (test purposes only)
*
* @param args String[]
*/
public static void main(String[] args) {
Versions version = new Versions();
version.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
version.setVisible(true);
}
/**
* Initialization of the jFrame.
*
* @throws Exception
*/
private void initialize() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Returns the TableModel implementation that will be used to show the plugin_versions.
*
* @param versionsarray ArrayList
* @return TableModel
*/
public TableModel getVersionTableModel(final ArrayList<String> versionsarray) {
return new AbstractTableModel() {
private static final long serialVersionUID = 5105003782164682777L;
public int getColumnCount() {
return 4;
}
public int getRowCount() {
return versionsarray.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
String dummy;
switch (columnIndex) {
case 0:
dummy = versionsarray.get(rowIndex);
return dummy.split(".java")[0];
case 1:
dummy = versionsarray.get(rowIndex);
return dummy.split(" ")[1];
case 2:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dummy = versionsarray.get(rowIndex);
try {
return df.parse(dummy.split(" ")[2] + " "
+ dummy.split(" ")[3]);
} catch (ParseException ex) {
return null;
}
case 3:
dummy = versionsarray.get(rowIndex);
return dummy.split(" ")[4];
}
return versionsarray;
}
public String getColumnName(int column) {
switch (column) {
case 0:
return "Name";
case 1:
return "Version";
case 2:
return "Changed";
case 3:
return "ChangeBy";
default:
return "";
}
}
public Class<? extends Object> getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return java.util.Date.class;
case 3:
return String.class;
default:
return null;
}
}
};
}
}
|
this.getContentPane().setLayout(new BorderLayout());
scroll_versions.setViewportView(plugin_versions);
library_versions.setIcon(new ImageIcon(Versions.class.getResource(
"1t3xt.gif")));
this.getContentPane().add(library_versions, BorderLayout.NORTH);
this.getContentPane().add(scroll_versions, BorderLayout.CENTER);
Properties properties = System.getProperties();
Runtime runtime = Runtime.getRuntime();
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<p>iTexttoolbox version: ").append(Versions.class.getPackage().getImplementationVersion())
.append("</p>");
sb.append("<p>iText version: ").append(Document.getVersion()).append("</p>");
sb.append("<p>java.version: ").append(properties.getProperty("java.version")).append("</p>");
sb.append("<p>java.vendor: ").append(properties.getProperty("java.vendor")).append("</p>");
sb.append("<p>java.home: ").append(properties.getProperty("java.home")).append("</p>");
sb.append("<p>java.freeMemory: ").append(runtime.freeMemory()).append(" bytes").append("</p>");
sb.append("<p>java.totalMemory: ").append(runtime.totalMemory()).append(" bytes").append("</p>");
sb.append("<p>user.home: ").append(properties.getProperty("user.home")).append("</p>");
sb.append("<p>os.name: ").append(properties.getProperty("os.name")).append("</p>");
sb.append("<p>os.arch: ").append(properties.getProperty("os.arch")).append("</p>");
sb.append("<p>os.version: ").append(properties.getProperty("os.version")).append("</p>");
sb.append("</html>");
library_versions.setText(sb.toString());
TableModel model = getVersionTableModel(AbstractTool.versionsarray);
RowSorter<TableModel> sorter =
new TableRowSorter<>(model);
plugin_versions.setRowSorter(sorter);
plugin_versions.setModel(model);
pack();
| 928
| 621
| 1,549
|
<methods>public void <init>() throws java.awt.HeadlessException,public void <init>(java.awt.GraphicsConfiguration) ,public void <init>(java.lang.String) throws java.awt.HeadlessException,public void <init>(java.lang.String, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setIconImage(java.awt.Image) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/AbstractArgument.java
|
AbstractArgument
|
getUsage
|
class AbstractArgument implements ActionListener, PropertyChangeListener {
protected PropertyChangeSupport pcs = new PropertyChangeSupport(this);
/**
* value of the argument.
*/
protected Object value = null;
/**
* short name for the argument.
*/
protected String name;
/**
* reference to the internal frame
*/
protected AbstractTool tool;
/**
* describes the argument.
*/
protected String description;
public AbstractArgument() {
}
public AbstractArgument(AbstractTool tool, String name, String description, Object value) {
this.tool = tool;
this.name = name;
this.description = description;
this.value = value;
}
protected synchronized void firePropertyChange(PropertyChangeEvent evt) {
pcs.firePropertyChange(evt);
}
public synchronized void removePropertyChangeListener(
PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
public synchronized void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
/**
* @return Returns the value.
*/
public Object getValue() {
return value;
}
/**
* @param value The value to set.
*/
public void setValue(Object value) {
Object oldvalue = this.value;
this.value = value;
tool.valueHasChanged(this);
this.firePropertyChange(new PropertyChangeEvent(this, name, oldvalue,
this.value));
}
public void setValue(Object value, String propertyname) {
Object oldvalue = this.value;
this.value = value;
tool.valueHasChanged(this);
this.firePropertyChange(new PropertyChangeEvent(this, propertyname,
oldvalue, this.value));
}
/**
* @return Returns the description.
*/
public String getDescription() {
return description;
}
/**
* @param description The description to set.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Give you a String that can be used in a usage description.
*
* @return a String
*/
public String getUsage() {<FILL_FUNCTION_BODY>}
public AbstractTool getTool() {
return tool;
}
public void setTool(AbstractTool tool) {
this.tool = tool;
}
/**
* Gets the argument as an object.
*
* @return an object
* @throws InstantiationException if the specified key cannot be compared with the keys currently in the map
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
return value;
}
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("AbstractArgument PropertyChange");
}
public abstract void actionPerformed(ActionEvent e);
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
return getValue().toString();
}
}
|
StringBuilder buf = new StringBuilder(" ");
buf.append(name);
buf.append(" - ");
buf.append(description);
buf.append('\n');
return buf.toString();
| 899
| 56
| 955
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/BitsetArgument.java
|
BitsetArgument
|
actionPerformed
|
class BitsetArgument extends AbstractArgument {
/**
* These are the different options that can be true or false.
*/
private JCheckBox[] options;
/**
* Constructs an BitsetArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
* @param options the different options that can be true or false
*/
public BitsetArgument(AbstractTool tool, String name, String description,
String[] options) {
super(tool, name, description, null);
this.options = new JCheckBox[options.length];
for (int i = 0; i < options.length; i++) {
this.options[i] = new JCheckBox(options[i]);
}
}
/**
* @return String
* @see com.lowagie.toolbox.arguments.StringArgument#getUsage()
*/
public String getUsage() {
StringBuilder buf = new StringBuilder(super.getUsage());
buf.append(" possible options:\n");
for (JCheckBox option : options) {
buf.append(" - ");
buf.append(option.getText());
buf.append('\n');
}
return buf.toString();
}
/**
* @param evt ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {<FILL_FUNCTION_BODY>}
}
|
Object[] message = new Object[1 + options.length];
message[0] = "Check the options you need:";
System.arraycopy(options, 0, message, 1, options.length);
int result = JOptionPane.showOptionDialog(
tool.getInternalFrame(),
message,
description,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null
);
if (result == 0) {
StringBuilder buf = new StringBuilder();
for (JCheckBox option : options) {
if (option.isSelected()) {
buf.append('1');
} else {
buf.append('0');
}
}
setValue(buf.toString());
}
| 403
| 205
| 608
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/ColorArgument.java
|
ColorArgument
|
getArgument
|
class ColorArgument extends AbstractArgument {
public ColorArgument() {
super();
}
public ColorArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
}
public Object getArgument() throws InstantiationException {<FILL_FUNCTION_BODY>}
public void actionPerformed(ActionEvent e) {
Color initialColor = new Color(0xFF, 0xFF, 0xFF);
if (value != null) {
initialColor = Color.decode(value.toString());
}
Color newColor = JColorChooser.showDialog(tool.getInternalFrame(),
"Choose Color", initialColor);
setValue("0x"
+ Integer.toHexString(
(newColor.getRed() << 16)
| (newColor.getGreen() << 8)
| (newColor.getBlue() << 0)).toUpperCase());
}
}
|
if (value == null) {
return null;
}
try {
return Color.decode(value.toString());
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
| 244
| 60
| 304
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/FileArgument.java
|
FileArgument
|
actionPerformed
|
class FileArgument extends AbstractArgument {
/**
* a filter to put on the FileChooser.
*/
protected FileFilter filter;
/**
* indicates if the argument has to point to a new or an existing file.
*/
protected boolean newFile;
/**
* the label
*/
PdfInformationPanel label = null;
public FileArgument() {
super();
}
/**
* Constructs a FileArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
* @param newFile makes the difference between an Open or Save dialog
* @param filter FileFilter
*/
public FileArgument(AbstractTool tool, String name, String description,
boolean newFile, FileFilter filter) {
super(tool, name, description, null);
this.newFile = newFile;
this.filter = filter;
}
/**
* Constructs a FileArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
* @param newFile makes the difference between an Open or Save dialog
*/
public FileArgument(AbstractTool tool, String name, String description,
boolean newFile) {
this(tool, name, description, newFile, null);
}
/**
* Gets the argument as an object.
*
* @return an object
* @throws InstantiationException if the specified key cannot be compared with the keys currently in the map
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
try {
return new File(value.toString());
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
}
/**
* @param e ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
/**
* @return Returns the filter.
*/
public FileFilter getFilter() {
return filter;
}
/**
* @param filter The filter to set.
*/
public void setFilter(FileFilter filter) {
this.filter = filter;
}
/**
* @return Returns the label.
*/
public PdfInformationPanel getLabel() {
return label;
}
/**
* @param label The label to set.
*/
public void setLabel(PdfInformationPanel label) {
this.label = label;
}
}
|
JFileChooser fc = new JFileChooser();
if (filter != null) {
fc.setFileFilter(filter);
if (filter instanceof DirFilter) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
}
if (label != null) {
fc.setAccessory(label);
fc.addPropertyChangeListener(
JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, label);
}
if (newFile) {
fc.showSaveDialog(tool.getInternalFrame());
} else {
fc.showOpenDialog(tool.getInternalFrame());
}
try {
setValue(fc.getSelectedFile());
} catch (NullPointerException npe) {
}
| 701
| 215
| 916
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/FileArrayArgument.java
|
FileArrayArgument
|
getArgument
|
class FileArrayArgument extends AbstractArgument {
FileList fileList1 = new FileList();
public FileArrayArgument() {
super();
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public FileArrayArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileArrayArgument filearrayargument = new FileArrayArgument();
}
public void actionPerformed(ActionEvent e) {
fileList1.setLocation(10, 10);
fileList1.setVisible(true);
this.getTool().getInternalFrame().getDesktopPane().add(fileList1);
try {
fileList1.setSelected(true);
} catch (PropertyVetoException ex1) {
System.out.println(ex1.getMessage());
}
// try {
// setValue(fileList1.getFilevector().toArray());
// } catch (NullPointerException npe) {
// }
}
public Object getArgument() throws InstantiationException {<FILL_FUNCTION_BODY>}
private void jbInit() throws Exception {
fileList1.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent evt) {
String propertyname = evt.getPropertyName();
if (propertyname.equals("filevector")) {
File[] filear = (File[]) evt.getNewValue();
if (filear != null) {
this.setValue(filear);
}
}
}
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
return fileList1.getStringreprasentation();
}
}
|
if (value == null) {
return null;
}
try {
return value;
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
| 516
| 54
| 570
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/FloatArgument.java
|
FloatArgument
|
actionPerformed
|
class FloatArgument extends AbstractArgument {
public FloatArgument() {
super();
}
public FloatArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
}
/**
* Invoked when an action occurs.
*
* @param e ActionEvent
*/
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
}
|
CustomDialog cd = new CustomDialog("Enter a value for " + name +
":", CustomDialog.instantiateFloatDocument());
setValue(cd.showInputDialog(this.getValue() == null ? "0" : this.getValue().toString()));
| 114
| 63
| 177
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/ImageArgument.java
|
ImageArgument
|
actionPerformed
|
class ImageArgument extends AbstractArgument {
/**
* a filter to put on the FileChooser.
*/
private FileFilter filter;
/**
* Constructs a FileArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
* @param filter a custom filter
*/
public ImageArgument(AbstractTool tool, String name, String description,
FileFilter filter) {
super(tool, name, description, null);
this.filter = filter;
}
/**
* Constructs a FileArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public ImageArgument(AbstractTool tool, String name, String description) {
this(tool, name, description, new ImageFilter());
}
/**
* Gets the argument as an object.
*
* @return an object
* @throws InstantiationException if the specified key cannot be compared with the keys currently in the map
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
try {
return Image.getInstance(value.toString());
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
}
/**
* @param e ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
}
|
JFileChooser fc = new JFileChooser();
if (filter != null) {
fc.setFileFilter(filter);
}
fc.showOpenDialog(tool.getInternalFrame());
try {
setValue(fc.getSelectedFile().getAbsolutePath());
} catch (NullPointerException npe) {
}
| 429
| 94
| 523
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/IntegerArgument.java
|
IntegerArgument
|
actionPerformed
|
class IntegerArgument extends AbstractArgument {
/**
* Constructs a IntegerArgument.
*/
public IntegerArgument() {
}
/**
* Constructs a IntegerArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public IntegerArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
}
/**
* @param e ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
}
|
CustomDialog cd = new CustomDialog("Enter a value for " + name +
":",
CustomDialog.instantiateIntegerDocument());
setValue(cd.showInputDialog(this.getValue() == null ? "0" : this.getValue().toString()));
| 190
| 65
| 255
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/OptionArgument.java
|
OptionArgument
|
actionPerformed
|
class OptionArgument extends AbstractArgument {
private TreeMap<String, Entry> options = new TreeMap<>();
/**
* Constructs an OptionArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public OptionArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
// this.setClassname(new Entry("").getClass().getName());
}
/**
* Adds an Option.
*
* @param description the description of the option
* @param value the value of the option
*/
public void addOption(Object description, Object value) {
options.put(value.toString(), new Entry(description, value));
}
/**
* Gets the argument as an object.
*
* @return an object
* @throws InstantiationException if the specified key cannot be compared with the keys currently in the map
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
try {
return options.get(value).getValue();
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
}
/**
* @return String
* @see com.lowagie.toolbox.arguments.StringArgument#getUsage()
*/
public String getUsage() {
StringBuilder buf = new StringBuilder(super.getUsage());
buf.append(" possible options:\n");
for (Entry entry : options.values()) {
buf.append(" - ");
buf.append(entry.getValueToString());
buf.append(": ");
buf.append(entry.toString());
buf.append('\n');
}
return buf.toString();
}
/**
* @param evt ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {<FILL_FUNCTION_BODY>}
/**
* An Entry that can be chosen as option.
*/
public class Entry {
/**
* Describes the option.
*/
private Object description;
/**
* Holds the actual value of the option.
*/
private Object value;
/**
* Constructs an entry.
*
* @param value the value of the entry (that will be identical to the description)
*/
public Entry(Object value) {
this.value = value;
this.description = value;
}
/**
* Constructs an entry.
*
* @param description the description of the entry
* @param value the value of the entry
*/
public Entry(Object description, Object value) {
this.description = description;
this.value = value;
}
/**
* String representation of the Entry.
*
* @return a description of the entry
*/
public String toString() {
return description.toString();
}
/**
* Gets the value of the String.
*
* @return the toString of the value
*/
public String getValueToString() {
return value.toString();
}
/**
* @return Returns the description.
*/
public Object getDescription() {
return description;
}
/**
* @param description The description to set.
*/
public void setDescription(Object description) {
this.description = description;
}
/**
* @return Returns the value.
*/
public Object getValue() {
return value;
}
/**
* @param value The value to set.
*/
public void setValue(Object value) {
this.value = value;
}
}
}
|
Object[] message = new Object[2];
message[0] = "Choose one of the following options:";
JComboBox<Entry> cb = new JComboBox<>();
for (Entry entry : options.values()) {
cb.addItem(entry);
}
message[1] = cb;
int result = JOptionPane.showOptionDialog(
tool.getInternalFrame(),
message,
description,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null
);
if (result == 0) {
Entry entry = (Entry) cb.getSelectedItem();
setValue(entry.getValueToString());
}
| 996
| 188
| 1,184
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/PageSizeArgument.java
|
PageSizeArgument
|
getUsage
|
class PageSizeArgument extends OptionArgument {
private TreeMap<String, String> options = new TreeMap<>();
/**
* Constructs an OptionArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public PageSizeArgument(AbstractTool tool, String name, String description) {
super(tool, name, description);
Class<?> ps = PageSize.class;
Field[] sizes = ps.getDeclaredFields();
try {
for (Field size : sizes) {
addOption(size.getName(), size.get(null));
}
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Adds an Option.
*
* @param description the description of the option
* @param value the value of the option
*/
public void addOption(String description, String value) {
options.put(description, value);
}
/**
* Gets the options.
*
* @return Returns the options.
*/
public TreeMap<String, String> getOptions() {
return options;
}
/**
* Gets the argument as an object.
*
* @return an object
* @throws InstantiationException if the key can't be compared with the other ones in the map
*/
public Object getArgument() throws InstantiationException {
if (value == null) {
return null;
}
try {
return options.get(value);
} catch (Exception e) {
throw new InstantiationException(e.getMessage());
}
}
/**
* @return String
* @see com.lowagie.toolbox.arguments.StringArgument#getUsage()
*/
public String getUsage() {<FILL_FUNCTION_BODY>}
/**
* @param evt ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {
Object[] message = new Object[2];
message[0] = "Choose one of the following pagesizes:";
JComboBox<String> cb = new JComboBox<>();
for (String o : options.keySet()) {
cb.addItem(o);
}
message[1] = cb;
int result = JOptionPane.showOptionDialog(
tool.getInternalFrame(),
message,
description,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
null,
null
);
if (result == 0) {
setValue(cb.getSelectedItem());
}
}
/**
* Returns a string representation of the object.
*
* @return a string representation of the object.
*/
public String toString() {
return super.getValue().toString();
}
}
|
StringBuilder buf = new StringBuilder(" ");
buf.append(name);
buf.append(" - ");
buf.append(description);
buf.append('\n');
buf.append(" possible options:\n");
String s;
for (Object o : options.keySet()) {
s = (String) o;
buf.append(" - ");
buf.append(s);
buf.append('\n');
}
return buf.toString();
| 780
| 124
| 904
|
<methods>public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String) ,public void actionPerformed(java.awt.event.ActionEvent) ,public void addOption(java.lang.Object, java.lang.Object) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getUsage() <variables>private TreeMap<java.lang.String,com.lowagie.toolbox.arguments.OptionArgument.Entry> options
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/StringArgument.java
|
StringArgument
|
actionPerformed
|
class StringArgument extends AbstractArgument {
/**
* Constructs a StringArgument.
*/
public StringArgument() {
}
/**
* Constructs a StringArgument.
*
* @param tool the tool that needs this argument
* @param name the name of the argument
* @param description the description of the argument
*/
public StringArgument(AbstractTool tool, String name, String description) {
super(tool, name, description, null);
}
/**
* @param e ActionEvent
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {<FILL_FUNCTION_BODY>}
}
|
CustomDialog cd = new CustomDialog("Enter a value for " + name + ":",
CustomDialog.instantiateStringDocument());
setValue(cd.showInputDialog(this.getValue() == null ? "" : this.getValue().toString()));
| 190
| 61
| 251
|
<methods>public void <init>() ,public void <init>(com.lowagie.toolbox.AbstractTool, java.lang.String, java.lang.String, java.lang.Object) ,public abstract void actionPerformed(java.awt.event.ActionEvent) ,public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener) ,public java.lang.Object getArgument() throws java.lang.InstantiationException,public java.lang.String getDescription() ,public java.lang.String getName() ,public com.lowagie.toolbox.AbstractTool getTool() ,public java.lang.String getUsage() ,public java.lang.Object getValue() ,public void propertyChange(java.beans.PropertyChangeEvent) ,public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener) ,public void setDescription(java.lang.String) ,public void setName(java.lang.String) ,public void setTool(com.lowagie.toolbox.AbstractTool) ,public void setValue(java.lang.Object) ,public void setValue(java.lang.Object, java.lang.String) ,public java.lang.String toString() <variables>protected java.lang.String description,protected java.lang.String name,protected java.beans.PropertyChangeSupport pcs,protected com.lowagie.toolbox.AbstractTool tool,protected java.lang.Object value
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/arguments/filters/ImageFilter.java
|
ImageFilter
|
accept
|
class ImageFilter extends FileFilter {
/**
* Array with all kinds of image extensions.
*/
public static final String[] IMAGES = new String[8];
static {
IMAGES[0] = ".jpg";
IMAGES[1] = ".jpeg";
IMAGES[2] = ".png";
IMAGES[3] = ".gif";
IMAGES[4] = ".bmp";
IMAGES[5] = ".wmf";
IMAGES[6] = ".tif";
IMAGES[7] = ".tiff";
}
/**
* array that enables you to filter on image types.
*/
public boolean[] filter = new boolean[8];
/**
* Constructs an ImageFilter allowing all images.
*/
public ImageFilter() {
for (int i = 0; i < filter.length; i++) {
filter[i] = true;
}
}
/**
* Constructs an ImageFilter allowing some images.
*
* @param jpeg indicates if jpegs are allowed
* @param png indicates if pngs are allowed
* @param gif indicates if gifs are allowed
* @param bmp indicates if bmps are allowed
* @param wmf indicates if wmfs are allowed
* @param tiff indicates if tiffs are allowed
*/
public ImageFilter(boolean jpeg, boolean png, boolean gif, boolean bmp, boolean wmf, boolean tiff) {
if (jpeg) {
filter[0] = true;
filter[1] = true;
}
if (png) {
filter[2] = true;
}
if (gif) {
filter[3] = true;
}
if (bmp) {
filter[4] = true;
}
if (wmf) {
filter[5] = true;
}
if (tiff) {
filter[6] = true;
filter[7] = true;
}
}
/**
* @param f File
* @return boolean
* @see javax.swing.filechooser.FileFilter#accept(java.io.File)
*/
public boolean accept(File f) {<FILL_FUNCTION_BODY>}
/**
* @return String
* @see javax.swing.filechooser.FileFilter#getDescription()
*/
public String getDescription() {
return "Image files";
}
}
|
if (f.isDirectory()) {
return true;
}
for (int i = 0; i < IMAGES.length; i++) {
if (filter[i] && f.getName().toLowerCase().endsWith(IMAGES[i])) {
return true;
}
}
return false;
| 642
| 85
| 727
|
<methods>public abstract boolean accept(java.io.File) ,public abstract java.lang.String getDescription() <variables>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Bookmarks2XML.java
|
Bookmarks2XML
|
execute
|
class Bookmarks2XML extends AbstractTool {
static {
addVersion("$Id: Bookmarks2XML.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs an Bookmarks2XML object.
*/
public Bookmarks2XML() {
arguments.add(new FileArgument(this, "pdffile", "the PDF from which you want to extract bookmarks", false,
new PdfFilter()));
arguments.add(new FileArgument(this, "xmlfile", "the resulting bookmarks file in XML", true));
}
/**
* Allows you to generate an index file in HTML containing Bookmarks to an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
Bookmarks2XML tool = new Bookmarks2XML();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Bookmarks2XML", true, true, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Bookmarks2XML OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
throw new InstantiationException("There is no file to show.");
}
}
|
try {
if (getValue("xmlfile") == null) {
throw new InstantiationException("You need to choose an xml file");
}
if (getValue("pdffile") == null) {
throw new InstantiationException("You need to choose a source PDF file");
}
PdfReader reader = new PdfReader(((File) getValue("pdffile")).getAbsolutePath());
reader.consolidateNamedDestinations();
List<Map<String, Object>> bookmarks = SimpleBookmark.getBookmarkList(reader);
// save them in XML format
FileOutputStream bmWriter = new FileOutputStream((File) getValue("xmlfile"));
SimpleBookmark.exportToXML(bookmarks, bmWriter, "UTF-8", false);
bmWriter.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 620
| 270
| 890
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Burst.java
|
Burst
|
execute
|
class Burst extends AbstractTool {
static {
addVersion("$Id: Burst.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Burst object.
*/
public Burst() {
FileArgument f = new FileArgument(this, "srcfile", "The file you want to split", false, new PdfFilter());
f.setLabel(new PdfInformationPanel());
arguments.add(f);
}
/**
* Divide PDF file into pages.
*
* @param args String[]
*/
public static void main(String[] args) {
Burst tool = new Burst();
if (args.length < 1) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Burst", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Burst OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
throw new InstantiationException("There is more than one destfile.");
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
File directory = src.getParentFile();
String name = src.getName();
name = name.substring(0, name.lastIndexOf('.'));
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
int digits = 1 + (n / 10);
System.out.println("There are " + n + " pages in the original file.");
Document document;
int pagenumber;
String filename;
for (int i = 0; i < n; i++) {
pagenumber = i + 1;
filename = String.valueOf(pagenumber);
while (filename.length() < digits) {
filename = "0" + filename;
}
filename = "_" + filename + ".pdf";
// step 1: creation of a document-object
document = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(new File(directory, name + filename)));
// step 3: we open the document
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, pagenumber);
int rotation = reader.getPageRotation(pagenumber);
if (rotation == 90 || rotation == 270) {
cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(pagenumber).getHeight());
} else {
cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
// step 5: we close the document
document.close();
}
} catch (Exception e) {
e.printStackTrace();
}
| 580
| 560
| 1,140
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/CompressDecompressPageContent.java
|
CompressDecompressPageContent
|
execute
|
class CompressDecompressPageContent extends AbstractTool {
static {
addVersion("$Id: CompressDecompressPageContent.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Burst object.
*/
public CompressDecompressPageContent() {
FileArgument f = new FileArgument(this, "srcfile", "The file you want to compress/decompress", false,
new PdfFilter());
f.setLabel(new PdfInformationPanel());
arguments.add(f);
arguments.add(new FileArgument(this, "destfile",
"The file to which the compressed/decompressed PDF has to be written", true, new PdfFilter()));
OptionArgument oa = new OptionArgument(this, "compress", "compress");
oa.addOption("Compress page content", "true");
oa.addOption("Decompress page content", "false");
arguments.add(oa);
}
/**
* Compresses/decompresses the page content streams in a PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
CompressDecompressPageContent tool = new CompressDecompressPageContent();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Compress/Decompress", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Compress/Decompress OPENED ===");
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
boolean compress = "true".equals(getValue("compress"));
PdfReader reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath());
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(getDestPathPDF()));
synchronized (arguments) {
Document.compress = compress;
int total = reader.getNumberOfPages() + 1;
for (int i = 1; i < total; i++) {
reader.setPageContent(i, reader.getPageContent(i));
}
stamper.close();
Document.compress = true;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 727
| 298
| 1,025
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Concat.java
|
Concat
|
main
|
class Concat extends AbstractTool {
static {
addVersion("$Id: Concat.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Concat object.
*/
public Concat() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcfile1", "The first PDF file", false, new PdfFilter()));
arguments.add(new FileArgument(this, "srcfile2", "The second PDF file", false, new PdfFilter()));
arguments.add(
new FileArgument(this, "destfile", "The file to which the concatenated PDF has to be written", true,
new PdfFilter()));
}
/**
* Concatenates two PDF files.
*
* @param args String[]
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Concatenate 2 PDF files", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Concat OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
String[] files = new String[2];
if (getValue("srcfile1") == null) {
throw new InstantiationException("You need to choose a first sourcefile");
}
files[0] = ((File) getValue("srcfile1")).getAbsolutePath();
if (getValue("srcfile2") == null) {
throw new InstantiationException("You need to choose a second sourcefile");
}
files[1] = ((File) getValue("srcfile2")).getAbsolutePath();
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
File pdf_file = (File) getValue("destfile");
int pageOffset = 0;
List<Map<String, Object>> master = new ArrayList<>();
Document document = null;
PdfCopy writer = null;
for (int i = 0; i < 2; i++) {
// we create a reader for a certain document
PdfReader reader = new PdfReader(files[i]);
reader.consolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
List<Map<String, Object>> bookmarks = SimpleBookmark.getBookmarkList(reader);
if (bookmarks != null) {
if (pageOffset != 0) {
SimpleBookmark.shiftPageNumbersInRange(bookmarks, pageOffset, null);
}
master.addAll(bookmarks);
}
pageOffset += n;
System.out.println("There are " + n + " pages in " + files[i]);
if (i == 0) {
// step 1: creation of a document-object
document = new Document(reader.getPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document, new FileOutputStream(pdf_file));
// step 3: we open the document
document.open();
}
// step 4: we add content
PdfImportedPage page;
for (int p = 0; p < n; ) {
++p;
page = writer.getImportedPage(reader, p);
writer.addPage(page);
System.out.println("Processed page " + p);
}
}
if (!master.isEmpty()) {
writer.setOutlines(master);
}
// step 5: we close the document
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
Concat tool = new Concat();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
| 1,251
| 56
| 1,307
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/ConcatN.java
|
ConcatN
|
execute
|
class ConcatN extends AbstractTool {
static {
addVersion("$Id: ConcatN.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Concat object.
*/
public ConcatN() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArrayArgument(this, "srcfiles",
"The list of PDF files"));
arguments.add(new FileArgument(this, "destfile",
"The file to which the concatenated PDF has to be written", true,
new PdfFilter()));
}
/**
* Concatenates two PDF files.
*
* @param args String[]
*/
public static void main(String[] args) {
ConcatN tool = new ConcatN();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Concatenate n PDF files", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Concat OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
File[] files;
if (getValue("srcfiles") == null) {
throw new InstantiationException(
"You need to choose a list of sourcefiles");
}
files = ((File[]) getValue("srcfiles"));
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
File pdf_file = (File) getValue("destfile");
int pageOffset = 0;
List<Map<String, Object>> master = new ArrayList<>();
Document document = null;
PdfCopy writer = null;
for (int i = 0; i < files.length; i++) {
// we create a reader for a certain document
PdfReader reader = new PdfReader(files[i].getAbsolutePath());
reader.consolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
List<Map<String, Object>> bookmarks = SimpleBookmark.getBookmarkList(reader);
if (bookmarks != null) {
if (pageOffset != 0) {
SimpleBookmark.shiftPageNumbersInRange(bookmarks, pageOffset, null);
}
master.addAll(bookmarks);
}
pageOffset += n;
System.out.println("There are " + n + " pages in " + files[i]);
if (i == 0) {
// step 1: creation of a document-object
document = new Document(reader.getPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document,
new FileOutputStream(pdf_file));
// step 3: we open the document
document.open();
}
// step 4: we add content
PdfImportedPage page;
for (int p = 0; p < n; ) {
++p;
page = writer.getImportedPage(reader, p);
writer.addPage(page);
System.out.println("Processed page " + p);
}
}
if (!master.isEmpty()) {
writer.setOutlines(master);
}
// step 5: we close the document
document.close();
} catch (Exception e) {
e.printStackTrace();
}
| 625
| 595
| 1,220
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Decrypt.java
|
Decrypt
|
createFrame
|
class Decrypt extends AbstractTool {
static {
addVersion("$Id: Decrypt.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Decrypt object.
*/
public Decrypt() {
arguments.add(new FileArgument(this, "srcfile", "The file you want to decrypt", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "The file to which the decrypted PDF has to be written", true,
new PdfFilter()));
arguments.add(new StringArgument(this, "ownerpassword", "The ownerpassword you want to add to the PDF file"));
}
/**
* Decrypts an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
Decrypt tool = new Decrypt();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
byte[] ownerpassword = null;
if (getValue("ownerpassword") != null) {
ownerpassword = ((String) getValue("ownerpassword")).getBytes();
}
PdfReader reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath(), ownerpassword);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream((File) getValue("destfile")));
stamper.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
internalFrame = new JInternalFrame("Decrypt", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Decrypt OPENED ===");
| 808
| 69
| 877
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Divide.java
|
Divide
|
execute
|
class Divide extends AbstractTool {
static {
addVersion("$Id: Divide.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs an Divide object.
*/
public Divide() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcfile",
"The file you want to divide", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "The resulting PDF",
true, new PdfFilter()));
}
/**
* Generates a divided version of an NUp version of an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
Divide tool = new Divide();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Divide", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Divide OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the
// command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException(
"You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
File dest = (File) getValue("destfile");
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
// we retrieve the total number of pages and the page size
int total = reader.getNumberOfPages();
System.out.println("There are " + total
+ " pages in the original file.");
Rectangle pageSize = reader.getPageSize(1);
Rectangle newSize = new Rectangle(pageSize.getWidth() / 2, pageSize
.getHeight());
// step 1: creation of a document-object
Document document = new Document(newSize, 0, 0, 0, 0);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(dest));
// step 3: we open the document
document.open();
// step 4: adding the content
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
float offsetX, offsetY;
int p;
for (int i = 0; i < total; i++) {
p = i + 1;
pageSize = reader.getPageSize(p);
newSize = new Rectangle(pageSize.getWidth() / 2, pageSize.getHeight());
document.newPage();
offsetX = 0;
offsetY = 0;
page = writer.getImportedPage(reader, p);
cb.addTemplate(page, 1, 0, 0, 1, offsetX, offsetY);
document.newPage();
offsetX = -newSize.getWidth();
offsetY = 0;
page = writer.getImportedPage(reader, p);
cb.addTemplate(page, 1, 0, 0, 1, offsetX, offsetY);
}
// step 5: we close the document
document.close();
} catch (Exception e) {
e.printStackTrace();
}
| 621
| 612
| 1,233
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/DvdCover.java
|
DvdCover
|
execute
|
class DvdCover extends AbstractTool {
static {
addVersion("$Id: DvdCover.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a DvdCover object.
*/
public DvdCover() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW | MENU_EXECUTE_PRINT;
arguments.add(new FileArgument(this, "destfile", "The file to which the PDF has to be written", true,
new PdfFilter()));
arguments.add(new StringArgument(this, "title", "The title of the DVD"));
arguments.add(new ColorArgument(this, "backgroundcolor",
"The backgroundcolor of the DVD Cover (for instance 0xFFFFFF)"));
arguments.add(new ImageArgument(this, "front", "The front image of the DVD Cover"));
arguments.add(new ImageArgument(this, "back", "The back image of the DVD Cover"));
arguments.add(new ImageArgument(this, "side", "The side image of the DVD Cover"));
}
/**
* Generates a DVD Cover in PDF.
*
* @param args an array containing [0] a filename [1] a title [2] a backgroundcolor [3] a front image [4] a back
* image [5] a side image
*/
public static void main(String[] args) {
DvdCover tool = new DvdCover();
if (args.length == 0) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Make your own DVD Cover", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== DvdCover OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
// step 1: creation of a document-object
Rectangle pageSize = new Rectangle(780, 525);
if (getValue("backgroundcolor") != null) {
pageSize.setBackgroundColor((Color) getValue("backgroundcolor"));
}
Document document = new Document(pageSize);
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
if (getValue("destfile") == null) {
throw new DocumentException("You must provide a destination file!");
}
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream((File) getValue("destfile")));
// step 3: we open the document
document.open();
// step 4:
PdfContentByte cb = writer.getDirectContent();
if (getValue("title") != null) {
cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false), 24);
cb.beginText();
if (getValue("front") == null) {
cb.showTextAligned(Element.ALIGN_CENTER, (String) getValue("title"), 595f, 262f, 0f);
}
if (getValue("side") == null) {
cb.showTextAligned(Element.ALIGN_CENTER, (String) getValue("title"), 385f, 262f, 270f);
}
cb.endText();
}
cb.moveTo(370, 0);
cb.lineTo(370, 525);
cb.moveTo(410, 525);
cb.lineTo(410, 0);
cb.stroke();
if (getValue("front") != null) {
Image front = (Image) getValue("front");
front.scaleToFit(370, 525);
front.setAbsolutePosition(410f + (370f - front.getScaledWidth()) / 2f,
(525f - front.getScaledHeight()) / 2f);
document.add(front);
}
if (getValue("back") != null) {
Image back = (Image) getValue("back");
back.scaleToFit(370, 525);
back.setAbsolutePosition((370f - back.getScaledWidth()) / 2f, (525f - back.getScaledHeight()) / 2f);
document.add(back);
}
if (getValue("side") != null) {
Image side = (Image) getValue("side");
side.scaleToFit(40, 525);
side.setAbsolutePosition(370 + (40f - side.getScaledWidth()) / 2f,
(525f - side.getScaledHeight()) / 2f);
document.add(side);
}
// step 5: we close the document
document.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 781
| 862
| 1,643
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Encrypt.java
|
Encrypt
|
valueHasChanged
|
class Encrypt extends AbstractTool {
private final static int[] PERMISSIONS = {
PdfWriter.ALLOW_PRINTING,
PdfWriter.ALLOW_MODIFY_CONTENTS,
PdfWriter.ALLOW_COPY,
PdfWriter.ALLOW_MODIFY_ANNOTATIONS,
PdfWriter.ALLOW_FILL_IN,
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.ALLOW_ASSEMBLY,
PdfWriter.ALLOW_DEGRADED_PRINTING};
private final static String[] PERMISSION_OPTIONS = {
"AllowPrinting",
"AllowModifyContents",
"AllowCopy",
"AllowModifyAnnotations",
"AllowFillIn (128 bit only)",
"AllowScreenReaders (128 bit only)",
"AllowAssembly (128 bit only)",
"AllowDegradedPrinting (128 bit only)"
};
static {
addVersion("$Id: Encrypt.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs an Encrypt object.
*/
public Encrypt() {
arguments.add(new FileArgument(this, "srcfile", "The file you want to encrypt", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "The file to which the encrypted PDF has to be written", true,
new PdfFilter()));
arguments.add(new StringArgument(this, "ownerpassword", "The ownerpassword you want to add to the PDF file"));
arguments.add(new StringArgument(this, "userpassword", "The userpassword you want to add to the PDF file"));
arguments.add(new BitsetArgument(this, "permissions", "Permissions on the file", PERMISSION_OPTIONS));
OptionArgument oa = new OptionArgument(this, "strength", "Strength of the encryption");
oa.addOption("40 bit encryption", "40");
oa.addOption("128 bit encryption", "128");
arguments.add(oa);
}
/**
* Encrypts an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
Encrypt tool = new Encrypt();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Encrypt", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Encrypt OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
int permissions = 0;
String p = (String) getValue("permissions");
if (p != null) {
for (int k = 0; k < p.length(); ++k) {
permissions |= (p.charAt(k) == '0' ? 0 : PERMISSIONS[k]);
}
}
byte[] userpassword = null;
if (getValue("userpassword") != null) {
userpassword = ((String) getValue("userpassword")).getBytes();
}
byte[] ownerpassword = null;
if (getValue("ownerpassword") != null) {
ownerpassword = ((String) getValue("ownerpassword")).getBytes();
}
PdfReader reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath());
PdfEncryptor.encrypt(
reader,
new FileOutputStream((File) getValue("destfile")),
userpassword,
ownerpassword,
permissions,
"128".equals(getValue("strength"))
);
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {<FILL_FUNCTION_BODY>}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
| 1,335
| 51
| 1,386
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/ExtractAttachments.java
|
ExtractAttachments
|
unpackFile
|
class ExtractAttachments extends AbstractTool {
static {
addVersion("$Id: ExtractAttachments.java 3712 2009-02-20 20:11:31Z xlv $");
}
/**
* Constructs a ExtractAttachements object.
*/
public ExtractAttachments() {
FileArgument f = new FileArgument(this, "srcfile",
"The file you want to operate on", false, new PdfFilter());
f.setLabel(new PdfInformationPanel());
arguments.add(f);
}
/**
* Extract the attachments of a PDF.
*
* @param args String[]
*/
public static void main(String[] args) {
ExtractAttachments tool = new ExtractAttachments();
if (args.length < 1) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* Unpacks a file attachment.
*
* @param reader The object that reads the PDF document
* @param filespec The dictionary containing the file specifications
* @param outPath The path where the attachment has to be written
* @throws IOException on error
*/
public static void unpackFile(PdfReader reader, PdfDictionary filespec,
String outPath) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("ExtractAttachments", true, false,
true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== ExtractAttachments OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException(
"You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
final File parentFile = src.getParentFile();
final String outPath;
if (parentFile != null) {
outPath = parentFile.getAbsolutePath();
} else {
outPath = "";
}
PdfDictionary catalog = reader.getCatalog();
PdfDictionary names = catalog.getAsDict(PdfName.NAMES);
if (names != null) {
PdfDictionary embFiles = names.getAsDict(new PdfName("EmbeddedFiles"));
if (embFiles != null) {
HashMap<String, PdfObject> embMap = PdfNameTree.readTree(embFiles);
for (PdfObject pdfObject : embMap.values()) {
PdfDictionary filespec = (PdfDictionary) PdfReader
.getPdfObject(pdfObject);
unpackFile(reader, filespec, outPath);
}
}
}
for (int k = 1; k <= reader.getNumberOfPages(); ++k) {
PdfArray annots = reader.getPageN(k).getAsArray(PdfName.ANNOTS);
if (annots == null) {
continue;
}
for (PdfObject pdfObject : annots.getElements()) {
PdfDictionary annot = (PdfDictionary) PdfReader.getPdfObject(pdfObject);
PdfName subType = annot.getAsName(PdfName.SUBTYPE);
if (!PdfName.FILEATTACHMENT.equals(subType)) {
continue;
}
PdfDictionary filespec = annot.getAsDict(PdfName.FS);
unpackFile(reader, filespec, outPath);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the
// command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
throw new InstantiationException("There is more than one destfile.");
}
}
|
if (filespec == null) {
return;
}
PdfName type = filespec.getAsName(PdfName.TYPE);
if (!PdfName.F.equals(type) && !PdfName.FILESPEC.equals(type)) {
return;
}
PdfDictionary ef = filespec.getAsDict(PdfName.EF);
if (ef == null) {
return;
}
PdfString fn = filespec.getAsString(PdfName.F);
System.out.println("Unpacking file '" + fn + "' to " + outPath);
if (fn == null) {
return;
}
File fLast = new File(fn.toUnicodeString());
File fullPath = new File(outPath, fLast.getName());
if (fullPath.exists()) {
return;
}
PRStream prs = (PRStream) PdfReader.getPdfObject(ef.get(PdfName.F));
if (prs == null) {
return;
}
byte[] b = PdfReader.getStreamBytes(prs);
FileOutputStream fout = new FileOutputStream(fullPath);
fout.write(b);
fout.close();
| 1,249
| 317
| 1,566
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Handouts.java
|
Handouts
|
execute
|
class Handouts extends AbstractTool {
static {
addVersion("$Id: Handouts.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Handouts object.
*/
public Handouts() {
arguments.add(new FileArgument(this, "srcfile", "The file you want to convert", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "The file to which the Handout has to be written", true,
new PdfFilter()));
OptionArgument oa = new OptionArgument(this, "pages", "The number of pages you want on one handout page");
oa.addOption("2 pages on 1", "2");
oa.addOption("3 pages on 1", "3");
oa.addOption("4 pages on 1", "4");
oa.addOption("5 pages on 1", "5");
oa.addOption("6 pages on 1", "6");
oa.addOption("7 pages on 1", "7");
oa.addOption("8 pages on 1", "8");
arguments.add(oa);
}
/**
* Converts a PDF file to a PDF file usable as Handout.
*
* @param args String[]
*/
public static void main(String[] args) {
Handouts tool = new Handouts();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Handouts", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Handouts OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
File dest = (File) getValue("destfile");
int pages;
try {
pages = Integer.parseInt((String) getValue("pages"));
} catch (Exception e) {
pages = 4;
}
float x1 = 30f;
float x2 = 280f;
float x3 = 320f;
float x4 = 565f;
float[] y1 = new float[pages];
float[] y2 = new float[pages];
float height = (778f - (20f * (pages - 1))) / pages;
y1[0] = 812f;
y2[0] = 812f - height;
for (int i = 1; i < pages; i++) {
y1[i] = y2[i - 1] - 20f;
y2[i] = y1[i] - height;
}
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(PageSize.A4);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3: we open the document
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
int p = 0;
// step 4: we add content
while (i < n) {
i++;
Rectangle rect = reader.getPageSizeWithRotation(i);
float factorx = (x2 - x1) / rect.getWidth();
float factory = (y1[p] - y2[p]) / rect.getHeight();
float factor = (factorx < factory ? factorx : factory);
float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.getWidth() * factor) / 2f);
float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.getHeight() * factor) / 2f);
page = writer.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.getHeight() * factor);
} else {
cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
}
cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
cb.moveTo(x3, l);
cb.lineTo(x4, l);
}
cb.rectangle(x1 + dx, y2[p] + dy, rect.getWidth() * factor, rect.getHeight() * factor);
cb.stroke();
System.out.println("Processed page " + i);
p++;
if (p == pages) {
p = 0;
document.newPage();
}
}
// step 5: we close the document
document.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 756
| 1,135
| 1,891
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/ImageXRefViewer.java
|
ImageXRefViewer
|
execute
|
class ImageXRefViewer extends AbstractTool {
static {
addVersion("$Id: ImageXRefViewer.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* The total number of pictures inside the PDF.
*/
int total_number_of_pictures = 0;
/**
* The spinner that will allow you to select an image.
*/
JSpinner jSpinner = new JSpinner();
/**
* The panel that will show the images.
*/
JPanel image_panel = new JPanel();
/**
* The layout with the images.
*/
CardLayout layout = new CardLayout();
/**
* Creates a ViewImageXObjects object.
*/
public ImageXRefViewer() {
arguments.add(new FileArgument(this, "srcfile",
"The file you want to inspect", false, new PdfFilter()));
}
/**
* Shows the images that are in the PDF as Image XObjects.
*
* @param args String[]
*/
public static void main(String[] args) {
ImageXRefViewer tool = new ImageXRefViewer();
if (args.length < 1) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
throw new InstantiationException("There is no file to show.");
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("View Image XObjects", true, false,
true);
internalFrame.setSize(500, 300);
internalFrame.setJMenuBar(getMenubar());
internalFrame.getContentPane().setLayout(new BorderLayout());
JPanel master_panel = new JPanel();
master_panel.setLayout(new BorderLayout());
internalFrame.getContentPane().add(master_panel,
java.awt.BorderLayout.CENTER);
// images
image_panel.setLayout(layout);
jSpinner.addChangeListener(new SpinnerListener(this));
image_panel.setBorder(BorderFactory.createEtchedBorder());
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(image_panel);
master_panel.add(scrollPane, java.awt.BorderLayout.CENTER);
// spinner
JPanel spinner_panel = new JPanel();
spinner_panel.setLayout(new BorderLayout());
spinner_panel.add(jSpinner, java.awt.BorderLayout.CENTER);
JLabel image_label = new JLabel();
image_label.setHorizontalAlignment(SwingConstants.CENTER);
image_label.setText("images");
spinner_panel.add(image_label, java.awt.BorderLayout.NORTH);
master_panel.add(spinner_panel, java.awt.BorderLayout.NORTH);
System.out.println("=== Image XObject Viewer OPENED ===");
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
// do nothing
}
/**
* Reflects the change event in the JSpinner object.
*
* @param evt ChangeEvent
*/
public void propertyChange(ChangeEvent evt) {
int picture = Integer.parseInt(jSpinner.getValue().toString());
if (picture < 0) {
picture = 0;
jSpinner.setValue("0");
}
if (picture >= total_number_of_pictures) {
picture = total_number_of_pictures - 1;
jSpinner.setValue(String.valueOf(picture));
}
layout.show(image_panel, String.valueOf(picture));
image_panel.repaint();
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
class SpinnerListener implements ChangeListener {
private ImageXRefViewer adaptee;
SpinnerListener(ImageXRefViewer adaptee) {
this.adaptee = adaptee;
}
/**
* @param e ChangeEvent
* @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent e) {
adaptee.propertyChange(e);
}
}
}
|
total_number_of_pictures = 0;
try {
if (getValue("srcfile") == null) {
throw new InstantiationException(
"You need to choose a sourcefile");
}
EventDispatchingThread task = new EventDispatchingThread() {
public Object construct() {
try {
PdfReader reader = new PdfReader(
((File) getValue("srcfile")).getAbsolutePath());
for (int i = 0; i < reader.getXrefSize(); i++) {
PdfObject pdfobj = reader.getPdfObject(i);
if (pdfobj != null) {
if (pdfobj.isStream()) {
PdfStream pdfdict = (PdfStream) pdfobj;
PdfObject pdfsubtype = pdfdict
.get(PdfName.SUBTYPE);
if (pdfsubtype == null) {
continue;
}
if (!pdfsubtype.toString().equals(
PdfName.IMAGE.toString())) {
continue;
}
System.out.println("total_number_of_pictures: "
+ total_number_of_pictures);
System.out.println("height:"
+ pdfdict.get(PdfName.HEIGHT));
System.out.println("width:"
+ pdfdict.get(PdfName.WIDTH));
System.out.println("bitspercomponent:"
+ pdfdict.get(PdfName.BITSPERCOMPONENT));
byte[] barr = PdfReader
.getStreamBytesRaw((PRStream) pdfdict);
java.awt.Image im = Toolkit
.getDefaultToolkit().createImage(barr);
javax.swing.ImageIcon ii = new javax.swing.ImageIcon(im);
JLabel label = new JLabel();
label.setIcon(ii);
image_panel.add(label, String.valueOf(total_number_of_pictures++));
}
}
}
} catch (InstantiationException | IOException ex) {
}
internalFrame.setCursor(Cursor.getDefaultCursor());
return null;
}
};
internalFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task.start();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame, e.getMessage(), e
.getClass().getName(), JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 1,292
| 628
| 1,920
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/InspectPDF.java
|
InspectPDF
|
main
|
class InspectPDF extends AbstractTool {
static {
addVersion("$Id: InspectPDF.java 3826 2009-03-31 17:46:18Z blowagie $");
}
/**
* Constructs an InpectPDF object.
*/
public InspectPDF() {
arguments.add(new FileArgument(this, "srcfile", "The file you want to inspect", false, new PdfFilter()));
arguments.add(new StringArgument(this, "ownerpassword", "The owner password if the file is encrypt"));
}
/**
* Inspects an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Pdf Information", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Pdf Information OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
PdfReader reader;
if (getValue("ownerpassword") == null) {
reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath());
} else {
reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath(),
((String) getValue("ownerpassword")).getBytes());
}
// Some general document information and page size
System.out.println("=== Document Information ===");
System.out.println("PDF Version: " + reader.getPdfVersion());
System.out.println("Number of pages: " + reader.getNumberOfPages());
System.out.println("Number of PDF objects: " + reader.getXrefSize());
System.out.println("File length: " + reader.getFileLength());
System.out.println("Encrypted? " + reader.isEncrypted());
if (reader.isEncrypted()) {
System.out.println("Permissions: " + PdfEncryptor.getPermissionsVerbose(reader.getPermissions()));
System.out.println("128 bit? " + reader.is128Key());
}
System.out.println("Rebuilt? " + reader.isRebuilt());
// Some metadata
System.out.println("=== Metadata ===");
Map<String, String> info = reader.getInfo();
String key;
String value;
for (Map.Entry<String, String> entry : info.entrySet()) {
key = entry.getKey();
value = entry.getValue();
System.out.println(key + ": " + value);
}
if (reader.getMetadata() == null) {
System.out.println("There is no XML Metadata in the file");
} else {
System.out.println("XML Metadata: " + new String(reader.getMetadata()));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
throw new InstantiationException("There is no file to show.");
}
}
|
InspectPDF tool = new InspectPDF();
if (args.length < 1) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
| 1,103
| 58
| 1,161
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/NUp.java
|
NUp
|
execute
|
class NUp extends AbstractTool {
static {
addVersion("$Id: NUp.java 3427 2008-05-24 18:32:31Z xlv $");
}
/**
* Constructs an NUp object.
*/
public NUp() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcfile", "The file you want to N-up", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "The resulting PDF", true, new PdfFilter()));
OptionArgument oa = new OptionArgument(this, "pow2", "The number of pages you want to copy to 1 page");
oa.addOption("2", "1");
oa.addOption("4", "2");
oa.addOption("8", "3");
oa.addOption("16", "4");
oa.addOption("32", "5");
oa.addOption("64", "6");
arguments.add(oa);
}
/**
* Generates an NUp version of an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
NUp tool = new NUp();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("N-up", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== N-up OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file");
}
File dest = (File) getValue("destfile");
int pow2;
try {
pow2 = Integer.parseInt((String) getValue("pow2"));
} catch (Exception e) {
pow2 = 1;
}
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
// we retrieve the total number of pages and the page size
int total = reader.getNumberOfPages();
System.out.println("There are " + total + " pages in the original file.");
Rectangle pageSize = reader.getPageSize(1);
Rectangle newSize = (pow2 % 2) == 0 ? new Rectangle(pageSize.getWidth(), pageSize.getHeight())
: new Rectangle(pageSize.getHeight(), pageSize.getWidth());
Rectangle unitSize = new Rectangle(pageSize.getWidth(), pageSize.getHeight());
Rectangle currentSize;
for (int i = 0; i < pow2; i++) {
unitSize = new Rectangle(unitSize.getHeight() / 2, unitSize.getWidth());
}
int n = (int) Math.pow(2, pow2);
int r = (int) Math.pow(2, pow2 / 2);
int c = n / r;
// step 1: creation of a document-object
Document document = new Document(newSize, 0, 0, 0, 0);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
// step 3: we open the document
document.open();
// step 4: adding the content
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
float offsetX, offsetY, factor;
int p;
for (int i = 0; i < total; i++) {
if (i % n == 0) {
document.newPage();
}
p = i + 1;
offsetX = unitSize.getWidth() * ((i % n) % c);
offsetY = newSize.getHeight() - (unitSize.getHeight() * (((i % n) / c) + 1));
currentSize = reader.getPageSize(p);
factor = Math.min(unitSize.getWidth() / currentSize.getWidth(),
unitSize.getHeight() / currentSize.getHeight());
offsetX += (unitSize.getWidth() - (currentSize.getWidth() * factor)) / 2f;
offsetY += (unitSize.getHeight() - (currentSize.getHeight() * factor)) / 2f;
page = writer.getImportedPage(reader, p);
cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
}
// step 5: we close the document
document.close();
} catch (Exception e) {
e.printStackTrace();
}
| 734
| 845
| 1,579
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Normalize.java
|
Ausrichtung
|
klassifiziere
|
class Ausrichtung {
static final float tolerance = 60;
static final int UNKNOWN = 0;
static final int A4Portrait = 1;
static final int A4Landscape = 2;
static final int A3Portrait = 3;
static final int A3Landscape = 4;
float rotation;
Rectangle rect;
float m5;
float m6;
int type;
public Ausrichtung() {
this(0, new Rectangle(1, 1));
}
public Ausrichtung(float rotation, Rectangle unrotatedoriginalrect) {
this.rotation = rotation;
if ((rotation == 90) || (rotation == 270)) {
rect = unrotatedoriginalrect.rotate();
} else {
rect = unrotatedoriginalrect;
}
m5 = rect.getWidth();
m6 = rect.getHeight();
klassifiziere();
}
private void klassifiziere() {<FILL_FUNCTION_BODY>}
public float getM5() {
return m5;
}
public float getM6() {
return m6;
}
public String toString() {
String back;
switch (type) {
case UNKNOWN:
back = rect.getWidth() + "*" + rect.getHeight();
break;
case A3Landscape:
back = "A3 Landscape";
break;
case A3Portrait:
back = "A3 Portrait";
break;
case A4Landscape:
back = "A4 Landscape";
break;
case A4Portrait:
back = "A4 Portrait";
break;
default:
back = "";
}
return back;
}
public void rotate() {
rect = rect.rotate();
m5 = rect.getWidth();
m6 = rect.getHeight();
rotation += 90;
rotation = rotation % 360;
klassifiziere();
}
public float getRotation() {
return rotation;
}
}
|
if (Math.abs(rect.getWidth() - 595) < tolerance &&
Math.abs(rect.getHeight() - 842) < tolerance) {
this.type = A4Portrait;
} else if (Math.abs(rect.getWidth() - 842) < tolerance &&
Math.abs(rect.getHeight() - 595) < tolerance) {
this.type = A4Landscape;
} else if (Math.abs(rect.getWidth() - 1190) < tolerance &&
Math.abs(rect.getHeight() - 842) < tolerance) {
this.type = A3Landscape;
} else if (Math.abs(rect.getWidth() - 842) < tolerance &&
Math.abs(rect.getHeight() - 1190) < tolerance) {
this.type = A3Portrait;
} else {
type = UNKNOWN;
}
| 562
| 244
| 806
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/PhotoAlbum.java
|
PhotoAlbum
|
execute
|
class PhotoAlbum extends AbstractTool {
static {
addVersion("$Id: PhotoAlbum.java 3451 2008-05-26 02:56:13Z xlv $");
}
/**
* Constructs a PhotoAlbum object.
*/
public PhotoAlbum() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcdir",
"The directory containing the image files", false,
new DirFilter()));
arguments.add(new FileArgument(this, "destfile",
"The file to which the converted TIFF has to be written", true,
new PdfFilter()));
}
/**
* Converts a tiff file to PDF.
*
* @param args String[]
*/
public static void main(String[] args) {
PhotoAlbum tool = new PhotoAlbum();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("PhotoAlbum", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== PhotoAlbum OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
if (getValue("srcdir") == null) {
throw new InstantiationException(
"You need to choose a source directory");
}
File directory = (File) getValue("srcdir");
if (directory.isFile()) {
directory = directory.getParentFile();
}
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
File pdf_file = (File) getValue("destfile");
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdf_file));
writer.setViewerPreferences(PdfWriter.PageModeUseThumbs);
PdfPageLabels pageLabels = new PdfPageLabels();
int dpiX, dpiY;
float imgWidthPica, imgHeightPica;
TreeSet<File> images = new TreeSet<>();
File[] files = directory.listFiles();
if (files == null) {
throw new NullPointerException("listFiles() returns null");
}
for (File file : files) {
if (file.isFile()) {
images.add(file);
}
}
String label;
for (File image : images) {
System.out.println("Testing image: " + image.getName());
try {
Image img = Image.getInstance(image.getAbsolutePath());
String caption = "";
dpiX = img.getDpiX();
if (dpiX == 0) {
dpiX = 72;
}
dpiY = img.getDpiY();
if (dpiY == 0) {
dpiY = 72;
}
imgWidthPica = (72 * img.getPlainWidth()) / dpiX;
imgHeightPica = (72 * img.getPlainHeight()) / dpiY;
img.scaleAbsolute(imgWidthPica, imgHeightPica);
document.setPageSize(new Rectangle(imgWidthPica,
imgHeightPica));
if (document.isOpen()) {
document.newPage();
} else {
document.open();
}
img.setAbsolutePosition(0, 0);
document.add(img);
BaseFont bf = BaseFont.createFont("Helvetica",
BaseFont.WINANSI,
false);
PdfGState gs1 = new PdfGState();
gs1.setBlendMode(PdfGState.BM_OVERLAY);
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.setGState(gs1);
cb.beginText();
cb.setFontAndSize(bf, 40);
cb.setTextMatrix(50, 50);
cb.showText(caption);
cb.endText();
cb.restoreState();
label = image.getName();
if (label.lastIndexOf('.') > 0) {
label = label.substring(0, label.lastIndexOf('.'));
}
pageLabels.addPageLabel(writer.getPageNumber(),
PdfPageLabels.EMPTY, label);
System.out.println("Added image: " + image.getName());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
if (document.isOpen()) {
writer.setPageLabels(pageLabels);
document.close();
} else {
System.err.println("No images were found in directory " +
directory.getAbsolutePath());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 634
| 995
| 1,629
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/RemoveLaunchApplication.java
|
RemoveLaunchApplication
|
createFrame
|
class RemoveLaunchApplication
extends AbstractTool {
static {
addVersion(
"$Id: RemoveLaunchApplication.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a ReversePages object.
*/
public RemoveLaunchApplication() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcfile",
"The file from which you want to remove Launch Application actions", false,
new PdfFilter()));
arguments.add(new FileArgument(this, "destfile",
"The file to which the cleaned up version of the original PDF has to be written", true,
new PdfFilter()));
}
/**
* Copy an existing PDF and replace the Launch Application Action with JavaScript alerts.
*
* @param args String[]
*/
public static void main(String[] args) {
RemoveLaunchApplication tool = new RemoveLaunchApplication();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
File dest = (File) getValue("destfile");
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
PdfObject o;
PdfDictionary d;
PdfDictionary l;
PdfName n;
for (int i = 1; i < reader.getXrefSize(); i++) {
o = reader.getPdfObject(i);
if (o instanceof PdfDictionary) {
d = (PdfDictionary) o;
o = d.get(PdfName.A);
if (o == null) {
continue;
}
if (o instanceof PdfDictionary) {
l = (PdfDictionary) o;
} else {
PRIndirectReference r = (PRIndirectReference) o;
l = (PdfDictionary) reader.getPdfObject(r.getNumber());
}
n = (PdfName) l.get(PdfName.S);
if (PdfName.LAUNCH.equals(n)) {
if (l.get(PdfName.F) != null) {
System.out.println("Removed: " + l.get(PdfName.F));
l.remove(PdfName.F);
}
if (l.get(PdfName.WIN) != null) {
System.out.println("Removed: " + l.get(PdfName.WIN));
l.remove(PdfName.WIN);
}
l.put(PdfName.S, PdfName.JAVASCRIPT);
l.put(PdfName.JS, new PdfString("app.alert('Launch Application Action removed by iText');\r"));
}
}
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
internalFrame = new JInternalFrame("Remove Launch Applications", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Remove Launch Applications OPENED ===");
| 1,172
| 71
| 1,243
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/ReversePages.java
|
ReversePages
|
createFrame
|
class ReversePages
extends AbstractTool {
static {
addVersion(
"$Id: ReversePages.java 3271 2008-04-18 20:39:42Z xlv $");
}
FileArgument destfile = null;
/**
* Constructs a ReversePages object.
*/
public ReversePages() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
FileArgument inputfile = null;
inputfile = new FileArgument(this, "srcfile",
"The file you want to reorder", false,
new PdfFilter());
arguments.add(inputfile);
destfile = new FileArgument(this, "destfile",
"The file to which the reordered version of the original PDF has to be written", true,
new PdfFilter());
arguments.add(destfile);
inputfile.addPropertyChangeListener(destfile);
}
/**
* Take pages from an existing PDF and copy them in reverse order into a new PDF.
*
* @param args String[]
*/
public static void main(String[] args) {
ReversePages tool = new ReversePages();
if (args.length < 2) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
File dest = (File) getValue("destfile");
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
System.out.println("The original file had " + reader.getNumberOfPages() +
" pages.");
int pages = reader.getNumberOfPages();
ArrayList<Integer> li = new ArrayList<>();
for (int i = pages; i > 0; i--) {
li.add(i);
}
reader.selectPages(li);
System.err.println("The new file has " + pages + " pages.");
Document document = new Document(reader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(document,
new FileOutputStream(dest.getAbsolutePath()));
document.open();
PdfImportedPage page;
for (int i = 0; i < pages; ) {
++i;
System.out.println("Processed page " + i);
page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null) {
copy.copyAcroForm(reader);
}
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
if (destfile.getValue() == null && arg.getName().equalsIgnoreCase("srcfile")) {
String filename = arg.getValue().toString();
String filenameout = filename.substring(0, filename.indexOf(".",
filename.length() - 4)) + "_out.pdf";
destfile.setValue(filenameout);
}
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
internalFrame = new JInternalFrame("ReversePages", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== ReversePages OPENED ===");
| 1,139
| 73
| 1,212
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/SelectedPages.java
|
SelectedPages
|
createFrame
|
class SelectedPages extends AbstractTool {
static {
addVersion("$Id: SelectedPages.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a SelectedPages object.
*/
public SelectedPages() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW;
arguments.add(new FileArgument(this, "srcfile", "The file you want to split", false, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile",
"The file to which the first part of the original PDF has to be written", true, new PdfFilter()));
arguments.add(new StringArgument(this, "selection", "A selection of pages (see Help for more info)"));
}
/**
* Generates a PDF file with selected pages from an existing PDF.
*
* @param args String[]
*/
public static void main(String[] args) {
SelectedPages tool = new SelectedPages();
if (args.length < 4) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {<FILL_FUNCTION_BODY>}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination file for the first part of the PDF");
}
File dest = (File) getValue("destfile");
String selection = (String) getValue("selection");
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
System.out.println("The original file had " + reader.getNumberOfPages() + " pages.");
reader.selectPages(selection);
int pages = reader.getNumberOfPages();
System.err.println("The new file has " + pages + " pages.");
Document document = new Document(reader.getPageSizeWithRotation(1));
PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest.getAbsolutePath()));
document.open();
PdfImportedPage page;
for (int i = 0; i < pages; ) {
++i;
System.out.println("Processed page " + i);
page = copy.getImportedPage(reader, i);
copy.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null) {
copy.copyAcroForm(reader);
}
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
internalFrame = new JInternalFrame("SelectedPages", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== SelectedPages OPENED ===");
| 994
| 70
| 1,064
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Split.java
|
Split
|
execute
|
class Split extends AbstractTool {
static {
addVersion("$Id: Split.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs an Split object.
*/
public Split() {
FileArgument f = new FileArgument(this, "srcfile", "The file you want to split", false, new PdfFilter());
f.setLabel(new PdfInformationPanel());
arguments.add(f);
arguments.add(new FileArgument(this, "destfile1",
"The file to which the first part of the original PDF has to be written", true, new PdfFilter()));
arguments.add(new FileArgument(this, "destfile2",
"The file to which the second part of the original PDF has to be written", true, new PdfFilter()));
arguments.add(new IntegerArgument(this, "pagenumber", "The pagenumber where you want to split"));
}
/**
* Split a PDF in two separate PDF files.
*
* @param args String[]
*/
public static void main(String[] args) {
Split tool = new Split();
if (args.length < 4) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Split", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Split OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile1");
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException("You need to choose a sourcefile");
}
File src = (File) getValue("srcfile");
if (getValue("destfile1") == null) {
throw new InstantiationException("You need to choose a destination file for the first part of the PDF");
}
File file1 = (File) getValue("destfile1");
if (getValue("destfile2") == null) {
throw new InstantiationException(
"You need to choose a destination file for the second part of the PDF");
}
File file2 = (File) getValue("destfile2");
int pagenumber = Integer.parseInt((String) getValue("pagenumber"));
// we create a reader for a certain document
PdfReader reader = new PdfReader(src.getAbsolutePath());
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
if (pagenumber < 2 || pagenumber > n) {
throw new DocumentException(
"You can't split this document at page " + pagenumber + "; there is no such page.");
}
// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(file1));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(file2));
// step 3: we open the document
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
i++;
document1.setPageSize(reader.getPageSizeWithRotation(i));
document1.newPage();
page = writer1.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
} else {
cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
while (i < n) {
i++;
document2.setPageSize(reader.getPageSizeWithRotation(i));
document2.newPage();
page = writer2.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
} else {
cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// step 5: we close the document
document1.close();
document2.close();
} catch (Exception e) {
e.printStackTrace();
}
| 691
| 918
| 1,609
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/Txt2Pdf.java
|
Txt2Pdf
|
execute
|
class Txt2Pdf extends AbstractTool {
static {
addVersion("$Id: Txt2Pdf.java 3271 2008-04-18 20:39:42Z xlv $");
}
/**
* Constructs a Txt2Pdf object.
*/
public Txt2Pdf() {
menuoptions = MENU_EXECUTE | MENU_EXECUTE_SHOW | MENU_EXECUTE_PRINT_SILENT;
arguments.add(new FileArgument(this, "srcfile", "The file you want to convert", false));
arguments.add(new FileArgument(this, "destfile", "The file to which the converted text has to be written", true,
new PdfFilter()));
PageSizeArgument oa1 = new PageSizeArgument(this, "pagesize", "Pagesize");
arguments.add(oa1);
OptionArgument oa2 = new OptionArgument(this, "orientation", "Orientation of the page");
oa2.addOption("Portrait", "PORTRAIT");
oa2.addOption("Landscape", "LANDSCAPE");
arguments.add(oa2);
}
/**
* Converts a monospaced txt file to a PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
Txt2Pdf tool = new Txt2Pdf();
if (args.length < 3) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("Txt2Pdf", true, true, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Txt2Pdf OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {<FILL_FUNCTION_BODY>}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
try {
String line = null;
Document document;
Font f;
Rectangle pagesize = (Rectangle) getValue("pagesize");
if ("LANDSCAPE".equals(getValue("orientation"))) {
f = FontFactory.getFont(FontFactory.COURIER, 10);
document = new Document(pagesize.rotate(), 36, 9, 36, 36);
} else {
f = FontFactory.getFont(FontFactory.COURIER, 11);
document = new Document(pagesize, 72, 36, 36, 36);
}
BufferedReader in = new BufferedReader(new FileReader((File) getValue("srcfile")));
PdfWriter.getInstance(document, new FileOutputStream((File) getValue("destfile")));
document.open();
while ((line = in.readLine()) != null) {
document.add(new Paragraph(12, line, f));
}
document.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 761
| 325
| 1,086
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/XML2Bookmarks.java
|
XML2Bookmarks
|
valueHasChanged
|
class XML2Bookmarks extends AbstractTool {
static {
addVersion("$Id: XML2Bookmarks.java 3373 2008-05-12 16:21:24Z xlv $");
}
/**
* Constructs an XML2Bookmarks object.
*/
public XML2Bookmarks() {
arguments.add(new FileArgument(this, "xmlfile", "the bookmarks in XML", false));
arguments.add(new FileArgument(this, "pdffile", "the PDF to which you want to add bookmarks", false,
new PdfFilter()));
arguments.add(new FileArgument(this, "destfile", "the resulting PDF", true, new PdfFilter()));
}
/**
* Allows you to generate an index file in HTML containing Bookmarks to an existing PDF file.
*
* @param args String[]
*/
public static void main(String[] args) {
XML2Bookmarks tool = new XML2Bookmarks();
if (args.length < 3) {
System.err.println(tool.getUsage());
}
tool.setMainArguments(args);
tool.execute();
}
/**
* @see com.lowagie.toolbox.AbstractTool#createFrame()
*/
protected void createFrame() {
internalFrame = new JInternalFrame("XML + PDF = PDF", true, true, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== XML2Bookmarks OPENED ===");
}
/**
* @see com.lowagie.toolbox.AbstractTool#execute()
*/
public void execute() {
try {
if (getValue("xmlfile") == null) {
throw new InstantiationException("You need to choose an xml file");
}
if (getValue("pdffile") == null) {
throw new InstantiationException("You need to choose a source PDF file");
}
if (getValue("destfile") == null) {
throw new InstantiationException("You need to choose a destination PDF file");
}
FileInputStream bmReader = new FileInputStream((File) getValue("xmlfile"));
List<Map<String, Object>> bookmarks = SimpleBookmark.importFromXML(bmReader);
bmReader.close();
PdfReader reader = new PdfReader(((File) getValue("pdffile")).getAbsolutePath());
reader.consolidateNamedDestinations();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream((File) getValue("destfile")));
stamper.setOutlines(bookmarks);
stamper.setViewerPreferences(reader.getSimpleViewerPreferences() | PdfWriter.PageModeUseOutlines);
stamper.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(internalFrame,
e.getMessage(),
e.getClass().getName(),
JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
}
/**
* @param arg StringArgument
* @see com.lowagie.toolbox.AbstractTool#valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument)
*/
public void valueHasChanged(AbstractArgument arg) {<FILL_FUNCTION_BODY>}
/**
* @return File
* @throws InstantiationException on error
* @see com.lowagie.toolbox.AbstractTool#getDestPathPDF()
*/
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
}
|
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the command line
return;
}
// represent the changes of the argument in the internal frame
| 950
| 51
| 1,001
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/watermarker/Watermarker.java
|
Watermarker
|
write
|
class Watermarker {
private final PdfReader reader;
private final ByteArrayOutputStream outputStream;
private final PdfStamper stamp;
private final String text;
private final int fontsize;
private final float opacity;
private Color color = BLACK;
private BaseFont font = null;
/**
* The main constructor with all mandatory arguments. By default, the color stays black.
*
* @param input the pdf content as a byte[]
* @param text the text to write as watermark
* @param fontsize the fontsize of the watermark
* @param opacity the opacity of the watermark
* @throws IOException on error
* @throws DocumentException on error
*/
public Watermarker(byte[] input, String text, int fontsize, float opacity) throws IOException, DocumentException {
this.reader = new PdfReader(input);
this.outputStream = new ByteArrayOutputStream();
this.stamp = new PdfStamper(reader, outputStream);
this.text = text;
this.fontsize = fontsize;
this.opacity = opacity;
}
/**
* To change the default black color by a new one.
*
* @param color the new color to use
* @return the current builder instance
*/
public Watermarker withColor(Color color) {
this.color = color;
return this;
}
public Watermarker withFont(final BaseFont font) {
this.font = font;
return this;
}
/**
* Write the watermark to the pdf given in entry.
*
* @return a brand new byte[] without modifying the original one.
* @throws IOException on error
* @throws DocumentException on error
*/
public byte[] write() throws IOException, DocumentException {<FILL_FUNCTION_BODY>}
}
|
Writer writer = new Writer(reader, stamp, text, fontsize, opacity, color);
if (font != null) {
writer.withFont(font);
}
writer.write();
return outputStream.toByteArray();
| 471
| 65
| 536
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/watermarker/WatermarkerTool.java
|
WatermarkerTool
|
execute
|
class WatermarkerTool extends AbstractTool {
FileArgument destfile;
/**
* This tool lets you add a text watermark to all pages of a document.
*/
public WatermarkerTool() {
super();
FileArgument inputfile = new FileArgument(this, "srcfile",
"The file you want to watermark", false, new PdfFilter());
arguments.add(inputfile);
arguments.add(new StringArgument(this, "watermark",
"The text that can be used as watermark"));
arguments.add(new IntegerArgument(this, "fontsize",
"The fontsize of the watermark text"));
arguments.add(new FloatArgument(this, "opacity",
"The opacity of the watermark text"));
destfile = new FileArgument(this, "destfile",
"The file to which the watermarked PDF has to be written",
true, new PdfFilter());
arguments.add(destfile);
arguments.add(new StringArgument(this, "color",
"The color of the watermark text"));
inputfile.addPropertyChangeListener(destfile);
}
/**
* This methods helps you running this tool as a standalone application.
*
* <p>
* Call it like this from command line: java com.lowagie.tools.plugins.Watermarker input.pdf Draft 230 0.2
* output.pdf #FF000000
*
* <p>
* "input.pdf" is the input file name to be processed
* <p>
* "Draft" is the text written as transparent "watermark" on top of each page
* <p>
* "230" is the font size
* <p>
* "0.2" is the opacity (1.0 completely opaque, 0.0 completely transparent)
* <p>
* "output.pdf" is the output file name
* <p>
* (Optional) "#FF0000" is the color (in hex format like #nnnnnn or 0xnnnnnn), #000000 (black) by default
*
* <p>
* Call it from within other Java code:
*
* <p>
* Watermarker.main(new String[]{"input.pdf","Draft","230","0.2","output.pdf","#FF000000"});
*
* @param args the srcfile, watermark text and destfile
*/
public static void main(String[] args) {
WatermarkerTool watermarkerTool = new WatermarkerTool();
if (args.length < 5 || args.length > 6) {
System.err.println(watermarkerTool.getUsage());
}
watermarkerTool.setMainArguments(args);
watermarkerTool.execute();
}
/**
* Creates the internal frame.
*/
@Override
protected void createFrame() {
internalFrame = new JInternalFrame("Watermark", true, false, true);
internalFrame.setSize(300, 80);
internalFrame.setJMenuBar(getMenubar());
System.out.println("=== Watermark OPENED ===");
}
/**
* Executes the tool (in most cases this generates a PDF file).
*/
@Override
public void execute() {<FILL_FUNCTION_BODY>}
/**
* Gets the PDF file that should be generated (or null if the output isn't a PDF file).
*
* @return the PDF file that should be generated
* @throws InstantiationException on error
*/
@Override
protected File getDestPathPDF() throws InstantiationException {
return (File) getValue("destfile");
}
/**
* Indicates that the value of an argument has changed.
*
* @param arg the argument that has changed
*/
@Override
public void valueHasChanged(AbstractArgument arg) {
if (internalFrame == null) {
// if the internal frame is null, the tool was called from the
// command line
return;
}
if (destfile.getValue() == null
&& arg.getName().equalsIgnoreCase("srcfile")) {
String filename = arg.getValue().toString();
String filenameout = filename.substring(0,
filename.indexOf(".", filename.length() - 4))
+ "_out.pdf";
destfile.setValue(filenameout);
}
}
}
|
try {
if (getValue("srcfile") == null) {
throw new InstantiationException(
"You need to choose a sourcefile");
}
if (getValue("destfile") == null) {
throw new InstantiationException(
"You need to choose a destination file");
}
if (getValue("watermark") == null) {
throw new InstantiationException(
"You need to add a text for the watermark");
}
if (getValue("fontsize") == null) {
throw new InstantiationException(
"You need to add a fontsize for the watermark");
}
if (getValue("opacity") == null) {
throw new InstantiationException(
"You need to add a opacity for the watermark");
}
Color color = BLACK;
if (getValue("color") != null) {
color = decode((String) getValue("color"));
}
PdfReader reader = new PdfReader(((File) getValue("srcfile")).getAbsolutePath());
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream((File) getValue("destfile")));
String text = (String) getValue("watermark");
int fontsize = parseInt((String) getValue("fontsize"));
float opacity = parseFloat((String) getValue("opacity"));
Writer writer = new Writer(reader, stamp, text, fontsize, opacity, color);
writer.write();
} catch (Exception e) {
JOptionPane.showMessageDialog(internalFrame, e.getMessage(), e
.getClass().getName(), JOptionPane.ERROR_MESSAGE);
System.err.println(e.getMessage());
}
| 1,137
| 432
| 1,569
|
<methods>public void <init>() ,public void actionPerformed(java.awt.event.ActionEvent) ,public abstract void execute() ,public ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> getArguments() ,public javax.swing.JInternalFrame getInternalFrame() ,public javax.swing.JMenuBar getMenubar() ,public java.lang.String getUsage() ,public java.lang.Object getValue(java.lang.String) throws java.lang.InstantiationException,public void setArguments(ArrayList<com.lowagie.toolbox.arguments.AbstractArgument>) ,public void setInternalFrame(javax.swing.JInternalFrame) ,public void setMainArguments(java.lang.String[]) ,public void setMenubar(javax.swing.JMenuBar) ,public abstract void valueHasChanged(com.lowagie.toolbox.arguments.AbstractArgument) <variables>public static final int MENU_EXECUTE,public static final int MENU_EXECUTE_PRINT,public static final int MENU_EXECUTE_PRINT_SILENT,public static final int MENU_EXECUTE_SHOW,protected ArrayList<com.lowagie.toolbox.arguments.AbstractArgument> arguments,private java.awt.Desktop awtdesktop,protected javax.swing.JInternalFrame internalFrame,private javax.swing.JMenuBar menubar,protected int menuoptions,public static ArrayList<java.lang.String> versionsarray
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/plugins/watermarker/Writer.java
|
Writer
|
write
|
class Writer {
private PdfReader reader;
private PdfStamper stamp;
private String text;
private int fontsize;
private float opacity;
private Color color;
private BaseFont font;
Writer(PdfReader reader, PdfStamper stamp, String text, int fontsize, float opacity, Color color) {
this.reader = reader;
this.stamp = stamp;
this.text = text;
this.fontsize = fontsize;
this.opacity = opacity;
this.color = color;
}
Writer withFont(final BaseFont font) {
this.font = font;
return this;
}
/**
* Does the magic, with all parameters already set and valid. At the end, the PDF file configured through the stamp
* parameter will be written.
*
* @throws DocumentException if the default "Helvetica" font cannot be created
* @throws IOException if the default "Helvetica" font cannot be created
*/
void write() throws IOException, DocumentException {<FILL_FUNCTION_BODY>}
}
|
final BaseFont bf = (font != null) ? font : createFont("Helvetica", WINANSI, false);
int pagecount = reader.getNumberOfPages();
PdfGState gs1 = new PdfGState();
gs1.setFillOpacity(opacity);
float txtwidth = bf.getWidthPoint(text, fontsize);
for (int i = 1; i <= pagecount; i++) {
PdfContentByte seitex = stamp.getOverContent(i);
Rectangle recc = reader.getCropBox(i);
recc.normalize();
float winkel = (float) Math.atan(recc.getHeight()
/ recc.getWidth());
float m1 = (float) Math.cos(winkel);
float m2 = (float) -Math.sin(winkel);
float m3 = (float) Math.sin(winkel);
float m4 = (float) Math.cos(winkel);
float xoff = (float) (-Math.cos(winkel) * txtwidth / 2 - Math
.sin(winkel) * fontsize / 2);
float yoff = (float) (Math.sin(winkel) * txtwidth / 2 - Math
.cos(winkel) * fontsize / 2);
seitex.saveState();
seitex.setGState(gs1);
seitex.beginText();
seitex.setFontAndSize(bf, fontsize);
seitex.setColorFill(color);
seitex.setTextMatrix(m1, m2, m3, m4,
xoff + recc.getWidth() / 2, yoff + recc.getHeight() / 2);
seitex.showText(text);
seitex.endText();
seitex.restoreState();
}
stamp.close();
| 281
| 486
| 767
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/swing/CustomDialog.java
|
CustomDialog
|
instantiateFloatDocument
|
class CustomDialog {
JDialog dialog = null;
JPanel jPanel1 = new JPanel();
PlainDocument plainDocument;
String msgString1;
Object[] array;
private JTextField textField = new JTextField(10);
private JOptionPane optionPane;
public CustomDialog(String msgstring, PlainDocument plainDocument) {
super();
this.setMsgString1(msgstring);
this.plainDocument = plainDocument;
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public CustomDialog() {
this("Enter a value:", new PlainDocument());
}
public static PlainDocument instantiateFloatDocument() {<FILL_FUNCTION_BODY>}
public static PlainDocument instantiateIntegerDocument() {
PlainDocument intDocument = new PlainDocument() {
private static final long serialVersionUID = -8735280090112457273L;
public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
super.insertString(offset, str, a);
try {
Integer.parseInt(super.getText(0, this.getLength()));
} catch (Exception ex) {
super.remove(offset, 1);
Toolkit.getDefaultToolkit().beep();
return;
}
}
};
return intDocument;
}
public static PlainDocument instantiateStringDocument() {
PlainDocument stringDocument = new PlainDocument() {
private static final long serialVersionUID = -1244429733606195330L;
public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
super.insertString(offset, str, a);
}
};
return stringDocument;
}
private void jbInit() throws Exception {
textField.setDocument(plainDocument);
}
public void setMsgString1(String msgString1) {
this.msgString1 = msgString1;
array = new Object[]{msgString1, textField};
optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
dialog = optionPane.createDialog(UIManager.getString(
"OptionPane.inputDialogTitle", null));
}
public String showInputDialog(String startvalue) {
textField.setText(startvalue);
dialog.setVisible(true);
dialog.dispose();
return textField.getText();
}
}
|
PlainDocument floatDocument = new PlainDocument() {
private static final long serialVersionUID = 1874451914306029381L;
public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
super.insertString(offset, str, a);
try {
Float.parseFloat(super.getText(0, this.getLength()));
} catch (Exception ex) {
super.remove(offset, 1);
Toolkit.getDefaultToolkit().beep();
return;
}
}
};
return floatDocument;
| 682
| 162
| 844
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/swing/EventDispatchingThread.java
|
EventDispatchingThread
|
start
|
class EventDispatchingThread {
/**
* The value of an object constructed by the construct() method.
*/
private Object value;
/**
* A wrapper for the tread that executes a time-consuming task.
*/
private ThreadWrapper thread;
/**
* Starts a thread. Executes the time-consuming task in the construct method; finally calls the finish().
*/
public EventDispatchingThread() {
final Runnable doFinished = this::finished;
Runnable doConstruct = () -> {
try {
value = construct();
} finally {
thread.clear();
}
SwingUtilities.invokeLater(doFinished);
};
Thread t = new Thread(doConstruct);
thread = new ThreadWrapper(t);
}
/**
* Implement this class; the time-consuming task will go here.
*
* @return Object
*/
public abstract Object construct();
/**
* Starts the thread.
*/
public void start() {<FILL_FUNCTION_BODY>}
/**
* Forces the thread to stop what it's doing.
*/
public void interrupt() {
Thread t = thread.get();
if (t != null) {
t.interrupt();
}
thread.clear();
}
/**
* Called on the event dispatching thread once the construct method has finished its task.
*/
public void finished() {
}
/**
* Returns the value created by the construct method.
*
* @return the value created by the construct method or null if the task was interrupted before it was finished.
*/
public Object get() {
while (true) {
Thread t = thread.get();
if (t == null) {
return value;
}
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // propagate
return null;
}
}
}
/**
* Inner class that holds the reference to the thread.
*/
private static class ThreadWrapper {
private Thread thread;
ThreadWrapper(Thread t) {
thread = t;
}
synchronized Thread get() {
return thread;
}
synchronized void clear() {
thread = null;
}
}
}
|
Thread t = thread.get();
if (t != null) {
t.start();
}
| 612
| 31
| 643
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/swing/FileList.java
|
FileList
|
jbInit
|
class FileList
extends JInternalFrame implements DropTargetListener {
private static final long serialVersionUID = -7238230038043975672L;
private final Vector<RowContainer> filevector = new Vector<>();
private final JPanel jPanel1 = new JPanel();
private final BorderLayout borderLayout1 = new BorderLayout();
private final JPanel jPanel2 = new JPanel();
private final BorderLayout borderLayout2 = new BorderLayout();
private final JScrollPane jScrollPane1 = new JScrollPane();
private final FileTableModel model = new FileTableModel();
private final JTable jTable1 = new JTable(model);
private final RowSorter<TableModel> sorter = new TableRowSorter<>(model);
private final BorderLayout borderLayout3 = new BorderLayout();
private final DropTarget dt = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true, null);
private final JPanel jPanel3 = new JPanel();
private final JLabel jLabel1 = new JLabel();
private final JLabel jLabel2 = new JLabel();
public FileList() {
super("FileList", true, true, true);
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() {<FILL_FUNCTION_BODY>}
public void dragEnter(DropTargetDragEvent dtde) {
}
public void dragOver(DropTargetDragEvent dtde) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("actionchanged");
}
public void drop(DropTargetDropEvent dtde) {
if ((dtde.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE) == 0) {
dtde.rejectDrop();
return;
}
dtde.acceptDrop(DnDConstants.ACTION_COPY);
Transferable transferable = dtde.getTransferable();
try {
// Transferable is not generic, so the cast can only be unchecked.
@SuppressWarnings("unchecked")
List<File> filelist = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
for (File f : filelist) {
filevector.add(new RowContainer(f));
model.fireTableDataChanged();
System.out.println(f.toString());
}
} catch (IOException | UnsupportedFlavorException ex) {
ex.printStackTrace();
}
dtde.dropComplete(true);
File[] filar = new File[filevector.size()];
for (int i = 0; i < filevector.size(); i++) {
filar[i] = filevector.get(i).getFile();
}
super.firePropertyChange("filevector",
null, filar);
}
public void dragExit(DropTargetEvent dte) {
}
public void jTable1_keyPressed(KeyEvent e) {
if (e.getKeyCode() == 127) {
int[] selected = jTable1.getSelectedRows();
for (int i = selected.length - 1; i >= 0; i--) {
model.removeRow(selected[i]);
model.fireTableDataChanged();
}
}
}
public void ftm_tableChanged(TableModelEvent e) {
int sum = 0;
for (RowContainer c : filevector) {
sum += c.getPages();
}
this.jLabel2.setText(Integer.toString(sum));
}
public Vector<RowContainer> getFilevector() {
return filevector;
}
public String getStringreprasentation() {
StringBuilder sb = new StringBuilder();
List<RowContainer> vec = getFilevector();
for (RowContainer c : vec) {
sb.append(c.getFile().getAbsolutePath()).append('\n');
}
return sb.toString();
}
static class FileListFtmTableModelAdapter
implements TableModelListener {
private final FileList adaptee;
FileListFtmTableModelAdapter(FileList adaptee) {
this.adaptee = adaptee;
}
public void tableChanged(TableModelEvent e) {
adaptee.ftm_tableChanged(e);
}
}
static class FileListJTable1KeyAdapter
extends KeyAdapter {
private final FileList adaptee;
FileListJTable1KeyAdapter(FileList adaptee) {
this.adaptee = adaptee;
}
public void keyPressed(KeyEvent e) {
adaptee.jTable1_keyPressed(e);
}
}
static class RowContainer {
private File file;
private int pages;
/**
* RowContainer
*/
RowContainer(File file) {
this.file = file;
PdfReader reader = null;
try {
reader = new PdfReader(file.getAbsolutePath());
} catch (IOException ignored) {
}
this.pages = reader.getNumberOfPages();
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
}
class FileTableModel extends AbstractTableModel {
private static final long serialVersionUID = -8173736343997473512L;
private final String[] columnNames = {
"Filename", "Pages", "Directory"};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return filevector.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
switch (col) {
case 0:
return filevector.get(row).getFile().getName();
case 1:
return filevector.get(row).getPages();
case 2:
return filevector.get(row).getFile().getParent();
}
return null;
}
public Class<?> getColumnClass(int col) {
switch (col) {
case 0:
return String.class;
case 1:
return Integer.class;
case 2:
return String.class;
}
return null;
}
public void removeRow(int row) {
filevector.remove(row);
}
}
}
|
this.getContentPane().setLayout(borderLayout1);
jTable1.addKeyListener(new FileListJTable1KeyAdapter(this));
jLabel1.setText("pages");
jLabel2.setText("-");
model.addTableModelListener(new FileListFtmTableModelAdapter(this));
this.getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(borderLayout2);
jPanel2.setLayout(borderLayout3);
jPanel1.add(jPanel2, java.awt.BorderLayout.CENTER);
jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel1.add(jPanel3, java.awt.BorderLayout.NORTH);
jPanel3.add(jLabel2);
jPanel3.add(jLabel1);
jScrollPane1.setViewportView(jTable1);
jTable1.setRowSorter(sorter);
// this.setSize(200,100);
this.pack();
| 1,762
| 276
| 2,038
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, boolean) ,public void <init>(java.lang.String, boolean, boolean) ,public void <init>(java.lang.String, boolean, boolean, boolean) ,public void <init>(java.lang.String, boolean, boolean, boolean, boolean) ,public void addInternalFrameListener(javax.swing.event.InternalFrameListener) ,public void dispose() ,public void doDefaultCloseAction() ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public javax.swing.JInternalFrame.JDesktopIcon getDesktopIcon() ,public javax.swing.JDesktopPane getDesktopPane() ,public final java.awt.Container getFocusCycleRootAncestor() ,public java.awt.Component getFocusOwner() ,public javax.swing.Icon getFrameIcon() ,public java.awt.Component getGlassPane() ,public javax.swing.event.InternalFrameListener[] getInternalFrameListeners() ,public javax.swing.JMenuBar getJMenuBar() ,public java.awt.Cursor getLastCursor() ,public int getLayer() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JMenuBar getMenuBar() ,public java.awt.Component getMostRecentFocusOwner() ,public java.awt.Rectangle getNormalBounds() ,public javax.swing.JRootPane getRootPane() ,public java.lang.String getTitle() ,public javax.swing.plaf.InternalFrameUI getUI() ,public java.lang.String getUIClassID() ,public final java.lang.String getWarningString() ,public void hide() ,public boolean isClosable() ,public boolean isClosed() ,public final boolean isFocusCycleRoot() ,public boolean isIcon() ,public boolean isIconifiable() ,public boolean isMaximizable() ,public boolean isMaximum() ,public boolean isResizable() ,public boolean isSelected() ,public void moveToBack() ,public void moveToFront() ,public void pack() ,public void remove(java.awt.Component) ,public void removeInternalFrameListener(javax.swing.event.InternalFrameListener) ,public void reshape(int, int, int, int) ,public void restoreSubcomponentFocus() ,public void setClosable(boolean) ,public void setClosed(boolean) throws java.beans.PropertyVetoException,public void setContentPane(java.awt.Container) ,public void setCursor(java.awt.Cursor) ,public void setDefaultCloseOperation(int) ,public void setDesktopIcon(javax.swing.JInternalFrame.JDesktopIcon) ,public final void setFocusCycleRoot(boolean) ,public void setFrameIcon(javax.swing.Icon) ,public void setGlassPane(java.awt.Component) ,public void setIcon(boolean) throws java.beans.PropertyVetoException,public void setIconifiable(boolean) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayer(java.lang.Integer) ,public void setLayer(int) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setMaximizable(boolean) ,public void setMaximum(boolean) throws java.beans.PropertyVetoException,public void setMenuBar(javax.swing.JMenuBar) ,public void setNormalBounds(java.awt.Rectangle) ,public void setResizable(boolean) ,public void setSelected(boolean) throws java.beans.PropertyVetoException,public void setTitle(java.lang.String) ,public void setUI(javax.swing.plaf.InternalFrameUI) ,public void show() ,public void toBack() ,public void toFront() ,public void updateUI() <variables>public static final java.lang.String CONTENT_PANE_PROPERTY,public static final java.lang.String FRAME_ICON_PROPERTY,public static final java.lang.String GLASS_PANE_PROPERTY,public static final java.lang.String IS_CLOSED_PROPERTY,public static final java.lang.String IS_ICON_PROPERTY,public static final java.lang.String IS_MAXIMUM_PROPERTY,public static final java.lang.String IS_SELECTED_PROPERTY,public static final java.lang.String LAYERED_PANE_PROPERTY,public static final java.lang.String MENU_BAR_PROPERTY,private static final java.lang.Object PROPERTY_CHANGE_LISTENER_KEY,public static final java.lang.String ROOT_PANE_PROPERTY,public static final java.lang.String TITLE_PROPERTY,protected boolean closable,boolean danger,private int defaultCloseOperation,protected javax.swing.JInternalFrame.JDesktopIcon desktopIcon,protected javax.swing.Icon frameIcon,protected boolean iconable,protected boolean isClosed,boolean isDragging,protected boolean isIcon,protected boolean isMaximum,protected boolean isSelected,private java.awt.Cursor lastCursor,private java.awt.Component lastFocusOwner,protected boolean maximizable,private java.awt.Rectangle normalBounds,private boolean opened,protected boolean resizable,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,protected java.lang.String title,private static final java.lang.String uiClassID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/toolbox/swing/PdfInformationPanel.java
|
PdfInformationPanel
|
propertyChange
|
class PdfInformationPanel extends JPanel implements PropertyChangeListener {
/**
* A serial version id
*/
private static final long serialVersionUID = -4171577284617028707L;
/**
* The file name of the PDF we're going to label.
*/
String filename = "";
/**
* the label containing the metadata
*/
JLabel label = new JLabel();
/**
* the scrollpane to scroll through the label
*/
JScrollPane scrollpane = new JScrollPane();
/**
* the panel to witch the scrollpane will be added.
*/
JPanel panel = new JPanel();
/**
* Construct the information label (actually it's a JPanel).
*/
public PdfInformationPanel() {
try {
this.setLayout(new BorderLayout());
label.setHorizontalAlignment(SwingConstants.CENTER);
panel.setLayout(new BorderLayout());
this.add(panel, BorderLayout.CENTER);
scrollpane.setPreferredSize(new Dimension(200, 200));
panel.add(scrollpane, BorderLayout.CENTER);
scrollpane.setViewportView(label);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Reads a PDF file for retrieving its metadata.
*
* @param file File
*/
public void createTextFromPDF(File file) {
if (file.exists()) {
int page = 1;
PdfReader reader = null;
try (RandomAccessFileOrArray raf = new RandomAccessFileOrArray(file.getAbsolutePath())) {
reader = new PdfReader(raf, null);
Map<String, String> pdfinfo = reader.getInfo();
StringBuilder sb = new StringBuilder();
sb.append("<html>=== Document Information ===<p>");
sb.append(reader.getCropBox(page).getHeight()).append("*").append(reader.getCropBox(page).getWidth())
.append("<p>");
sb.append("PDF Version: ").append(reader.getPdfVersion()).append("<p>");
sb.append("Number of pages: ").append(reader.getNumberOfPages()).append("<p>");
sb.append("Number of PDF objects: ").append(reader.getXrefSize()).append("<p>");
sb.append("File length: ").append(reader.getFileLength()).append("<p>");
sb.append("Encrypted= ").append(reader.isEncrypted()).append("<p>");
if (pdfinfo.get("Title") != null) {
sb.append("Title= ").append(pdfinfo.get("Title")).append("<p>");
}
if (pdfinfo.get("Author") != null) {
sb.append("Author= ").append(pdfinfo.get("Author")).append("<p>");
}
if (pdfinfo.get("Subject") != null) {
sb.append("Subject= ").append(pdfinfo.get("Subject")).append("<p>");
}
if (pdfinfo.get("Producer") != null) {
sb.append("Producer= ").append(pdfinfo.get("Producer")).append("<p>");
}
if (pdfinfo.get("ModDate") != null) {
sb.append("ModDate= ").append(PdfDate.decode(pdfinfo.get("ModDate"))
.getTime()).append("<p>");
}
if (pdfinfo.get("CreationDate") != null) {
sb.append("CreationDate= ").append(PdfDate.decode(
pdfinfo.get("CreationDate"))
.getTime()).append("<p>");
}
sb.append("</html>");
label.setText(sb.toString());
} catch (IOException ex) {
label.setText("");
}
}
}
/**
* @param evt PropertyChangeEvent
* @see java.beans.PropertyChangeListener#propertyChange(java.beans.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent evt) {<FILL_FUNCTION_BODY>}
}
|
filename = evt.getPropertyName();
if (filename.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File file = (File) evt.getNewValue();
if (file != null) {
this.createTextFromPDF(file);
this.repaint();
}
}
| 1,104
| 91
| 1,195
|
<methods>public void <init>() ,public void <init>(java.awt.LayoutManager) ,public void <init>(boolean) ,public void <init>(java.awt.LayoutManager, boolean) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public javax.swing.plaf.PanelUI getUI() ,public java.lang.String getUIClassID() ,public void setUI(javax.swing.plaf.PanelUI) ,public void updateUI() <variables>private static final java.lang.String uiClassID
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/BuildTutorial.java
|
BuildTutorial
|
main
|
class BuildTutorial {
static String root;
static FileWriter build;
//~ Methods
// ----------------------------------------------------------------
/**
* Main method so you can call the convert method from the command line.
*
* @param args 4 arguments are expected:
* <ul><li>a sourcedirectory (root of the tutorial xml-files),
* <li>a destination directory (where the html and build.xml files will be generated),
* <li>an xsl to transform the index.xml into a build.xml
* <li>an xsl to transform the index.xml into am index.html</ul>
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
/**
* Inspects a file or directory that is given and performs the necessary actions on it (transformation or
* recursion).
*
* @param source a sourcedirectory (possibly with a tutorial xml-file)
* @param destination a destination directory (where the html and build.xml file will be generated, if necessary)
* @param xsl_examples an xsl to transform the index.xml into a build.xml
* @param xsl_site an xsl to transform the index.xml into am index.html
* @throws IOException when something goes wrong while reading or creating a file or directory
*/
public static void action(File source, File destination, File xsl_examples, File xsl_site) throws IOException {
if (".svn".equals(source.getName())) {
return;
}
System.out.print(source.getName());
if (source.isDirectory()) {
System.out.print(" ");
System.out.println(source.getCanonicalPath());
File dest = new File(destination, source.getName());
dest.mkdir();
File current;
File[] xmlFiles = source.listFiles();
if (xmlFiles != null) {
for (File xmlFile : xmlFiles) {
current = xmlFile;
action(current, dest, xsl_examples, xsl_site);
}
} else {
System.out.println("... skipped");
}
} else if (source.getName().equals("index.xml")) {
System.out.println("... transformed");
convert(source, xsl_site, new File(destination, "index.php"));
File buildfile = new File(destination, "build.xml");
String path = buildfile.getCanonicalPath().substring(root.length());
path = path.replace(File.separatorChar, '/');
if ("/build.xml".equals(path)) {
return;
}
convert(source, xsl_examples, buildfile);
build.write("\t<ant antfile=\"${basedir}");
build.write(path);
build.write("\" target=\"install\" inheritAll=\"false\" />\n");
} else {
System.out.println("... skipped");
}
}
/**
* Converts an <code>infile</code>, using an <code>xslfile</code> to an
* <code>outfile</code>.
*
* @param infile the path to an XML file
* @param xslfile the path to the XSL file
* @param outfile the path for the output file
*/
public static void convert(File infile, File xslfile, File outfile) {
try {
// Create transformer factory
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// Use the factory to create a template containing the xsl file
Templates template = factory.newTemplates(new StreamSource(
new FileInputStream(xslfile)));
// Use the template to create a transformer
Transformer xformer = template.newTransformer();
// passing 2 parameters
String branch = outfile.getParentFile().getCanonicalPath().substring(root.length());
branch = branch.replace(File.separatorChar, '/');
StringBuilder path = new StringBuilder();
for (int i = 0; i < branch.length(); i++) {
if (branch.charAt(i) == '/') {
path.append("/pdf-core/src/test");
}
}
xformer.setParameter("branch", branch);
xformer.setParameter("root", path.toString());
// Prepare the input and output files
Source source = new StreamSource(new FileInputStream(infile));
Result result = new StreamResult(new FileOutputStream(outfile));
// Apply the xsl file to the source file and write the result to the
// output file
xformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
if (args.length == 4) {
File srcdir = new File(args[0]);
File destdir = new File(args[1]);
File xsl_examples = new File(srcdir, args[2]);
File xsl_site = new File(srcdir, args[3]);
try {
System.out.print("Building tutorial: ");
root = new File(args[1], srcdir.getName()).getCanonicalPath();
System.out.println(root);
build = new FileWriter(new File(root, "build.xml"));
build.write("<project name=\"tutorial\" default=\"all\" basedir=\".\">\n");
build.write("<target name=\"all\">\n");
action(srcdir, destdir, xsl_examples, xsl_site);
build.write("</target>\n</project>");
build.flush();
build.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
} else {
System.err
.println("Wrong number of parameters.\nUsage: BuildSite srcdr destdir xsl_examples xsl_site");
}
| 1,228
| 310
| 1,538
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/ConcatPdf.java
|
ConcatPdf
|
concat
|
class ConcatPdf {
/**
* This class can be used to concatenate existing PDF files. (This was an example known as PdfCopy.java)
*
* @param args the command line arguments
*/
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("arguments: file1 [file2 ...] destfile");
} else {
try {
File outFile = new File(args[args.length - 1]);
List<File> sources = new ArrayList<>();
for (int i = 0; i < args.length - 1; i++) {
sources.add(new File(args[i]));
}
concat(sources, outFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void concat(List<File> sources, File target) throws IOException {<FILL_FUNCTION_BODY>}
}
|
for (File source : sources) {
if (!source.isFile() || !source.canRead()) {
throw new IOException("cannot read:" + source.getAbsolutePath());
}
}
int pageOffset = 0;
List<Map<String, Object>> master = new ArrayList<>();
Document document = new Document();
PdfCopy writer = new PdfCopy(document, new BufferedOutputStream(Files.newOutputStream(target.toPath())));
writer.setPdfVersion(PdfWriter.VERSION_1_7);
writer.setFullCompression();
writer.setCompressionLevel(PdfStream.BEST_COMPRESSION);
document.open();
for (File source : sources) {
// we create a reader for a certain document
PdfReader reader = new PdfReader(new BufferedInputStream(Files.newInputStream(source.toPath())));
reader.consolidateNamedDestinations();
// we retrieve the total number of pages
int numberOfPages = reader.getNumberOfPages();
List<Map<String, Object>> bookmarks = SimpleBookmark.getBookmarkList(reader);
if (bookmarks != null) {
if (pageOffset != 0) {
SimpleBookmark.shiftPageNumbersInRange(bookmarks, pageOffset, null);
}
master.addAll(bookmarks);
}
pageOffset += numberOfPages;
// we add content
PdfImportedPage page;
for (int i = 1; i <= numberOfPages; i++) {
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
writer.freeReader(reader);
}
if (!master.isEmpty()) {
writer.setOutlines(master);
}
// we close the document
document.close();
| 247
| 457
| 704
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/EncryptPdf.java
|
EncryptPdf
|
main
|
class EncryptPdf {
private final static int INPUT_FILE = 0;
private final static int OUTPUT_FILE = 1;
private final static int USER_PASSWORD = 2;
private final static int OWNER_PASSWORD = 3;
private final static int PERMISSIONS = 4;
private final static int STRENGTH = 5;
private final static int MOREINFO = 6;
private final static int[] permit = {
PdfWriter.ALLOW_PRINTING,
PdfWriter.ALLOW_MODIFY_CONTENTS,
PdfWriter.ALLOW_COPY,
PdfWriter.ALLOW_MODIFY_ANNOTATIONS,
PdfWriter.ALLOW_FILL_IN,
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.ALLOW_ASSEMBLY,
PdfWriter.ALLOW_DEGRADED_PRINTING};
private static void usage() {
System.out.println(
"usage: input_file output_file user_password owner_password permissions 128|40 [new info string pairs]");
System.out.println("permissions is 8 digit long 0 or 1. Each digit has a particular security function:");
System.out.println();
System.out.println("AllowPrinting");
System.out.println("AllowModifyContents");
System.out.println("AllowCopy");
System.out.println("AllowModifyAnnotations");
System.out.println("AllowFillIn (128 bit only)");
System.out.println("AllowScreenReaders (128 bit only)");
System.out.println("AllowAssembly (128 bit only)");
System.out.println("AllowDegradedPrinting (128 bit only)");
System.out.println("Example permissions to copy and print would be: 10100000");
}
/**
* Encrypts a PDF document.
*
* @param args input_file output_file user_password owner_password permissions 128|40 [new info string pairs]
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
System.out.println("PDF document encryptor");
if (args.length <= STRENGTH || args[PERMISSIONS].length() != 8) {
usage();
return;
}
try {
int permissions = 0;
String p = args[PERMISSIONS];
for (int k = 0; k < p.length(); ++k) {
permissions |= (p.charAt(k) == '0' ? 0 : permit[k]);
}
System.out.println("Reading " + args[INPUT_FILE]);
PdfReader reader = new PdfReader(args[INPUT_FILE]);
System.out.println("Writing " + args[OUTPUT_FILE]);
Map<String, String> moreInfo = new HashMap<>();
for (int k = MOREINFO; k < args.length - 1; k += 2) {
moreInfo.put(args[k], args[k + 1]);
}
PdfEncryptor.encrypt(reader, new FileOutputStream(args[OUTPUT_FILE]),
args[USER_PASSWORD].getBytes(), args[OWNER_PASSWORD].getBytes(), permissions,
args[STRENGTH].equals("128"), moreInfo);
System.out.println("Done.");
} catch (Exception e) {
e.printStackTrace();
}
| 555
| 337
| 892
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/HandoutPdf.java
|
HandoutPdf
|
main
|
class HandoutPdf {
/**
* Makes handouts based on an existing PDF file.
*
* @param args the command line arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
if (args.length != 3) {
System.err.println("arguments: srcfile destfile pages");
} else {
try {
int pages = Integer.parseInt(args[2]);
if (pages < 2 || pages > 8) {
throw new DocumentException(MessageLocalization
.getComposedMessage("you.can.t.have.1.pages.on.one.page.minimum.2.maximum.8", pages));
}
float x1 = 30f;
float x2 = 280f;
float x3 = 320f;
float x4 = 565f;
float[] y1 = new float[pages];
float[] y2 = new float[pages];
float height = (778f - (20f * (pages - 1))) / pages;
y1[0] = 812f;
y2[0] = 812f - height;
for (int i = 1; i < pages; i++) {
y1[i] = y2[i - 1] - 20f;
y2[i] = y1[i] - height;
}
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
// step 1: creation of a document-object
Document document = new Document(PageSize.A4);
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(args[1]));
// step 3: we open the document
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
int p = 0;
// step 4: we add content
while (i < n) {
i++;
Rectangle rect = reader.getPageSizeWithRotation(i);
float factorx = (x2 - x1) / rect.getWidth();
float factory = (y1[p] - y2[p]) / rect.getHeight();
float factor = (factorx < factory ? factorx : factory);
float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.getWidth() * factor) / 2f);
float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.getHeight() * factor) / 2f);
page = writer.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.getHeight() * factor);
} else {
cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
}
cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
cb.moveTo(x3, l);
cb.lineTo(x4, l);
}
cb.rectangle(x1 + dx, y2[p] + dy, rect.getWidth() * factor, rect.getHeight() * factor);
cb.stroke();
System.out.println("Processed page " + i);
p++;
if (p == pages) {
p = 0;
document.newPage();
}
}
// step 5: we close the document
document.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
| 67
| 1,083
| 1,150
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/SplitPdf.java
|
SplitPdf
|
main
|
class SplitPdf extends java.lang.Object {
/**
* This class can be used to split an existing PDF file.
*
* @param args the command line arguments
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
if (args.length != 4) {
System.err.println("arguments: srcfile destfile1 destfile2 pagenumber");
} else {
try {
int pagenumber = Integer.parseInt(args[3]);
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[0]);
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
System.out.println("There are " + n + " pages in the original file.");
if (pagenumber < 2 || pagenumber > n) {
throw new DocumentException(MessageLocalization.getComposedMessage(
"you.can.t.split.this.document.at.page.1.there.is.no.such.page", pagenumber));
}
// step 1: creation of a document-object
Document document1 = new Document(reader.getPageSizeWithRotation(1));
Document document2 = new Document(reader.getPageSizeWithRotation(pagenumber));
// step 2: we create a writer that listens to the document
PdfWriter writer1 = PdfWriter.getInstance(document1, new FileOutputStream(args[1]));
PdfWriter writer2 = PdfWriter.getInstance(document2, new FileOutputStream(args[2]));
// step 3: we open the document
document1.open();
PdfContentByte cb1 = writer1.getDirectContent();
document2.open();
PdfContentByte cb2 = writer2.getDirectContent();
PdfImportedPage page;
int rotation;
int i = 0;
// step 4: we add content
while (i < pagenumber - 1) {
i++;
document1.setPageSize(reader.getPageSizeWithRotation(i));
document1.newPage();
page = writer1.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb1.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
} else {
cb1.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
while (i < n) {
i++;
document2.setPageSize(reader.getPageSizeWithRotation(i));
document2.newPage();
page = writer2.getImportedPage(reader, i);
rotation = reader.getPageRotation(i);
if (rotation == 90 || rotation == 270) {
cb2.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
} else {
cb2.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
System.out.println("Processed page " + i);
}
// step 5: we close the document
document1.close();
document2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
| 74
| 826
| 900
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/com/lowagie/tools/ToolboxAvailable.java
|
ToolboxAvailable
|
main
|
class ToolboxAvailable {
/**
* Checks if the toolbox if available. If it is, the toolbox is started. If it isn't, an error message is shown.
*
* @param args the command-line args
*/
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
if (GraphicsEnvironment.isHeadless()) {
System.out.println(Document.getVersion() + " Toolbox error: headless display");
} else {
try {
Toolbox.main(args);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"You need the iText-toolbox.jar with class com.lowagie.toolbox.Toolbox to use the iText Toolbox.",
Document.getVersion() + " Toolbox error",
JOptionPane.ERROR_MESSAGE);
}
}
| 87
| 142
| 229
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/org/librepdf/openpdf/examples/fonts/languages/Chinese.java
|
Chinese
|
main
|
class Chinese {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// step 0: prepare font with chinese symbols
// Downloaded from:
// https://github.com/adobe-fonts/source-han-serif/blob/release/OTF/SimplifiedChinese/SourceHanSerifSC-Regular.otf
final String fontFile = "SourceHanSerifSC-Regular.otf";
BaseFont baseFont = BaseFont
.createFont(fontFile, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
final Font chineseFont = new Font(baseFont, 12, Font.NORMAL);
// step 1: Prepare document for chinese text
Document document = new Document();
ByteArrayOutputStream pdfOutput = new ByteArrayOutputStream();
PdfWriter.getInstance(document, pdfOutput);
document.open();
// step 2: we add content to the document
document.add(new Chunk("Chinese Poetry: 中文", chineseFont));
document.add(new Paragraph("李白《赠汪伦》", chineseFont));
document.add(new Paragraph("李白乘舟将欲行,", chineseFont));
document.add(new Paragraph("忽闻岸上踏歌声。", chineseFont));
document.add(new Paragraph("桃花潭水深千尺,", chineseFont));
document.add(new Paragraph("不及汪伦送我行。", chineseFont));
// step 3: we close the document
document.close();
// step 4: (optional) some watermark with chinese text
String watermark = "水印 (Watermark)";
final byte[] pdfBytesWithWaterMark =
new Watermarker(pdfOutput.toByteArray(), watermark, 64, 0.3f)
.withColor(Color.RED)
.withFont(chineseFont.getBaseFont())
.write();
// step 5: write the output to a file
final Path target = Paths.get(Chinese.class.getSimpleName() + ".pdf");
Files.write(target, pdfBytesWithWaterMark);
| 33
| 527
| 560
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/pdf-toolbox/src/main/java/org/librepdf/openpdf/examples/fonts/languages/Japanese.java
|
Japanese
|
main
|
class Japanese {
public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>}
}
|
// step 0: prepare font with chinese symbols
BaseFont baseFont = BaseFont.createFont(
Japanese.class.getClassLoader().getResource("fonts/GenShinGothic-Normal.ttf").getFile(),
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(baseFont, 12, Font.NORMAL);
// step 1: Prepare document for japanese text
Document document = new Document();
ByteArrayOutputStream pdfOutput = new ByteArrayOutputStream();
PdfWriter.getInstance(document, pdfOutput);
document.open();
// step 2: we add content to the document
// http://en.glyphwiki.org/wiki/u20bb7
document.add(new Chunk("\uD842\uDFB7", font));
// step 3: we close the document
document.close();
Files.write(Paths.get(Japanese.class.getSimpleName() + ".pdf"), pdfOutput.toByteArray());
| 33
| 262
| 295
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/starter/src/main/java/org/jivesoftware/openfire/launcher/DroppableFrame.java
|
DroppableFrame
|
drop
|
class DroppableFrame extends JFrame implements DropTargetListener, DragSourceListener,
DragGestureListener
{
private DragSource dragSource = DragSource.getDefaultDragSource();
/**
* Creates a droppable rame.
*/
public DroppableFrame() {
new DropTarget(this, this);
dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
@Override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent) {
}
@Override
public void dragEnter(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dragExit(DragSourceEvent DragSourceEvent) {
}
@Override
public void dragOver(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dragEnter(DropTargetDragEvent dropTargetDragEvent) {
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
@Override
public void dragExit(DropTargetEvent dropTargetEvent) {
}
@Override
public void dragOver(DropTargetDragEvent dropTargetDragEvent) {
}
@Override
public void dropActionChanged(DropTargetDragEvent dropTargetDragEvent) {
}
@Override
public void drop(DropTargetDropEvent dropTargetDropEvent) {<FILL_FUNCTION_BODY>}
@Override
public void dragGestureRecognized(DragGestureEvent dragGestureEvent) {
}
/**
* Notified when a file has been dropped onto the frame.
*
* @param file the file that has been dropped.
*/
public void fileDropped(File file){
}
/**
* Notified when a directory has been dropped onto the frame.
*
* @param file the directory that has been dropped.
*/
public void directoryDropped(File file){
}
}
|
try {
Transferable transferable = dropTargetDropEvent.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dropTargetDropEvent.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List fileList = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iterator = fileList.iterator();
while (iterator.hasNext()) {
File file = (File) iterator.next();
if (file.isFile()) {
fileDropped(file);
}
if (file.isDirectory()) {
directoryDropped(file);
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
}
else {
dropTargetDropEvent.rejectDrop();
}
}
catch (IOException | UnsupportedFlavorException io) {
io.printStackTrace();
dropTargetDropEvent.rejectDrop();
}
| 553
| 261
| 814
|
<methods>public void <init>() throws java.awt.HeadlessException,public void <init>(java.awt.GraphicsConfiguration) ,public void <init>(java.lang.String) throws java.awt.HeadlessException,public void <init>(java.lang.String, java.awt.GraphicsConfiguration) ,public javax.accessibility.AccessibleContext getAccessibleContext() ,public java.awt.Container getContentPane() ,public int getDefaultCloseOperation() ,public java.awt.Component getGlassPane() ,public java.awt.Graphics getGraphics() ,public javax.swing.JMenuBar getJMenuBar() ,public javax.swing.JLayeredPane getLayeredPane() ,public javax.swing.JRootPane getRootPane() ,public javax.swing.TransferHandler getTransferHandler() ,public static boolean isDefaultLookAndFeelDecorated() ,public void remove(java.awt.Component) ,public void repaint(long, int, int, int, int) ,public void setContentPane(java.awt.Container) ,public void setDefaultCloseOperation(int) ,public static void setDefaultLookAndFeelDecorated(boolean) ,public void setGlassPane(java.awt.Component) ,public void setIconImage(java.awt.Image) ,public void setJMenuBar(javax.swing.JMenuBar) ,public void setLayeredPane(javax.swing.JLayeredPane) ,public void setLayout(java.awt.LayoutManager) ,public void setTransferHandler(javax.swing.TransferHandler) ,public void update(java.awt.Graphics) <variables>protected javax.accessibility.AccessibleContext accessibleContext,private int defaultCloseOperation,private static final java.lang.Object defaultLookAndFeelDecoratedKey,protected javax.swing.JRootPane rootPane,protected boolean rootPaneCheckingEnabled,private javax.swing.TransferHandler transferHandler
|
igniterealtime_Openfire
|
Openfire/starter/src/main/java/org/jivesoftware/openfire/launcher/DroppableTextPane.java
|
DroppableTextPane
|
drop
|
class DroppableTextPane extends JTextPane implements DropTargetListener,
DragSourceListener, DragGestureListener
{
private DragSource dragSource = DragSource.getDefaultDragSource();
/**
* Creates a droppable text pane.
*/
public DroppableTextPane() {
new DropTarget(this, this);
dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
@Override
public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent) {
}
@Override
public void dragEnter(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dragExit(DragSourceEvent DragSourceEvent) {
}
@Override
public void dragOver(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent) {
}
@Override
public void dragEnter(DropTargetDragEvent dropTargetDragEvent) {
dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
@Override
public void dragExit(DropTargetEvent dropTargetEvent) {
}
@Override
public void dragOver(DropTargetDragEvent dropTargetDragEvent) {
}
@Override
public void dropActionChanged(DropTargetDragEvent dropTargetDragEvent) {
}
@Override
public void drop(DropTargetDropEvent dropTargetDropEvent) {<FILL_FUNCTION_BODY>}
@Override
public void dragGestureRecognized(DragGestureEvent dragGestureEvent) {
}
/**
* Notified when a file has been dropped onto the frame.
*
* @param file the file that has been dropped.
*/
public void fileDropped(File file){
}
/**
* Notified when a directory has been dropped onto the frame.
*
* @param file the directory that has been dropped.
*/
public void directoryDropped(File file){
}
}
|
try {
Transferable transferable = dropTargetDropEvent.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dropTargetDropEvent.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List fileList = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
Iterator iterator = fileList.iterator();
while (iterator.hasNext()) {
File file = (File) iterator.next();
if (file.isFile()) {
fileDropped(file);
}
if (file.isDirectory()) {
directoryDropped(file);
}
}
dropTargetDropEvent.getDropTargetContext().dropComplete(true);
}
else {
dropTargetDropEvent.rejectDrop();
}
}
catch (IOException | UnsupportedFlavorException io) {
io.printStackTrace();
dropTargetDropEvent.rejectDrop();
}
| 556
| 261
| 817
|
<methods>public void <init>() ,public void <init>(javax.swing.text.StyledDocument) ,public javax.swing.text.Style addStyle(java.lang.String, javax.swing.text.Style) ,public javax.swing.text.AttributeSet getCharacterAttributes() ,public javax.swing.text.MutableAttributeSet getInputAttributes() ,public javax.swing.text.Style getLogicalStyle() ,public javax.swing.text.AttributeSet getParagraphAttributes() ,public javax.swing.text.Style getStyle(java.lang.String) ,public javax.swing.text.StyledDocument getStyledDocument() ,public java.lang.String getUIClassID() ,public void insertComponent(java.awt.Component) ,public void insertIcon(javax.swing.Icon) ,public void removeStyle(java.lang.String) ,public void replaceSelection(java.lang.String) ,public void setCharacterAttributes(javax.swing.text.AttributeSet, boolean) ,public void setDocument(javax.swing.text.Document) ,public final void setEditorKit(javax.swing.text.EditorKit) ,public void setLogicalStyle(javax.swing.text.Style) ,public void setParagraphAttributes(javax.swing.text.AttributeSet, boolean) ,public void setStyledDocument(javax.swing.text.StyledDocument) <variables>private static final java.lang.String uiClassID
|
igniterealtime_Openfire
|
Openfire/starter/src/main/java/org/jivesoftware/openfire/launcher/Uninstaller.java
|
Uninstaller
|
performAction
|
class Uninstaller extends UninstallAction {
@Override
public int getPercentOfTotalInstallation() {
return 0;
}
@Override
public boolean performAction(Context context, ProgressInterface progressInterface) {<FILL_FUNCTION_BODY>}
}
|
final File installationDirectory = context.getInstallationDirectory();
File libDirectory = new File(installationDirectory, "lib");
// If the directory still exists, remove all JAR files.
if (libDirectory.exists() && libDirectory.isDirectory()) {
File[] jars = libDirectory.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
for (File jar : jars) {
jar.delete();
}
}
return super.performAction(context, progressInterface);
| 73
| 157
| 230
|
<methods>public void <init>() ,public boolean performAction(com.install4j.api.Context, com.install4j.api.ProgressInterface) <variables>
|
igniterealtime_Openfire
|
Openfire/starter/src/main/java/org/jivesoftware/openfire/starter/JiveClassLoader.java
|
JiveClassLoader
|
accept
|
class JiveClassLoader extends URLClassLoader {
/**
* Constructs the classloader.
*
* @param parent the parent class loader (or null for none).
* @param libDir the directory to load jar files from.
* @throws java.net.MalformedURLException if the libDir path is not valid.
*/
JiveClassLoader(ClassLoader parent, File libDir) throws MalformedURLException {
super(new URL[] { libDir.toURI().toURL() }, parent);
File[] jars = libDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {<FILL_FUNCTION_BODY>}
});
// Do nothing if no jar or zip files were found
if (jars == null) {
return;
}
// sort jars otherwise order differs between installations (e.g. it's not alphabetical)
// order may matter if trying to patch an install by adding patch jar to lib folder
Arrays.sort(jars);
for (int i = 0; i < jars.length; i++) {
if (jars[i].isFile()) {
addURL(jars[i].toURI().toURL());
}
}
}
}
|
boolean accept = false;
String smallName = name.toLowerCase();
if (smallName.endsWith(".jar")) {
accept = true;
}
else if (smallName.endsWith(".zip")) {
accept = true;
}
return accept;
| 322
| 72
| 394
|
<methods>public void <init>(java.net.URL[]) ,public void <init>(java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader) ,public void <init>(java.lang.String, java.net.URL[], java.lang.ClassLoader, java.net.URLStreamHandlerFactory) ,public void close() throws java.io.IOException,public java.net.URL findResource(java.lang.String) ,public Enumeration<java.net.URL> findResources(java.lang.String) throws java.io.IOException,public java.io.InputStream getResourceAsStream(java.lang.String) ,public java.net.URL[] getURLs() ,public static java.net.URLClassLoader newInstance(java.net.URL[]) ,public static java.net.URLClassLoader newInstance(java.net.URL[], java.lang.ClassLoader) <variables>private final java.security.AccessControlContext acc,private WeakHashMap<java.io.Closeable,java.lang.Void> closeables,private final jdk.internal.loader.URLClassPath ucp
|
igniterealtime_Openfire
|
Openfire/starter/src/main/java/org/jivesoftware/openfire/starter/ServerStarter.java
|
ServerStarter
|
start
|
class ServerStarter {
private static final Logger Log = LoggerFactory.getLogger(ServerStarter.class);
/**
* Default to this location if one has not been specified
*/
private static final String DEFAULT_LIB_DIR = "../lib";
public static void main(String [] args) {
new ServerStarter().start();
}
/**
* Starts the server by loading and instantiating the bootstrap
* container. Once the start method is called, the server is
* started and the server starter should not be used again.
*/
private void start() {<FILL_FUNCTION_BODY>}
/**
* Locates the best class loader based on context (see class description).
*
* @return The best parent classloader to use
*/
private ClassLoader findParentClassLoader() {
ClassLoader parent = Thread.currentThread().getContextClassLoader();
if (parent == null) {
parent = this.getClass().getClassLoader();
if (parent == null) {
parent = ClassLoader.getSystemClassLoader();
}
}
return parent;
}
}
|
// Setup the classpath using JiveClassLoader
try {
// Load up the bootstrap container
final ClassLoader parent = findParentClassLoader();
String libDirString = System.getProperty("openfire.lib.dir");
File libDir;
if (libDirString != null) {
// If the lib directory property has been specified and it actually
// exists use it, else use the default
libDir = new File(libDirString);
if (!libDir.exists()) {
Log.warn("Lib directory " + libDirString +
" does not exist. Using default " + DEFAULT_LIB_DIR);
libDir = new File(DEFAULT_LIB_DIR);
}
}
else {
libDir = new File(DEFAULT_LIB_DIR);
}
ClassLoader loader = new JiveClassLoader(parent, libDir);
Thread.currentThread().setContextClassLoader(loader);
Class containerClass = loader.loadClass(
"org.jivesoftware.openfire.XMPPServer");
containerClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
| 286
| 291
| 577
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/ASN1DERTag.java
|
ASN1DERTag
|
doPrimitive
|
class ASN1DERTag extends BodyTagSupport {
private byte[] value; // ASN.1 DER-encoded value
public byte[] getValue() {
return value;
}
public void setValue(byte[] value) {
this.value = value;
}
@Override
public int doEndTag() throws JspException {
try (final ASN1InputStream decoder = new ASN1InputStream(value)){
ASN1Primitive primitive = decoder.readObject();
while (primitive != null && !(primitive instanceof ASN1Null)) {
pageContext.getOut().write(doPrimitive(primitive));
primitive = decoder.readObject();
}
} catch (Exception ex) {
throw new JspException(ex.getMessage());
}
return super.doEndTag();
}
private String doPrimitive(ASN1Primitive primitive) throws IOException {<FILL_FUNCTION_BODY>}
private String doCollection(ASN1Encodable[] asn1Encodables) throws IOException {
switch (asn1Encodables.length) {
case 1:
// one row, one column
return "<table><tr><td colspan='2'>" + doPrimitive(asn1Encodables[0].toASN1Primitive()) + "</td></tr></table>";
case 2:
// one row, two columns
return "<table><tr><td>" + doPrimitive(asn1Encodables[0].toASN1Primitive()) + "</td>"
+ "<td>" + doPrimitive(asn1Encodables[1].toASN1Primitive()) + "</td></tr></table>";
default:
// a row per per item
final StringBuilder sb = new StringBuilder();
for (ASN1Encodable asn1Encodable : asn1Encodables) {
sb.append("<table><tr><td colspan='2'>").append(doPrimitive(asn1Encodable.toASN1Primitive())).append("</td></tr></table>");
}
return sb.toString();
}
}
private String asString(ASN1Primitive primitive) {
if (primitive == null || primitive instanceof ASN1Null) {
return "";
}
if (primitive instanceof ASN1String) {
return ((ASN1String) primitive).getString();
}
if (primitive instanceof DERUTCTime) {
return ((DERUTCTime) primitive).getAdjustedTime();
}
if (primitive instanceof DERGeneralizedTime) {
return ((DERGeneralizedTime) primitive).getTime();
}
if (primitive instanceof ASN1ObjectIdentifier) {
switch (((ASN1ObjectIdentifier) primitive).getId()) {
case "1.3.6.1.5.5.7.8.5":
return "xmppAddr";
default:
return primitive.toString();
}
}
return primitive.toString();
}
}
|
if (primitive == null || primitive instanceof ASN1Null) {
return "";
} else if (primitive instanceof ASN1Sequence) {
return doCollection(((ASN1Sequence) primitive).toArray());
} else if (primitive instanceof ASN1Set) {
return doCollection(((ASN1Set) primitive).toArray());
} else if (primitive instanceof DERTaggedObject) {
final DERTaggedObject tagged = ((DERTaggedObject) primitive);
return "<table><tr><td>" + /* tagged.getTagNo() + */ "</td><td>" + doPrimitive(tagged.getBaseUniversal(false, tagged.getTagNo())) + "</td></tr></table>";
} else {
return "<table><tr><td colspan='2'>" + asString(primitive) + "</td></tr></table>";
}
| 790
| 230
| 1,020
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/AdminPageBean.java
|
AdminPageBean
|
getScripts
|
class AdminPageBean {
private String title;
private Collection breadcrumbs;
private String pageID;
private String subPageID;
private String extraParams;
private Collection scripts;
public AdminPageBean() {
}
/**
* Returns the title of the page with HTML escaped.
* @return the page title
*/
public String getTitle() {
if (title != null) {
return StringUtils.escapeHTMLTags(title);
}
else {
return title;
}
}
/**
* Sets the title of the admin console page.
* @param title the name of the page
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Returns a collection of breadcrumbs. Use the Collection API to get/set/remove crumbs.
* @return the collection of breadcrumbs
*/
public Collection getBreadcrumbs() {
if (breadcrumbs == null) {
breadcrumbs = new ArrayList();
}
return breadcrumbs;
}
/**
* Returns the page ID (corresponds to sidebar ID's).
* @return the page id
*/
public String getPageID() {
return pageID;
}
/**
* Sets the ID of the page (corresponds to sidebar ID's).
* @param pageID the id of page
*/
public void setPageID(String pageID) {
this.pageID = pageID;
}
/**
* Returns the subpage ID (corresponds to sidebar ID's).
* @return the sub page id
*/
public String getSubPageID() {
return subPageID;
}
/**
* Sets the subpage ID (corresponds to sidebar ID's).
* @param subPageID the sub page id
*/
public void setSubPageID(String subPageID) {
this.subPageID = subPageID;
}
/**
* Returns a string of extra parameters for the URLs - these might be specific IDs for resources.
* @return the extra URL parameters
*/
public String getExtraParams() {
return extraParams;
}
/**
* Sets the string of extra parameters for the URLs.
* @param extraParams the extra parameters
*/
public void setExtraParams(String extraParams) {
this.extraParams = extraParams;
}
/**
* Returns a collection of scripts. Use the Collection API to get/set/remove scripts.
* @return the collection of scripts
*/
public Collection getScripts() {<FILL_FUNCTION_BODY>}
/**
* A simple model of a breadcrumb. A bread crumb is a link with a display name.
*/
public static class Breadcrumb {
private String name;
private String url;
/**
* Creates a crumb given a name an URL.
* @param name the breadcrumb name
* @param url the url for the breadcrumb
*/
public Breadcrumb(String name, String url) {
this.name = name;
this.url = url;
}
/**
* Returns the name, with HTML escaped.
* @return the HTML escaped breadcrumb name
*/
public String getName() {
if (name != null) {
return StringUtils.escapeHTMLTags(name);
}
else {
return name;
}
}
/**
* Returns the URL.
* @return the URL of the breadcrumb
*/
public String getUrl() {
return url;
}
}
}
|
if (scripts == null) {
scripts = new ArrayList();
}
return scripts;
| 948
| 27
| 975
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/ContentSecurityPolicyFilter.java
|
ContentSecurityPolicyFilter
|
doFilter
|
class ContentSecurityPolicyFilter implements Filter
{
private final SystemProperty<Boolean> statusProperty;
private final SystemProperty<String> valueProperty;
public ContentSecurityPolicyFilter(@Nonnull final SystemProperty<Boolean> statusProperty, @Nonnull final SystemProperty<String> valueProperty)
{
this.statusProperty = statusProperty;
this.valueProperty = valueProperty;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{<FILL_FUNCTION_BODY>}
}
|
if (response instanceof HttpServletResponse && statusProperty.getValue()) {
final String value = valueProperty.getValue();
if (value != null && !value.trim().isEmpty()) {
((HttpServletResponse) response).setHeader("Content-Security-Policy", value);
}
}
chain.doFilter(request, response);
| 140
| 84
| 224
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/FlashMessageTag.java
|
FlashMessageTag
|
doTag
|
class FlashMessageTag extends SimpleTagSupport {
public static final String SUCCESS_MESSAGE_KEY = "success";
public static final String WARNING_MESSAGE_KEY = "warning";
public static final String ERROR_MESSAGE_KEY = "error";
@Override
public void doTag() throws IOException {<FILL_FUNCTION_BODY>}
}
|
final PageContext pageContext = (PageContext) getJspContext();
final JspWriter jspWriter = pageContext.getOut();
final HttpSession session = pageContext.getSession();
for (final String flash : new String[]{SUCCESS_MESSAGE_KEY, WARNING_MESSAGE_KEY, ERROR_MESSAGE_KEY}) {
final Object flashValue = session.getAttribute(flash);
if (flashValue != null) {
jspWriter.append(String.format("<div class='%s'>%s</div>", flash, flashValue));
session.setAttribute(flash, null);
}
}
| 95
| 165
| 260
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/JSTLFunctions.java
|
JSTLFunctions
|
urlDecode
|
class JSTLFunctions
{
/**
* JSTL delegate for {@link String#replaceAll(String, String)}. The first argument is the value on which the
* replacement has to occur. The other arguments are passed to {@link String#replaceAll(String, String)} directly.
* @param string The string to search
* @param regex the regular expression to which this string is to be matched
* @param replacement the string to be substituted for each match
* @return the updated string
* @see String#replaceAll(String, String)
*/
public static String replaceAll(String string, String regex, String replacement)
{
return string.replaceAll(regex, replacement);
}
/**
* JSTL delegate for {@link String#split(String)}. The first argument is the value on which the replacement has to
* occur. The other argument is used as the argument for the invocation of {@link String#split(String)}.
* @param string The string to split
* @param regex the delimiting regular expression
* @return the the array of strings computed by splitting this string around matches of the given regular expression
* @see String#split(String)
*/
public static String[] split(String string, String regex)
{
return string.split(regex);
}
/**
* A formatter for formatting byte sizes. For example, formatting 12345 byes results in
* "12.1 K" and 1234567 results in "1.18 MB".
*
* @param bytes the number of bytes
* @return the number of bytes in terms of KB, MB, etc.
* @see ByteFormat
*/
public static String byteFormat( long bytes )
{
return new ByteFormat().format( bytes );
}
/**
* Translates a string into {@code application/x-www-form-urlencoded} format using a specific encoding scheme. This
* method uses the UTF-8 encoding scheme to obtain the bytes for unsafe characters.
*
* @param string the URL to encode
* @return the encoded URL
*
* @see URLEncoder
*/
public static String urlEncode( String string )
{
try
{
return URLEncoder.encode( string, "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
// Should never occur, as UTF-8 encoding is mantdatory to implement for any JRE.
throw new IllegalStateException( "Unable to URL-encode string: " + string, e );
}
}
/**
* Decodes a {@code application/x-www-form-urlencoded} string using the UTF-8 encoding scheme. The encoding is used
* to determine what characters are represented by any consecutive sequences of the form "<i>{@code %xy}</i>".
* @param string the String to encode
* @return the encoded string
* @see URLDecoder
*/
public static String urlDecode( String string )
{<FILL_FUNCTION_BODY>}
/**
* This method takes a string which may contain HTML tags (ie, <b>,
* <table>, etc) and converts the '<' and '>' characters to
* their HTML escape sequences. It will also replace LF with <br>.
*
* @param string the String to escape
* @return the escaped string
* @see StringUtils#escapeHTMLTags(String)
*/
public static String escapeHTMLTags( String string )
{
return StringUtils.escapeHTMLTags( string );
}
}
|
try
{
return URLDecoder.decode( string, "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
// Should never occur, as UTF-8 encoding is mandatory to implement for any JRE.
throw new IllegalStateException( "Unable to URL-decode string: " + string, e );
}
| 921
| 90
| 1,011
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/LdapGroupTester.java
|
LdapGroupTester
|
getGroups
|
class LdapGroupTester {
private static final Logger Log = LoggerFactory.getLogger(LdapGroupTester.class);
private LdapManager manager;
public LdapGroupTester(LdapManager manager) {
this.manager = manager;
}
/**
* Returns fist N groups found in LDAP. The returned groups are only able to return their name,
* description and count of members. Count of members is considering all values that were found
* in the member field.
*
* @param maxGroups max number of groups to return.
* @return fist N groups found in the LDAP.
*/
public Collection<Group> getGroups(int maxGroups) {<FILL_FUNCTION_BODY>}
/**
* Representation of a group found in LDAP. This representatio is read-only and only provides
* some basic information: name, description and number of members in the group. Note that
* group members are not validated (i.e. checked that they are valid JIDs and that the JID belongs
* to an existing user).
*/
public static class Group {
private String name;
private String description;
/**
* Elements that the group contains. This includes admins, members or anything listed
* in the {@code member field}. At this point JIDs are not validated.
*/
private int members;
public Group(String name, String description, int members) {
this.name = name;
this.description = description;
this.members = members;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public int getMembers() {
return members;
}
}
}
|
Collection<Group> groups = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[]{
new SortControl(new String[]{manager.getGroupNameField()}, Control.NONCRITICAL)
};
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
}
else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// Attributes to return for each group
String[] standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
searchControls.setReturningAttributes(standardAttributes);
// Limit results to those we'll need to process
searchControls.setCountLimit(maxGroups);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
Attributes attributes = ((SearchResult) answer.next()).getAttributes();
String groupName = (String) attributes.get(manager.getGroupNameField()).get();
String description = "";
int elements = 0;
try {
description = ((String) attributes.get(manager.getGroupDescriptionField()).get());
} catch (NullPointerException e) {
// Do nothing since the group description field was not found
} catch (Exception e) {
Log.error("Error retrieving group description", e);
}
Attribute memberField = attributes.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
ne.next();
elements = elements + 1;
}
}
// Build Group with found information
groups.add(new Group(groupName, description, elements));
}
// Close the enumeration.
answer.close();
}
catch (Exception e) {
Log.error(e.getMessage(), e);
}
finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
}
catch (Exception ex) {
Log.debug("An exception occurred while trying to close a LDAP context after trying to retrieve groups.", ex);
}
}
return groups;
| 452
| 715
| 1,167
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/LoginLimitManager.java
|
LoginLimitManagerContainer
|
recordSuccessfulAttempt
|
class LoginLimitManagerContainer {
private static LoginLimitManager instance = new LoginLimitManager();
}
/**
* Returns a singleton instance of LoginLimitManager.
*
* @return a LoginLimitManager instance.
*/
public static LoginLimitManager getInstance() {
return LoginLimitManagerContainer.instance;
}
// Max number of attempts per ip address that can be performed in given time frame
public static final SystemProperty<Long> MAX_ATTEMPTS_PER_IP = SystemProperty.Builder.ofType(Long.class)
.setKey("adminConsole.maxAttemptsPerIP")
.setDynamic(true)
.setDefaultValue(10L)
.setMinValue(1L)
.build();
// Time frame before attempts per ip addresses are reset
public static final SystemProperty<Duration> PER_IP_ATTEMPT_RESET_INTERVAL = SystemProperty.Builder.ofType(Duration.class)
.setKey("adminConsole.perIPAttemptResetInterval")
.setDynamic(false)
.setChronoUnit(ChronoUnit.MILLIS)
.setDefaultValue(Duration.ofMinutes(15))
.setMinValue(Duration.ofMillis(1))
.build();
// Max number of attempts per username that can be performed in a given time frame
public static final SystemProperty<Long> MAX_ATTEMPTS_PER_USERNAME = SystemProperty.Builder.ofType(Long.class)
.setKey("adminConsole.maxAttemptsPerUsername")
.setDynamic(true)
.setDefaultValue(10L)
.setMinValue(1L)
.build();
// Time frame before attempts per username are reset
public static final SystemProperty<Duration> PER_USERNAME_ATTEMPT_RESET_INTERVAL = SystemProperty.Builder.ofType(Duration.class)
.setKey("adminConsole.perUsernameAttemptResetInterval")
.setDynamic(false)
.setChronoUnit(ChronoUnit.MILLIS)
.setDefaultValue(Duration.ofMinutes(15))
.setMinValue(Duration.ofMillis(1))
.build();
// Record of attempts per IP address
private Map<String,Long> attemptsPerIP;
// Record of attempts per username
private Map<String,Long> attemptsPerUsername;
/**
* Constructs a new login limit manager.
*/
private LoginLimitManager() {
this(SecurityAuditManager.getInstance(), TaskEngine.getInstance());
}
/**
* Constructs a new login limit manager. Exposed for test use only.
*/
LoginLimitManager(final SecurityAuditManager securityAuditManager, final TaskEngine taskEngine) {
this.securityAuditManager = securityAuditManager;
// Set up initial maps
attemptsPerIP = new ConcurrentHashMap<>();
attemptsPerUsername = new ConcurrentHashMap<>();
// Set up per username attempt reset task
taskEngine.scheduleAtFixedRate(new PerUsernameTask(), Duration.ZERO, PER_USERNAME_ATTEMPT_RESET_INTERVAL.getValue());
// Set up per IP attempt reset task
taskEngine.scheduleAtFixedRate(new PerIPAddressTask(), Duration.ZERO, PER_IP_ATTEMPT_RESET_INTERVAL.getValue());
}
/**
* Returns true of the entered username or connecting IP address has hit it's attempt limit.
*
* @param username Username being checked.
* @param address IP address that is connecting.
* @return True if the login attempt limit has been hit.
*/
public boolean hasHitConnectionLimit(String username, String address) {
if (attemptsPerIP.get(address) != null && attemptsPerIP.get(address) > MAX_ATTEMPTS_PER_IP.getValue()) {
return true;
}
if (attemptsPerUsername.get(username) != null && attemptsPerUsername.get(username) > MAX_ATTEMPTS_PER_USERNAME.getValue()) {
return true;
}
// No problem then, no limit hit.
return false;
}
/**
* Records a failed connection attempt.
*
* @param username Username being attempted.
* @param address IP address that is attempting.
*/
public void recordFailedAttempt(String username, String address) {
Log.warn("Failed admin console login attempt by "+username+" from "+address);
Long cnt = (long)0;
if (attemptsPerIP.get(address) != null) {
cnt = attemptsPerIP.get(address);
}
cnt++;
attemptsPerIP.put(address, cnt);
final StringBuilder sb = new StringBuilder();
if (cnt > MAX_ATTEMPTS_PER_IP.getValue()) {
Log.warn("Login attempt limit breached for address "+address);
sb.append("Future login attempts from this address will be temporarily locked out. ");
}
cnt = (long)0;
if (attemptsPerUsername.get(username) != null) {
cnt = attemptsPerUsername.get(username);
}
cnt++;
attemptsPerUsername.put(username, cnt);
if (cnt > MAX_ATTEMPTS_PER_USERNAME.getValue()) {
Log.warn("Login attempt limit breached for username "+username);
sb.append("Future login attempts for this user will be temporarily locked out. ");
}
securityAuditManager.logEvent(username, "Failed admin console login attempt", "A failed login attempt to the admin console was made from address " + address + ". " + sb);
}
/**
* Clears failed login attempts if a success occurs.
*
* @param username Username being attempted.
* @param address IP address that is attempting.
*/
public void recordSuccessfulAttempt(String username, String address) {<FILL_FUNCTION_BODY>
|
attemptsPerIP.remove(address);
attemptsPerUsername.remove(username);
securityAuditManager.logEvent(username, "Successful admin console login attempt", "The user logged in successfully to the admin console from address " + address + ". ");
| 1,515
| 63
| 1,578
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/PluginFilter.java
|
PluginFilter
|
removePluginFilter
|
class PluginFilter implements Filter {
private static final Logger Log = LoggerFactory.getLogger( PluginFilter.class );
private static final Map<String, List<Filter>> filters = new ConcurrentHashMap<>();
/**
* Adds a filter to the list of filters that will be run on every request of which the URL matches the URL that
* is registered with this filter. More specifically, the request URL should be equal to, or start with, the filter
* URL.
*
* Multiple filters can be registered on the same URL, in which case they will be executed in the order in which
* they were added.
*
* Adding a filter does not initialize the plugin instance.
*
* @param filterUrl The URL pattern to which the filter is to be applied. Cannot be null nor an empty string.
* @param filter The filter. Cannot be null.
*/
public static void addPluginFilter( String filterUrl, Filter filter )
{
if ( filterUrl == null || filterUrl.isEmpty() || filter == null )
{
throw new IllegalArgumentException();
}
if ( !filters.containsKey( filterUrl ) )
{
filters.put( filterUrl, new ArrayList<>() );
}
final List<Filter> urlFilters = PluginFilter.filters.get( filterUrl );
if ( urlFilters.contains( filter ) )
{
Log.warn( "Cannot add filter '{}' as it was already added for URL '{}'!", filter, filterUrl );
}
else
{
urlFilters.add( filter );
Log.debug( "Added filter '{}' for URL '{}'", filter, filterUrl );
}
}
/**
* Removes a filter that is applied to a certain URL.
*
* Removing a filter does not destroy the plugin instance.
*
* @param filterUrl The URL pattern to which the filter is applied. Cannot be null nor an empty string.
* @param filterClassName The filter class name. Cannot be null or empty string.
* @return The filter instance that was removed, or null if the URL and name combination did not match a filter.
*/
public static Filter removePluginFilter( String filterUrl, String filterClassName )
{<FILL_FUNCTION_BODY>}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
/**
* This class is a Filter implementation itself. It acts as a dynamic proxy to filters that are registered by
* Openfire plugins.
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException
{
if ( servletRequest instanceof HttpServletRequest )
{
final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
final String requestPath = ( httpServletRequest.getContextPath() + httpServletRequest.getServletPath() + httpServletRequest.getPathInfo() ).toLowerCase();
final List<Filter> applicableFilters = new ArrayList<>();
for ( final Map.Entry<String, List<Filter>> entry : filters.entrySet() )
{
String filterUrl = entry.getKey();
if ( filterUrl.endsWith( "*" ))
{
filterUrl = filterUrl.substring( 0, filterUrl.length() -1 );
}
filterUrl = filterUrl.toLowerCase();
if ( requestPath.startsWith( filterUrl ) )
{
applicableFilters.addAll(entry.getValue());
}
}
if ( !applicableFilters.isEmpty() )
{
Log.debug( "Wrapping filter chain in order to run plugin-specific filters." );
filterChain = new FilterChainInjector( filterChain, applicableFilters );
}
}
else
{
Log.warn( "ServletRequest is not an instance of an HttpServletRequest." );
}
// Plugin filtering is done. Progress down the filter chain that was initially provided.
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
// If the destroy method is being called, the Openfire instance is being shutdown.
// Therefore, clear out the list of plugin filters.
filters.clear();
}
/**
* A wrapper that can be used to inject a list of filters into an existing a filter chain.
*
* An instance of this class is expected to be created within the execution of a 'parent' filter chain. After
* instantiation, the caller is expected to invoke #doFilter once, after which all provided filters will be
* invoked. Afterwards, the original filter chain (as supplied in the constructor) will be resumed.
*
* @author Guus der Kinderen, guus.der.kinderen@gmail.com
*/
private static class FilterChainInjector implements FilterChain
{
private static final Logger Log = LoggerFactory.getLogger( FilterChainInjector.class );
private final FilterChain parentChain;
private final List<Filter> filters;
private int index = 0;
/**
* Creates a new instance.
*
* @param parentChain the chain to which the filters are to be appended (cannot be null).
* @param filters The filters to append (cannot be null, but can be empty).
*/
private FilterChainInjector( FilterChain parentChain, List<Filter> filters )
{
if ( parentChain == null || filters == null )
{
throw new IllegalArgumentException();
}
this.parentChain = parentChain;
this.filters = filters;
}
@Override
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse ) throws IOException, ServletException
{
if ( index < filters.size() )
{
Log.trace( "Executing injected filter {} of {}...", index + 1, filters.size() );
filters.get( index++ ).doFilter( servletRequest, servletResponse, this );
}
else
{
Log.trace( "Executed all injected filters. Resuming original chain." );
parentChain.doFilter( servletRequest, servletResponse );
}
}
}
}
|
if ( filterUrl == null || filterUrl.isEmpty() || filterClassName == null || filterClassName.isEmpty() )
{
throw new IllegalArgumentException();
}
Filter result = null;
if ( filters.containsKey( filterUrl ) )
{
final List<Filter> urlFilters = PluginFilter.filters.get( filterUrl );
final Iterator<Filter> iterator = urlFilters.iterator();
while ( iterator.hasNext() )
{
final Filter filter = iterator.next();
if ( filter.getClass().getName().equals( filterClassName ) )
{
iterator.remove();
result = filter; // assumed to be unique, but check the entire collection to avoid leaks.
}
}
if ( urlFilters.isEmpty() )
{
filters.remove( filterUrl );
}
}
if ( result == null )
{
Log.warn( "Unable to removed filter of class '{}' for URL '{}'. No such filter is present.", filterClassName, filterUrl );
}
else
{
Log.debug( "Removed filter '{}' for URL '{}'", result, filterUrl );
}
return result;
| 1,553
| 306
| 1,859
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/SiteMinderServletRequestAuthenticator.java
|
SiteMinderServletRequestAuthenticator
|
authenticateRequest
|
class SiteMinderServletRequestAuthenticator implements ServletRequestAuthenticator {
public static final SystemProperty<String> SITE_MINDER_HEADER = SystemProperty.Builder.ofType(String.class)
.setKey("adminConsole.siteMinderHeader")
.setDefaultValue("SM_USER")
.setDynamic(true)
.build();
/**
* Indicates if this ServletRequestAuthenticator is enabled or not
*
* @return {@code true} if enabled, otherwise {@code false}
*/
public static boolean isEnabled() {
return AuthCheckFilter.isServletRequestAuthenticatorInstanceOf(SiteMinderServletRequestAuthenticator.class);
}
@Override
public String authenticateRequest(final HttpServletRequest request) {<FILL_FUNCTION_BODY>}
}
|
final String smUser = request.getHeader(SITE_MINDER_HEADER.getValue());
if (smUser == null || smUser.trim().isEmpty()) {
// SiteMinder has not authenticated the user
return null;
} else {
return smUser;
}
| 207
| 75
| 282
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/SubSidebarTag.java
|
SubSidebarTag
|
doStartTag
|
class SubSidebarTag extends SidebarTag {
private SidebarTag parent;
private String body;
/**
* Returns the body content of this tag.
* @return the body of the tag
*/
public String getBody() {
return body;
}
/**
* Sets the body content of this tag.
* @param body the body of this tag
*/
public void setBody(String body) {
this.body = body;
}
/**
* Looks for the parent SidebarTag class, throws an error if not found. If found,
* {@link #EVAL_BODY_BUFFERED} is returned.
*
* @return {@link #EVAL_BODY_BUFFERED} if no errors.
* @throws javax.servlet.jsp.JspException if a parent SidebarTag is not found.
*/
@Override
public int doStartTag() throws JspException {<FILL_FUNCTION_BODY>}
/**
* Sets the 'body' property to be equal to the body content of this tag. Calls the
* {@link SidebarTag#setSubSidebar(SubSidebarTag)} method of the parent tag.
* @return {@link #EVAL_PAGE}
* @throws JspException if an error occurs.
*/
@Override
public int doEndTag() throws JspException {
setBody(bodyContent.getString());
parent.setSubSidebar(this);
return EVAL_PAGE;
}
}
|
// The I18nTag should be our parent Tag
parent = (SidebarTag)findAncestorWithClass(this, SidebarTag.class);
// If I18nTag was not our parent, throw Exception
if (parent == null) {
throw new JspTagException("SubSidebarTag with out a parent which is expected to be a SidebarTag");
}
return EVAL_BODY_BUFFERED;
| 386
| 112
| 498
|
<methods>public non-sealed void <init>() ,public int doEndTag() throws JspException,public int doStartTag() throws JspException,public java.lang.String getCss() ,public java.lang.String getCurrentcss() ,public java.lang.String getHeadercss() ,public org.jivesoftware.admin.SubSidebarTag getSubsidebarTag() ,public void setCss(java.lang.String) ,public void setCurrentcss(java.lang.String) ,public void setHeadercss(java.lang.String) ,public void setSubSidebar(org.jivesoftware.admin.SubSidebarTag) <variables>private java.lang.String css,private java.lang.String currentcss,private java.lang.String headercss,private org.jivesoftware.admin.SubSidebarTag subsidebarTag
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/SubnavTag.java
|
SubnavTag
|
doEndTag
|
class SubnavTag extends BodyTagSupport {
private String css;
private String currentcss;
/**
* Returns the value of the CSS class to be used for tab decoration. If not set will return a blank string.
* @return the CSS for the tab
*/
public String getCss() {
return clean(css);
}
/**
* Sets the CSS used for tab decoration.
* @param css The CSS for the tab
*/
public void setCss(String css) {
this.css = css;
}
/**
* Returns the value of the CSS class to be used for the currently selected LI (tab). If not set will
* return a blank string.
* @return the CSS class
*/
public String getCurrentcss() {
return clean(currentcss);
}
/**
* Sets the CSS class value for the currently selected tab.
* @param currentcss the CSS class
*/
public void setCurrentcss(String currentcss) {
this.currentcss = currentcss;
}
/**
* Does nothing, returns {@link #EVAL_BODY_BUFFERED} always.
*/
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
/**
* Gets the {@link AdminPageBean} instance from the request. If it doesn't exist then execution is stopped
* and nothing is printed. If it exists, retrieve values from it and render the sidebar items. The body content
* of the tag is assumed to have an A tag in it with tokens to replace (see class description) as well
* as having a subsidebar tag..
*
* @return {@link #EVAL_PAGE} after rendering the tabs.
* @throws JspException if an exception occurs while rendering the sidebar items.
*/
@Override
public int doEndTag() throws JspException {<FILL_FUNCTION_BODY>}
/**
* Cleans the given string - if it's null, it's converted to a blank string. If it has ' then those are
* converted to double ' so HTML isn't screwed up.
*
* @param in the string to clean
* @return a cleaned version - not null and with escaped characters.
*/
private String clean(String in) {
return (in == null ? "" : in.replaceAll("'", "\\'"));
}
}
|
// Start by getting the request from the page context
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
// Check for body of this tag and the child tag
if (getBodyContent().getString() == null) {
throw new JspException("Error, no template (body value) set for the sidebar tag.");
}
// Get the initial subpage and page IDs
String subPageID = (String)request.getAttribute("subPageID");
String pageID = (String)request.getAttribute("pageID");
// If the pageID is null, use the subPageID to set it. If both the pageID and
// subPageIDs are null, return because these are key to execution of the tag.
if (subPageID != null || pageID != null) {
if (pageID == null) {
Element subPage = AdminConsole.getElemnetByID(subPageID);
pageID = subPage.getParent().getParent().attributeValue("id");
}
// Top level menu items
if (AdminConsole.getModel().elements().size() > 0) {
JspWriter out = pageContext.getOut();
StringBuilder buf = new StringBuilder();
Element current = null;
Element subcurrent = null;
Element subnav = null;
if (subPageID != null) {
subcurrent = AdminConsole.getElemnetByID(subPageID);
}
current = AdminConsole.getElemnetByID(pageID);
if (current != null) {
if (subcurrent != null) {
subnav = subcurrent.getParent().getParent().getParent();
}
else {
subnav = current.getParent();
}
}
Element currentTab = (Element)AdminConsole.getModel().selectSingleNode(
"//*[@id='" + pageID + "']/ancestor::tab");
// Loop through all items in the root, print them out
if (currentTab != null) {
Collection items = currentTab.elements();
if (items.size() > 0) {
buf.append("<ul>");
for (Object itemObj : items) {
Element item = (Element) itemObj;
if (item.elements().size() > 0) {
Element firstSubItem = (Element)item.elements().get(0);
String pluginName = item.attributeValue("plugin");
String subitemID = item.attributeValue("id");
String subitemName = item.attributeValue("name");
String subitemURL = firstSubItem.attributeValue("url");
String subitemDescr = item.attributeValue("description");
String value = getBodyContent().getString();
if (value != null) {
value = value.replaceAll("\\[id]", clean(subitemID));
value = value.replaceAll("\\[name]", clean(AdminConsole.getAdminText(subitemName, pluginName)));
value = value.replaceAll("\\[description]", clean(AdminConsole.getAdminText(subitemDescr, pluginName)));
value = value.replaceAll("\\[url]",request.getContextPath() + "/" + clean(subitemURL));
}
String css = getCss();
boolean isCurrent = subnav != null && item.equals(subnav);
if (isCurrent) {
css = getCurrentcss();
}
buf.append("<li class=\"").append(css).append("\">").append(value).append("</li>");
}
}
buf.append("</ul>");
try {
out.write(buf.toString());
}
catch (IOException e) {
throw new JspException(e);
}
}
}
}
}
return EVAL_PAGE;
| 612
| 961
| 1,573
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/TabsTag.java
|
TabsTag
|
doEndTag
|
class TabsTag extends BodyTagSupport {
private String bean;
private String css;
private String currentcss;
private Boolean justlinks = false;
/**
* The name of the request attribute which holds a {@link AdminPageBean} instance.
* @return the name of the bean
*/
public String getBean() {
return bean;
}
/**
* Sets the name of the request attribute to hold a {@link AdminPageBean} instance.
* @param bean the name of the bean
*/
public void setBean(String bean) {
this.bean = bean;
}
/**
* Returns the value of the CSS class to be used for tab decoration. If not set will return a blank string.
* @return the CSS
*/
public String getCss() {
return clean(css);
}
/**
* Sets the CSS used for tab decoration.
* @param css the CSS
*/
public void setCss(String css) {
this.css = css;
}
/**
* Returns the value of the CSS class to be used for the currently selected LI (tab). If not set will
* return a blank string.
* @return the CSS class
*/
public String getCurrentcss() {
return clean(currentcss);
}
/**
* Sets the CSS class value for the currently selected tab.
* @param currentcss the CSS class
*/
public void setCurrentcss(String currentcss) {
this.currentcss = currentcss;
}
/**
* Returns whether we are in just links mode.
* @return {@code true} if just displaying links, otherwise {@code false}
*/
public Boolean getJustlinks() {
return justlinks;
}
/**
* Sets whether we are just to display links, no list.
* @param justlinks {@code true} to just display links, otherwise {@code false}
*/
public void setJustlinks(Boolean justlinks) {
this.justlinks = justlinks;
}
/**
* Does nothing, returns {@link #EVAL_BODY_BUFFERED} always.
*/
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
/**
* Gets the {@link AdminPageBean} instance from the request. If it doesn't exist then execution is stopped
* and nothing is printed. If it exists, retrieve values from it and render the tabs. The body content
* of the tag is assumed to have an A tag in it with tokens to replace (see class description).
*
* @return {@link #EVAL_PAGE} after rendering the tabs.
* @throws JspException if an exception occurs while rendering the tabs.
*/
@Override
public int doEndTag() throws JspException {<FILL_FUNCTION_BODY>}
/**
* Cleans the given string - if it's null, it's converted to a blank string. If it has ' then those are
* converted to double ' so HTML isn't screwed up.
*
* @param in the string to clean
* @return a cleaned version - not null and with escaped characters.
*/
private String clean(String in) {
return (in == null ? "" : in.replaceAll("'", "\\'"));
}
}
|
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
// Get the page data bean from the request:
// If the page info bean is not in the request then no tab will be selected - so, it'll fail gracefully
String pageID = (String)request.getAttribute("pageID");
String subPageID = (String)request.getAttribute("subPageID");
if (pageID == null) {
Element subPage = AdminConsole.getElemnetByID(subPageID);
if (subPage != null) {
pageID = subPage.getParent().getParent().attributeValue("id");
}
}
// Get tabs from the model:
List tabs = AdminConsole.getModel().selectNodes("//tab");
if (tabs.size() > 0) {
JspWriter out = pageContext.getOut();
// Build up the output in a buffer (is probably faster than a bunch of out.write's)
StringBuilder buf = new StringBuilder();
if (!justlinks) { buf.append("<ul>"); }
String body = getBodyContent().getString();
// For each tab, print out an <LI>.
Element currentTab = null;
if (pageID != null) {
currentTab = (Element)AdminConsole.getModel().selectSingleNode(
"//*[@id='" + pageID + "']/ancestor::tab");
}
for (int i=0; i<tabs.size(); i++) {
Element tab = (Element)tabs.get(i);
String value = body;
if (value != null) {
// The URL for the tab should be the URL of the first item in the tab.
String pluginName = tab.attributeValue("plugin");
value = value.replaceAll("\\[id]", clean(tab.attributeValue("id")));
value = value.replaceAll("\\[url]",request.getContextPath() + "/" + clean(tab.attributeValue("url")));
value = value.replaceAll("\\[name]", clean(AdminConsole.getAdminText(tab.attributeValue("name"), pluginName)));
value = value.replaceAll("\\[description]", clean(AdminConsole.getAdminText(tab.attributeValue("description"), pluginName)));
}
String css = getCss();
if (tab.equals(currentTab)) {
css = getCurrentcss();
}
if (!justlinks) { buf.append("<li class=\"").append(css).append("\">"); }
if (justlinks && i > 0) { buf.append(" | "); }
buf.append(value);
if (!justlinks) { buf.append("</li>"); }
}
if (!justlinks) { buf.append("</ul>"); }
try {
out.write(buf.toString());
}
catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}
}
return EVAL_PAGE;
| 846
| 750
| 1,596
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/servlet/BlogPostServlet.java
|
BlogPostServlet
|
parseFirstEntries
|
class BlogPostServlet extends HttpServlet {
public static final SystemProperty<Boolean> ENABLED = SystemProperty.Builder.ofType(Boolean.class)
.setKey("rss.enabled")
.setDynamic(true)
.setDefaultValue(true)
.addListener((b) -> lastRSSFetch = Instant.EPOCH)
.build();
public static final SystemProperty<String> URL = SystemProperty.Builder.ofType(String.class)
.setKey("rss.url")
.setDynamic(true)
.setDefaultValue("https://discourse.igniterealtime.org/c/blogs/ignite-realtime-blogs.rss")
.addListener((b) -> lastRSSFetch = Instant.EPOCH)
.build();
public static final SystemProperty<Duration> REFRESH = SystemProperty.Builder.ofType(Duration.class)
.setKey("rss.refresh")
.setDynamic(true)
.setDefaultValue(Duration.ofHours(6))
.setChronoUnit(ChronoUnit.MINUTES)
.addListener((b) -> lastRSSFetch = Instant.EPOCH)
.build();
private static final Logger Log = LoggerFactory.getLogger(BlogPostServlet.class);
private static Instant lastRSSFetch = Instant.EPOCH;
private JSONArray lastItems = null;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
synchronized (this) {
if (lastItems == null || Duration.between(lastRSSFetch, Instant.now()).compareTo(REFRESH.getDefaultValue()) > 0) {
Log.debug("Trying to obtain latest blog posts from IgniteRealtime.org");
final String proxyHost = UpdateManager.PROXY_HOST.getValue();
final int proxyPort = UpdateManager.PROXY_PORT.getValue();
final HttpRoutePlanner routePlanner;
if (proxyHost != null && !proxyHost.isEmpty() && proxyPort > 0) {
routePlanner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort, "http"));
} else {
routePlanner = new DefaultRoutePlanner(null);
}
final HttpGet httpGet = new HttpGet(URL.getValue());
try (final CloseableHttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build();
final CloseableHttpResponse httpResponse = client.execute(httpGet);
final InputStream stream = httpResponse.getEntity().getContent()) {
lastItems = parseFirstEntries(stream, 7);
lastRSSFetch = Instant.now();
} catch (final Throwable throwable) {
Log.warn("Unable to download blogposts from igniterealtime.org", throwable);
}
}
}
final JSONObject result = new JSONObject();
result.put("items", lastItems);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(result.toString(2));
}
/**
* Parses the input stream, expected to contain RSS data, into the proprietary format used by the admin console.
*
* @param inputStream An input stream of RSS data
* @param count The maximum number of items to return.
* @return A collection or RSS items.
*/
static JSONArray parseFirstEntries(final InputStream inputStream, final int count) throws ExecutionException, InterruptedException
{<FILL_FUNCTION_BODY>}
}
|
final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
final JSONArray result = new JSONArray();
final Document document = SAXReaderUtil.readDocument(inputStream);
final List<Node> nodes = document.selectNodes("/rss/channel/item");
for (final Node node : nodes) {
if (!(node instanceof Element)) {
continue;
}
try {
final Element item = (Element) node;
final JSONObject o = new JSONObject();
o.put("link", item.elementText("link"));
o.put("title", item.elementText("title"));
o.put("date", JiveGlobals.formatDate(dateFormat.parse(item.elementText("pubDate"))));
result.put(o);
} catch (Exception e) {
Log.debug("Unable to parse element as RSS data: {}", node.asXML(), e);
}
if (result.length() >= count) {
break;
}
}
return result;
| 958
| 282
| 1,240
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/servlet/SecurityAuditViewerServlet.java
|
SecurityAuditViewerServlet
|
doGet
|
class SecurityAuditViewerServlet extends HttpServlet {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");
private static final String[] SEARCH_FIELDS = {"searchUsername", "searchNode", "searchSummary", "searchFrom", "searchTo"};
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
private static Optional<Date> parseSearchDate(final String searchDate) {
try {
return Optional.ofNullable(DATE_FORMAT.parse(searchDate));
} catch (ParseException e) {
return Optional.empty();
}
}
public static class Search {
private final String username;
private final String node;
private final String summary;
private final String from;
private final String to;
public Search(final HttpServletRequest request) {
this.username = ParamUtils.getStringParameter(request, "searchUsername", "").trim();
this.node = ParamUtils.getStringParameter(request, "searchNode", "").trim();
this.summary = ParamUtils.getStringParameter(request, "searchSummary", "").trim();
this.from = ParamUtils.getStringParameter(request, "searchFrom", "").trim();
this.to = ParamUtils.getStringParameter(request, "searchTo", "").trim();
}
public String getUsername() {
return username;
}
public String getNode() {
return node;
}
public String getSummary() {
return summary;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
}
}
|
final SecurityAuditProvider securityAuditProvider = SecurityAuditManager.getSecurityAuditProvider();
final List<SecurityAuditEvent> events;
if (securityAuditProvider.isWriteOnly()) {
events = Collections.emptyList();
} else {
// The ListPager deals with paging & filtering so fetch all events
events = securityAuditProvider.getEvents(null, null, null, null, null);
}
final Search search = new Search(request);
Predicate<SecurityAuditEvent> predicate = auditEvent -> true;
if (!search.username.isEmpty()) {
predicate = predicate.and(event -> StringUtils.containsIgnoringCase(event.getUsername(), search.username));
}
if (!search.node.isEmpty()) {
predicate = predicate.and(event -> StringUtils.containsIgnoringCase(event.getNode(), search.node));
}
if (!search.summary.isEmpty()) {
predicate = predicate.and(event -> StringUtils.containsIgnoringCase(event.getSummary(), search.summary));
}
Optional<Date> from;
if (!search.from.isEmpty()) {
from = parseSearchDate(search.from);
if (!from.isPresent()) {
// Nothing matches a bad date!
predicate = auditEvent -> false;
}
} else {
from = Optional.empty();
}
Optional<Date> to;
if (!search.to.isEmpty()) {
to = parseSearchDate(search.to);
if (!to.isPresent()) {
// Nothing matches a bad date!
predicate = auditEvent -> false;
}
} else {
to = Optional.empty();
}
// Make sure the from/to are the correct way around
if (from.isPresent() && to.isPresent() && from.get().after(to.get())) {
final Optional<Date> temp = to;
to = from;
from = temp;
}
if (from.isPresent()) {
final Date date = from.get();
predicate = predicate.and(auditEvent -> !auditEvent.getEventStamp().before(date));
}
if (to.isPresent()) {
// Intuitively the end date is exclusive, so add an extra day
final Date date = Date.from(to.get().toInstant().plus(1, ChronoUnit.DAYS));
predicate = predicate.and(auditEvent -> auditEvent.getEventStamp().before(date));
}
final ListPager<SecurityAuditEvent> listPager = new ListPager<>(request, response, events, predicate, SEARCH_FIELDS);
request.setAttribute("securityAuditProvider", securityAuditProvider);
request.setAttribute("listPager", listPager);
request.setAttribute("search", search);
request.getRequestDispatcher("security-audit-viewer-jsp.jsp").forward(request, response);
| 445
| 752
| 1,197
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/admin/servlet/SystemCacheDetailsServlet.java
|
SystemCacheDetailsServlet
|
doPost
|
class SystemCacheDetailsServlet extends HttpServlet {
private static final String[] SEARCH_FIELDS = {"cacheName", "searchKey", "searchValue"};
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
final String cacheName = ParamUtils.getStringParameter(request, "cacheName", "").trim();
final Optional<Cache<?, ?>> optionalCache = Arrays.stream(CacheFactory.getAllCaches())
.filter(cache -> cacheName.equals(cache.getName()))
.findAny()
.map(cache -> (Cache<?, ?>) cache);
if (!optionalCache.isPresent()) {
request.setAttribute("warningMessage", LocaleUtils.getLocalizedString("system.cache-details.cache_not_found", Collections.singletonList(StringUtils.escapeHTMLTags(cacheName))));
}
final boolean secretKey = optionalCache.map(Cache::isKeySecret).orElse(Boolean.FALSE);
final boolean secretValue = optionalCache.map(Cache::isValueSecret).orElse(Boolean.FALSE);
final List<Map.Entry<String, String>> cacheEntries = optionalCache.map(Cache::entrySet)
.map(Collection::stream)
.orElseGet(Stream::empty)
.map(entry -> new AbstractMap.SimpleEntry<>(secretKey ? "************" : entry.getKey().toString(), secretValue ? "************" : entry.getValue().toString()))
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList());
// Find what we're searching for
final Search search = new Search(request);
Predicate<Map.Entry<String, String>> predicate = entry -> true;
if (!search.key.isEmpty() && !secretKey) {
predicate = predicate.and(entry -> StringUtils.containsIgnoringCase(entry.getKey(), search.key));
}
if (!search.value.isEmpty() && !secretValue) {
predicate = predicate.and(entry -> StringUtils.containsIgnoringCase(entry.getValue(), search.value));
}
final ListPager<Map.Entry<String, String>> listPager = new ListPager<>(request, response, cacheEntries, predicate, SEARCH_FIELDS);
final String csrf = StringUtils.randomString(16);
CookieUtils.setCookie(request, response, "csrf", csrf, -1);
addSessionFlashes(request, "errorMessage", "warningMessage", "successMessage");
request.setAttribute("csrf", csrf);
request.setAttribute("cacheName", cacheName);
request.setAttribute("listPager", listPager);
request.setAttribute("search", search);
request.getRequestDispatcher("system-cache-details.jsp").forward(request, response);
}
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>}
private void deleteProperty(final HttpServletRequest request, final HttpServletResponse response, final HttpSession session) {
final String cacheName = ParamUtils.getStringParameter(request, "cacheName", "").trim();
final String key = ParamUtils.getStringParameter(request, "key", "");
final Optional<Cache<?, ?>> optionalCache = Arrays.stream(CacheFactory.getAllCaches())
.filter(cache -> cacheName.equals(cache.getName()))
.findAny()
.map(cache -> (Cache<?, ?>) cache);
if(optionalCache.isPresent()) {
if(optionalCache.get().remove(key) != null ) {
session.setAttribute("successMessage", LocaleUtils.getLocalizedString("system.cache-details.deleted",
Collections.singletonList(StringEscapeUtils.escapeXml11(key))));
final WebManager webManager = new WebManager();
webManager.init(request, response, session, session.getServletContext());
webManager.logEvent(String.format("Key '%s' deleted from cache '%s'", key, cacheName), null);
} else {
session.setAttribute("errorMessage", LocaleUtils.getLocalizedString("system.cache-details.key_not_found",
Collections.singletonList(StringEscapeUtils.escapeXml11(key))));
}
} else {
request.setAttribute("warningMessage", LocaleUtils.getLocalizedString("system.cache-details.cache_not_found",
Collections.singletonList(StringEscapeUtils.escapeXml11(cacheName))));
}
}
private static void addSessionFlashes(final HttpServletRequest request, final String... flashes) {
final HttpSession session = request.getSession();
for (final String flash : flashes) {
final Object flashValue = session.getAttribute(flash);
if (flashValue != null) {
request.setAttribute(flash, flashValue);
session.setAttribute(flash, null);
}
}
}
/**
* Represents the entries being searched for
*/
public static final class Search {
private final String key;
private final String value;
public Search(final HttpServletRequest request) {
this.key = ParamUtils.getStringParameter(request, "searchKey", "").trim();
this.value = ParamUtils.getStringParameter(request, "searchValue", "").trim();
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
}
|
final HttpSession session = request.getSession();
final Cookie csrfCookie = CookieUtils.getCookie(request, "csrf");
if (csrfCookie == null || !csrfCookie.getValue().equals(request.getParameter("csrf"))) {
session.setAttribute("errorMessage", LocaleUtils.getLocalizedString("global.csrf.failed"));
} else {
final WebManager webManager = new WebManager();
webManager.init(request, response, session, session.getServletContext());
final String action = ParamUtils.getStringParameter(request, "action", "");
switch (action) {
case "delete":
deleteProperty(request, response, session);
break;
case "cancel":
session.setAttribute("warningMessage", LocaleUtils.getLocalizedString("system.cache-details.cancelled"));
break;
default:
session.setAttribute("warningMessage", LocaleUtils.getLocalizedString("global.request-error-no-such-action", Collections.singletonList(action)));
break;
}
}
response.sendRedirect(request.getRequestURI() + ListPager.getQueryString(request, '?', SEARCH_FIELDS));
| 1,407
| 309
| 1,716
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/database/CachedPreparedStatement.java
|
CachedPreparedStatement
|
toString
|
class CachedPreparedStatement {
private static final Logger Log = LoggerFactory.getLogger(CachedPreparedStatement.class);
private String sql;
private List<Object> params;
private List<Integer> types;
/**
* Constructs a new CachedPreparedStatement.
*/
public CachedPreparedStatement() {
params = new ArrayList<>();
types = new ArrayList<>();
}
/**
* Constructs a new CachedPreparedStatement.
*
* @param sql the SQL.
*/
public CachedPreparedStatement(String sql) {
this();
setSQL(sql);
}
/**
* Returns the SQL.
*
* @return the SQL.
*/
public String getSQL() {
return sql;
}
/**
* Sets the SQL.
*
* @param sql the SQL.
*/
public void setSQL(String sql) {
this.sql = sql;
}
/**
* Adds a boolean parameter to the prepared statement.
*
* @param value the boolean value.
*/
public void addBoolean(boolean value) {
params.add(value);
types.add(Types.BOOLEAN);
}
/**
* Adds an integer parameter to the prepared statement.
*
* @param value the int value.
*/
public void addInt(int value) {
params.add(value);
types.add(Types.INTEGER);
}
/**
* Adds a long parameter to the prepared statement.
*
* @param value the long value.
*/
public void addLong(long value) {
params.add(value);
types.add(Types.BIGINT);
}
/**
* Adds a String parameter to the prepared statement.
*
* @param value the String value.
*/
public void addString(String value) {
params.add(value);
types.add(Types.VARCHAR);
}
/**
* Sets all parameters on the given PreparedStatement. The standard code block
* for turning a CachedPreparedStatement into a PreparedStatement is as follows:
*
* <pre>
* PreparedStatement pstmt = con.prepareStatement(cachedPstmt.getSQL());
* cachedPstmt.setParams(pstmt);
* </pre>
*
* @param pstmt the prepared statement.
* @throws java.sql.SQLException if an SQL Exception occurs.
*/
public void setParams(PreparedStatement pstmt) throws SQLException {
for (int i=0; i<params.size(); i++) {
Object param = params.get(i);
int type = types.get(i);
// Set param, noting fact that params start at 1 and not 0.
switch(type) {
case Types.INTEGER:
pstmt.setInt(i+1, (Integer)param);
break;
case Types.BIGINT:
pstmt.setLong(i+1, (Long)param);
break;
case Types.VARCHAR:
pstmt.setString(i+1, (String)param);
break;
case Types.BOOLEAN:
pstmt.setBoolean(i+1, (Boolean)param);
}
}
}
@Override
public boolean equals(Object object) {
if (object == null) {
return false;
}
if (!(object instanceof CachedPreparedStatement)) {
return false;
}
if (this == object) {
return true;
}
CachedPreparedStatement otherStmt = (CachedPreparedStatement)object;
return (sql == null && otherStmt.sql == null) || sql != null && sql.equals(otherStmt.sql)
&& types.equals(otherStmt.types) && params.equals(otherStmt.params);
}
@Override
public int hashCode() {
int hashCode = 1;
if (sql != null) {
hashCode += sql.hashCode();
}
hashCode = hashCode * 31 + types.hashCode();
hashCode = hashCode * 31 + params.hashCode();
return hashCode;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
String toStringSql = sql;
try {
int index = toStringSql.indexOf('?');
int count = 0;
while (index > -1) {
Object param = params.get(count);
int type = types.get(count);
String val = null;
// Get param
switch(type) {
case Types.INTEGER:
val = "" + param;
break;
case Types.BIGINT:
val = "" + param;
break;
case Types.VARCHAR:
val = '\'' + (String) param + '\'';
break;
case Types.BOOLEAN:
val = "" + param;
}
toStringSql = toStringSql.substring(0, index) + val +
((index == toStringSql.length() -1) ? "" : toStringSql.substring(index + 1));
index = toStringSql.indexOf('?', index + val.length());
count++;
}
}
catch (Exception e) {
Log.error(e.getMessage(), e);
}
return "CachedPreparedStatement{ sql=" + toStringSql + '}';
| 1,138
| 307
| 1,445
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/database/EmbeddedConnectionProvider.java
|
EmbeddedConnectionProvider
|
start
|
class EmbeddedConnectionProvider implements ConnectionProvider {
private static final Logger Log = LoggerFactory.getLogger(EmbeddedConnectionProvider.class);
private String serverURL;
private PoolingDataSource<PoolableConnection> dataSource;
public EmbeddedConnectionProvider() {
}
@Override
public boolean isPooled() {
return true;
}
@Override
public Connection getConnection() throws SQLException {
if (dataSource == null) {
throw new SQLException("Check HSQLDB properties; data source was not be initialised");
}
return dataSource.getConnection();
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
@Override
public void restart() {
// Kill off pool.
destroy();
// Start a new pool.
start();
}
@Override
public void destroy() {
// Shutdown the database.
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement("SHUTDOWN");
pstmt.execute();
}
catch (SQLException sqle) {
Log.error(sqle.getMessage(), sqle);
}
finally {
DbConnectionManager.closeConnection(pstmt, con);
}
}
@Override
public void finalize() throws Throwable {
destroy();
super.finalize();
}
}
|
final Path databaseDir = JiveGlobals.getHomePath().resolve("embedded-db");
try {
// If the database doesn't exist, create it.
if (!Files.exists(databaseDir)) {
Files.createDirectory(databaseDir);
}
} catch (IOException e) {
Log.error("Unable to create 'embedded-db' directory", e);
}
serverURL = "jdbc:hsqldb:" + databaseDir.resolve("openfire");
final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, "sa", "");
final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
poolableConnectionFactory.setMaxConnLifetimeMillis(Duration.ofHours(12).toMillis());
final GenericObjectPoolConfig<PoolableConnection> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setMinIdle(3);
poolConfig.setMaxTotal(25);
final GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
poolableConnectionFactory.setPool(connectionPool);
dataSource = new PoolingDataSource<>(connectionPool);
| 379
| 308
| 687
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/database/JNDIDataSourceProvider.java
|
JNDIDataSourceProvider
|
start
|
class JNDIDataSourceProvider implements ConnectionProvider {
private static final Logger Log = LoggerFactory.getLogger(JNDIDataSourceProvider.class);
private String dataSourceName;
private DataSource dataSource;
/**
* Keys of JNDI properties to query PropertyManager for.
*/
public static final String[] jndiPropertyKeys = {
Context.APPLET,
Context.AUTHORITATIVE,
Context.BATCHSIZE,
Context.DNS_URL,
Context.INITIAL_CONTEXT_FACTORY,
Context.LANGUAGE,
Context.OBJECT_FACTORIES,
Context.PROVIDER_URL,
Context.REFERRAL,
Context.SECURITY_AUTHENTICATION,
Context.SECURITY_CREDENTIALS,
Context.SECURITY_PRINCIPAL,
Context.SECURITY_PROTOCOL,
Context.STATE_FACTORIES,
Context.URL_PKG_PREFIXES
};
/**
* Constructs a new JNDI pool.
*/
public JNDIDataSourceProvider() {
dataSourceName = JiveGlobals.getXMLProperty("database.JNDIProvider.name");
}
@Override
public boolean isPooled() {
return true;
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
@Override
public void restart() {
destroy();
start();
}
@Override
public void destroy() {
}
@Override
public Connection getConnection() throws SQLException {
if (dataSource == null) {
throw new SQLException("DataSource has not been initialized.");
}
return dataSource.getConnection();
}
}
|
if (dataSourceName == null || dataSourceName.equals("")) {
Log.error("No name specified for DataSource. JNDI lookup will fail", new Throwable());
return;
}
try {
Properties contextProperties = new Properties();
for (String key: jndiPropertyKeys) {
String value = JiveGlobals.getXMLProperty(key);
if (value != null) {
contextProperties.setProperty(key, value);
}
}
Context context;
if (contextProperties.size() > 0) {
context = new InitialContext(contextProperties);
}
else {
context = new InitialContext();
}
dataSource = (DataSource)context.lookup(dataSourceName);
}
catch (Exception e) {
Log.error("Could not lookup DataSource at '" + dataSourceName + "'", e);
}
| 460
| 226
| 686
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/database/ProfiledConnection.java
|
TimedStatement
|
execute
|
class TimedStatement extends StatementWrapper {
private Statement stmt;
/**
* Creates a new TimedStatement that wraps {@code stmt}.
*
* @param stmt the statement.
*/
public TimedStatement(Statement stmt) {
super(stmt);
this.stmt = stmt;
}
public boolean execute(String sql) throws SQLException {<FILL_FUNCTION_BODY>}
public ResultSet executeQuery(String sql) throws SQLException {
long t1 = System.currentTimeMillis();
ResultSet result = stmt.executeQuery(sql);
long t2 = System.currentTimeMillis();
// determine the type of query
String sqlL = sql.toLowerCase().trim();
if (sqlL.startsWith("insert")) {
addQuery(Type.insert, sql, t2 - t1);
}
else if (sqlL.startsWith("update")) {
addQuery(Type.update, sql, t2 - t1);
}
else if (sqlL.startsWith("delete")) {
addQuery(Type.delete, sql, t2 - t1);
}
else {
addQuery(Type.select, sql, t2 - t1);
}
return result;
}
public int executeUpdate(String sql) throws SQLException {
long t1 = System.currentTimeMillis();
int result = stmt.executeUpdate(sql);
long t2 = System.currentTimeMillis();
// determine the type of query
String sqlL = sql.toLowerCase().trim();
if (sqlL.startsWith("insert")) {
addQuery(Type.insert, sql, t2 - t1);
}
else if (sqlL.startsWith("update")) {
addQuery(Type.update, sql, t2 - t1);
}
else if (sqlL.startsWith("delete")) {
addQuery(Type.delete, sql, t2 - t1);
}
else {
addQuery(Type.select, sql, t2 - t1);
}
return result;
}
}
|
long t1 = System.currentTimeMillis();
boolean result = stmt.execute(sql);
long t2 = System.currentTimeMillis();
// determine the type of query
String sqlL = sql.toLowerCase().trim();
if (sqlL.startsWith("insert")) {
addQuery(Type.insert, sql, t2 - t1);
}
else if (sqlL.startsWith("update")) {
addQuery(Type.update, sql, t2 - t1);
}
else if (sqlL.startsWith("delete")) {
addQuery(Type.delete, sql, t2 - t1);
}
else {
addQuery(Type.select, sql, t2 - t1);
}
return result;
| 546
| 199
| 745
|
<methods>public void abort(java.util.concurrent.Executor) throws java.sql.SQLException,public void clearWarnings() throws java.sql.SQLException,public void close() throws java.sql.SQLException,public void commit() throws java.sql.SQLException,public java.sql.Array createArrayOf(java.lang.String, java.lang.Object[]) throws java.sql.SQLException,public java.sql.Blob createBlob() throws java.sql.SQLException,public java.sql.Clob createClob() throws java.sql.SQLException,public java.sql.NClob createNClob() throws java.sql.SQLException,public java.sql.SQLXML createSQLXML() throws java.sql.SQLException,public java.sql.Statement createStatement() throws java.sql.SQLException,public java.sql.Statement createStatement(int, int) throws java.sql.SQLException,public java.sql.Statement createStatement(int, int, int) throws java.sql.SQLException,public java.sql.Struct createStruct(java.lang.String, java.lang.Object[]) throws java.sql.SQLException,public boolean getAutoCommit() throws java.sql.SQLException,public java.lang.String getCatalog() throws java.sql.SQLException,public java.lang.String getClientInfo(java.lang.String) throws java.sql.SQLException,public java.util.Properties getClientInfo() throws java.sql.SQLException,public int getHoldability() throws java.sql.SQLException,public java.sql.DatabaseMetaData getMetaData() throws java.sql.SQLException,public int getNetworkTimeout() throws java.sql.SQLException,public java.lang.String getSchema() throws java.sql.SQLException,public int getTransactionIsolation() throws java.sql.SQLException,public Map<java.lang.String,Class<?>> getTypeMap() throws java.sql.SQLException,public java.sql.SQLWarning getWarnings() throws java.sql.SQLException,public boolean isClosed() throws java.sql.SQLException,public boolean isReadOnly() throws java.sql.SQLException,public boolean isValid(int) throws java.sql.SQLException,public boolean isWrapperFor(Class<?>) throws java.sql.SQLException,public java.lang.String nativeSQL(java.lang.String) throws java.sql.SQLException,public java.sql.CallableStatement prepareCall(java.lang.String) throws java.sql.SQLException,public java.sql.CallableStatement prepareCall(java.lang.String, int, int) throws java.sql.SQLException,public java.sql.CallableStatement prepareCall(java.lang.String, int, int, int) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String, int, int) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String, int, int, int) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String, int) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String, int[]) throws java.sql.SQLException,public java.sql.PreparedStatement prepareStatement(java.lang.String, java.lang.String[]) throws java.sql.SQLException,public void releaseSavepoint(java.sql.Savepoint) throws java.sql.SQLException,public void rollback() throws java.sql.SQLException,public void rollback(java.sql.Savepoint) throws java.sql.SQLException,public void setAutoCommit(boolean) throws java.sql.SQLException,public void setCatalog(java.lang.String) throws java.sql.SQLException,public void setClientInfo(java.lang.String, java.lang.String) throws java.sql.SQLClientInfoException,public void setClientInfo(java.util.Properties) throws java.sql.SQLClientInfoException,public void setHoldability(int) throws java.sql.SQLException,public void setNetworkTimeout(java.util.concurrent.Executor, int) throws java.sql.SQLException,public void setReadOnly(boolean) throws java.sql.SQLException,public java.sql.Savepoint setSavepoint() throws java.sql.SQLException,public java.sql.Savepoint setSavepoint(java.lang.String) throws java.sql.SQLException,public void setSchema(java.lang.String) throws java.sql.SQLException,public void setTransactionIsolation(int) throws java.sql.SQLException,public void setTypeMap(Map<java.lang.String,Class<?>>) throws java.sql.SQLException,public T unwrap(Class<T>) throws java.sql.SQLException<variables>protected java.sql.Connection connection
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/Channel.java
|
Channel
|
run
|
class Channel<T extends Packet> {
private static final Logger Log = LoggerFactory.getLogger(Channel.class);
private String name;
private ChannelHandler<T> channelHandler;
ThreadPoolExecutor executor;
/**
* Creates a new channel. The channel should be registered after it's created.
*
* @param name the name of the channel.
* @param channelHandler the handler for this channel.
*/
public Channel(String name, ChannelHandler<T> channelHandler) {
this.name = name;
this.channelHandler = channelHandler;
executor = new ThreadPoolExecutor(1, 8, 15, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("Channel-" + name + "-", Executors.defaultThreadFactory(), false, Thread.NORM_PRIORITY));
}
/**
* Returns the name of the channel.
*
* @return the name of the channel.
*/
public String getName() {
return name;
}
/**
* Enqueus a message to be handled by this channel. After the ChannelHandler is done
* processing the message, it will be sent to the next channel. Messages with a higher
* priority will be handled first.
*
* @param packet an XMPP packet to add to the channel for processing.
*/
public void add( final T packet )
{
Runnable r = new Runnable()
{
@Override
public void run()
{<FILL_FUNCTION_BODY>}
};
executor.execute(r);
}
/**
* Returns true if the channel is currently running. The channel can be started and
* stopped by calling the start() and stop() methods.
*
* @return true if the channel is running.
*/
public boolean isRunning() {
return !executor.isShutdown();
}
/**
* Starts the channel, which means that worker threads will start processing messages
* from the queue. If the server isn't running, messages can still be enqueued.
*/
public void start() {
}
/**
* Stops the channel, which means that worker threads will stop processing messages from
* the queue. If the server isn't running, messages can still be enqueued.
*/
public synchronized void stop() {
executor.shutdown();
}
/**
* Returns the number of currently active worker threads in the channel. This value
* will always fall in between the min a max thread count.
*
* @return the current number of worker threads.
*/
public int getThreadCount() {
return executor.getPoolSize();
}
/**
* Returns the min number of threads the channel will use for processing messages.
* The channel will automatically de-allocate worker threads as the queue load shrinks,
* down to the defined minimum. This lets the channel consume fewer resources when load
* is low.
*
* @return the min number of threads that can be used by the channel.
*/
public int getMinThreadCount() {
return executor.getCorePoolSize();
}
/**
* Sets the min number of threads the channel will use for processing messages.
* The channel will automatically de-allocate worker threads as the queue load shrinks,
* down to the defined minimum. This lets the channel consume fewer resources when load
* is low.
*
* @param minThreadCount the min number of threads that can be used by the channel.
*/
public void setMinThreadCount(int minThreadCount) {
executor.setCorePoolSize(minThreadCount);
}
/**
* Returns the max number of threads the channel will use for processing messages. The
* channel will automatically allocate new worker threads as the queue load grows, up to the
* defined maximum. This lets the channel meet higher concurrency needs, but prevents too
* many threads from being allocated, which decreases overall system performance.
*
* @return the max number of threads that can be used by the channel.
*/
public int getMaxThreadCount() {
return executor.getMaximumPoolSize();
}
/**
* Sets the max number of threads the channel will use for processing messages. The channel
* will automatically allocate new worker threads as the queue size grows, up to the defined
* maximum. This lets the channel meet higher concurrency needs, but prevents too many threads
* from being allocated, which decreases overall system performance.
*
* @param maxThreadCount the max number of threads that can be used by the channel.
*/
public void setMaxThreadCount(int maxThreadCount) {
executor.setMaximumPoolSize(maxThreadCount);
}
/**
* Returns the current number of ChannelMessage objects waiting to be processed by
* the channel.
*
* @return the current number of elements in the processing queue.
*/
public int getQueueSize() {
return executor.getQueue().size();
}
}
|
try
{
channelHandler.process( packet );
}
catch ( Exception e )
{
Log.error( LocaleUtils.getLocalizedString( "admin.error" ), e );
try
{
Session session = SessionManager.getInstance().getSession( packet.getFrom() );
if ( session != null )
{
Log.debug( "Closing session of '{}': {}", packet.getFrom(), session );
session.close();
}
}
catch ( Exception e1 )
{
Log.error( "Unexpected exception while trying to close session of '{}'.", packet.getFrom(), e1 );
}
}
| 1,263
| 173
| 1,436
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/LocalSessionManager.java
|
ServerCleanupTask
|
run
|
class ServerCleanupTask extends TimerTask {
/**
* Close incoming server sessions that have been idle for a long time.
*/
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
// Do nothing if this feature is disabled
int idleTime = SessionManager.getInstance().getServerSessionIdleTime();
if (idleTime == -1) {
return;
}
final long deadline = System.currentTimeMillis() - idleTime;
for (LocalIncomingServerSession session : incomingServerSessions.values()) {
try {
if (session.getLastActiveDate().getTime() < deadline) {
Log.debug( "ServerCleanupTask is closing an incoming server session that has been idle for a long time. Last active: {}. Session to be closed: {}", session.getLastActiveDate(), session );
session.close();
}
}
catch (Throwable e) {
Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
| 59
| 203
| 262
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/PrivateStorage.java
|
PrivateStorage
|
add
|
class PrivateStorage extends BasicModule {
private static final Logger Log = LoggerFactory.getLogger(PrivateStorage.class);
/**
* PubSub 7.1.5 specificy Publishing Options that are applicable to private data storage (as described in XEP-0223).
*/
private static final DataForm PRIVATE_DATA_PUBLISHING_OPTIONS;
static {
PRIVATE_DATA_PUBLISHING_OPTIONS = new DataForm( DataForm.Type.submit );
PRIVATE_DATA_PUBLISHING_OPTIONS.addField( "FORM_TYPE", null, FormField.Type.hidden ).addValue( "http://jabber.org/protocol/pubsub#publish-options" );
PRIVATE_DATA_PUBLISHING_OPTIONS.addField( "pubsub#persist_items", null, null ).addValue( "true" );
PRIVATE_DATA_PUBLISHING_OPTIONS.addField( "pubsub#access_model", null, null ).addValue( "whitelist" );
}
private boolean enabled = JiveGlobals.getBooleanProperty("xmpp.privateStorageEnabled", true);
/**
* Constructs a new PrivateStore instance.
*/
public PrivateStorage() {
super("Private user data storage");
}
/**
* Returns true if private storage is enabled.
*
* @return true if private storage is enabled.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Sets whether private storage is enabled.
*
* @param enabled true if this private store is enabled.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
JiveGlobals.setProperty("xmpp.privateStorageEnabled", Boolean.toString(enabled));
}
/**
* Stores private data. If the name and namespace of the element matches another
* stored private data XML document, then replace it with the new one.
*
* @param data the data to store (XML element)
* @param username the username of the account where private data is being stored
*/
public void add(String username, Element data) {<FILL_FUNCTION_BODY>}
/**
* Returns the data stored under a key corresponding to the name and namespace
* of the given element. The Element must be in the form:<p>
*
* <code><name xmlns='namespace'/></code><p>
*
* If no data is currently stored under the given key, an empty element will be
* returned.
*
* @param data an XML document who's element name and namespace is used to
* match previously stored private data.
* @param username the username of the account where private data is being stored.
* @return the data stored under the given key or the data element.
*/
public Element get(String username, Element data)
{
if (enabled)
{
final PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
final PEPService pepService = serviceMgr.getPEPService( XMPPServer.getInstance().createJID( username, null ) );
if ( pepService != null )
{
final Node node = pepService.getNode( data.getNamespaceURI() );
if ( node != null )
{
final PublishedItem item = node.getPublishedItem( "current" );
if ( item != null )
{
data.clearContent();
data = item.getPayload();
}
}
}
}
return data;
}
}
|
if (!enabled)
{
return;
}
final JID owner = XMPPServer.getInstance().createJID( username, null );
final PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
PEPService pepService = serviceMgr.getPEPService( owner );
if ( pepService == null )
{
pepService = serviceMgr.create( owner );
}
Node node = pepService.getNode( data.getNamespaceURI() );
if ( node == null )
{
PubSubEngine.CreateNodeResponse response = PubSubEngine.createNodeHelper( pepService, owner, pepService.getDefaultNodeConfiguration( true ).getConfigurationForm(null).getElement(), data.getNamespaceURI(), PRIVATE_DATA_PUBLISHING_OPTIONS );
node = response.newNode;
if ( node == null )
{
Log.error( "Unable to create new PEP node, to be used to store private data. Error condition: {}", response.creationStatus.toXMPP() );
return;
}
}
if (!(node instanceof LeafNode))
{
Log.error( "Unable to store private data into a PEP node. The node that is available is not a leaf node." );
return;
}
data.detach();
final Element item = DocumentHelper.createElement( "item" );
item.addAttribute( "id", "current" );
item.add( data );
((LeafNode) node).publishItems( owner, Collections.singletonList( item ) );
| 921
| 406
| 1,327
|
<methods>public void <init>(java.lang.String) ,public void destroy() ,public java.lang.String getName() ,public void initialize(org.jivesoftware.openfire.XMPPServer) ,public void start() throws java.lang.IllegalStateException,public void stop() <variables>private java.lang.String name
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/SessionPacketRouter.java
|
SessionPacketRouter
|
route
|
class SessionPacketRouter implements PacketRouter {
protected LocalClientSession session;
private PacketRouter router;
private boolean skipJIDValidation = false;
public SessionPacketRouter(LocalClientSession session) {
this.session = session;
router = XMPPServer.getInstance().getPacketRouter();
}
/**
* Sets if TO addresses of Elements being routed should be validated. Doing stringprep operations
* is very expensive and sometimes we already validated the TO address so there is no need to
* validate again the address. For instance, when using Connection Managers the validation
* is done by the Connection Manager so we can just trust the TO address. On the other hand,
* the FROM address is set by the server so there is no need to validate it.<p>
*
* By default validation is enabled.
*
* @param skipJIDValidation true if validation of TO address is enabled.
*/
public void setSkipJIDValidation(boolean skipJIDValidation) {
this.skipJIDValidation = skipJIDValidation;
}
public void route(Element wrappedElement)
throws UnknownStanzaException {<FILL_FUNCTION_BODY>}
private IQ getIQ(Element doc) {
Element query = doc.element("query");
if (query != null && "jabber:iq:roster".equals(query.getNamespaceURI())) {
return new Roster(doc);
}
else {
return new IQ(doc, skipJIDValidation);
}
}
@Override
public void route(Packet packet) {
// Security: Don't allow users to send packets on behalf of other users
packet.setFrom(session.getAddress());
if(packet instanceof IQ) {
route((IQ)packet);
}
else if(packet instanceof Message) {
route((Message)packet);
}
else if(packet instanceof Presence) {
route((Presence)packet);
}
}
@Override
public void route(IQ packet) {
packet.setFrom(session.getAddress());
router.route(packet);
session.incrementClientPacketCount();
}
@Override
public void route(Message packet) {
packet.setFrom(session.getAddress());
router.route(packet);
session.incrementClientPacketCount();
}
@Override
public void route(Presence packet) {
packet.setFrom(session.getAddress());
router.route(packet);
session.incrementClientPacketCount();
}
/**
* Determines if a peer that is sending a stanza in violation of RFC 6120, section 7.1:
*
* <blockquote>If, before completing the resource binding step, the client attempts to send an XML
* stanza to an entity other than the server itself or the client's account, the server MUST NOT process the
* stanza and MUST close the stream with a <not-authorized/> stream error.</blockquote>
*
* When this method returns 'true', the stream should be closed. This method does not close the stream.
*
* @param session The session over which the stanza is sent to Openfire.
* @param stanza The stanza that is sent to Openfire.
* @return true if the peer is in violation (and the stream should be closed), otherwise false.
* @see <a href="https://www.rfc-editor.org/rfc/rfc6120#section-7.1">RFC 6120, section 7.1</a>
* @see <a href="https://igniterealtime.atlassian.net/jira/software/c/projects/OF/issues/OF-2565">issue OF-2565</a>
*/
public static boolean isInvalidStanzaSentPriorToResourceBinding(final Packet stanza, final ClientSession session)
{
// Openfire sets 'authenticated' only after resource binding.
if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
return false;
}
// Beware, the 'to' address in the stanza will have been overwritten by the
final JID intendedRecipient = stanza.getTo();
final JID serverDomain = new JID(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
// If there's no 'to' address, then the stanza is implicitly addressed at the user itself.
if (intendedRecipient == null) {
return false;
}
// TODO: after authentication (but prior to resource binding), it should be possible to verify that the
// intended recipient's bare JID corresponds with the authorized user. Openfire currently does not have an API
// that can be used to obtain the authorized username, prior to resource binding.
if (intendedRecipient.equals(serverDomain)) {
return false;
}
return true;
}
}
|
String tag = wrappedElement.getName();
if ("auth".equals(tag) || "response".equals(tag)) {
SASLAuthentication.handle(session, wrappedElement);
}
else if ("iq".equals(tag)) {
route(getIQ(wrappedElement));
}
else if ("message".equals(tag)) {
route(new Message(wrappedElement, skipJIDValidation));
}
else if ("presence".equals(tag)) {
route(new Presence(wrappedElement, skipJIDValidation));
}
else {
throw new UnknownStanzaException();
}
| 1,289
| 158
| 1,447
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/SessionResultFilter.java
|
SessionComparator
|
equals
|
class SessionComparator implements Comparator<ClientSession> {
@Override
public int compare(ClientSession lhs, ClientSession rhs) {
int comparison;
switch (sortField) {
case SessionResultFilter.SORT_CREATION_DATE:
comparison = lhs.getCreationDate().compareTo(rhs.getCreationDate());
break;
case SessionResultFilter.SORT_LAST_ACTIVITY_DATE:
comparison = lhs.getLastActiveDate().compareTo(rhs.getCreationDate());
break;
case SessionResultFilter.SORT_NUM_CLIENT_PACKETS:
comparison = (int)(lhs.getNumClientPackets() - rhs.getNumClientPackets());
break;
case SessionResultFilter.SORT_NUM_SERVER_PACKETS:
comparison = (int)(lhs.getNumServerPackets() - rhs.getNumServerPackets());
break;
case SessionResultFilter.SORT_USER:
// sort first by name, then by resource
String lUsername = lhs.isAnonymousUser() ? "" : lhs.getAddress().getNode();
String rUsername = rhs.isAnonymousUser() ? "" : rhs.getAddress().getNode();
comparison = compareString(lUsername, rUsername);
if (comparison == 0) {
comparison = compareString(lhs.getAddress().getResource(),
rhs.getAddress().getResource());
}
break;
default:
comparison = 0;
}
if (sortOrder == SessionResultFilter.DESCENDING) {
comparison *= -1; // Naturally ascending, flip sign if descending
}
return comparison;
}
private int compareString(String lhs, String rhs) {
if (lhs == null) {
lhs = "";
}
if (rhs == null) {
rhs = "";
}
return lhs.compareTo(rhs);
}
}
/**
* Rounds the given date down to the nearest specified second. The following
* table shows sample input and expected output values: (Note, only
* the time portion of the date is shown for brevity)
*
* <table border="1">
* <caption>Rounding examples</caption>
* <tr><th>Date</th><th>Seconds</th><th>Result</th></tr>
* <tr><td>1:37.48</td><td>5</td><td>1:37.45</td></tr>
* <tr><td>1:37.48</td><td>10</td><td>1:37.40</td></tr>
* <tr><td>1:37.48</td><td>30</td><td>1:37.30</td></tr>
* <tr><td>1:37.48</td><td>60</td><td>1:37.00</td></tr>
* <tr><td>1:37.48</td><td>120</td><td>1:36.00</td></tr>
* </table>
*
* <p>This method is useful when calculating the last post in
* a forum or the number of new messages from a given date. Using a rounded
* date allows Jive to internally cache the results of the date query.
* Here's an example that shows the last posted message in a forum accurate
* to the last 60 seconds:</p>
*
* <pre>
* SessionResultFilter filter = new SessionResultFilter();
* filter.setSortOrder(SessionResultFilter.DESCENDING);
* filter.setSortField(JiveGlobals.SORT_CREATION_DATE);
* <b>filter.setCreationDateRangeMin(SessionResultFilter.roundDate(forum.getModificationDate(), 60));</b>
* filter.setNumResults(1);
* Iterator messages = forum.messages(filter);
* ForumMessage lastPost = (ForumMessage)messages.next();
* </pre>
*
* @param date the {@code Date} we want to round.
* @param seconds the number of seconds we want to round the date to.
* @return the given date, rounded down to the nearest specified number of seconds.
*/
public static Date roundDate(Date date, int seconds) {
return new Date(roundDate(date.getTime(), seconds));
}
/**
* Rounds the given date down to the nearest specified second.
*
* @param date the date (as a long) that we want to round.
* @param seconds the number of seconds we want to round the date to.
* @return the given date (as a long), rounded down to the nearest
* specified number of seconds.
*/
public static long roundDate(long date, int seconds) {
return date - (date % (1000 * seconds));
}
@Override
public boolean equals(Object object) {<FILL_FUNCTION_BODY>
|
if (this == object) {
return true;
}
if (object != null && object instanceof SessionResultFilter) {
SessionResultFilter o = (SessionResultFilter)object;
if (sortField != o.sortField) {
return false;
}
if (sortOrder != o.sortOrder) {
return false;
}
if (numResults != o.numResults) {
return false;
}
if (!compare(username, o.username)) {
return false;
}
if (!compare(creationDateRangeMin, o.creationDateRangeMin)) {
return false;
}
if (!compare(creationDateRangeMax, o.creationDateRangeMax)) {
return false;
}
if (!compare(lastActivityDateRangeMin, o.lastActivityDateRangeMin)) {
return false;
}
if (!compare(lastActivityDateRangeMax, o.lastActivityDateRangeMax)) {
return false;
}
// All checks passed, so equal.
return true;
}
else {
return false;
}
| 1,319
| 284
| 1,603
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/XMPPContextListener.java
|
XMPPContextListener
|
contextDestroyed
|
class XMPPContextListener implements ServletContextListener {
protected String XMPP_KEY = "XMPP_SERVER";
@Override
public void contextInitialized(ServletContextEvent event) {
if (XMPPServer.getInstance() != null) {
// Running in standalone mode so do nothing
return;
}
XMPPServer server = new XMPPServer();
event.getServletContext().setAttribute(XMPP_KEY, server);
}
@Override
public void contextDestroyed(ServletContextEvent event) {<FILL_FUNCTION_BODY>}
}
|
XMPPServer server = (XMPPServer) event.getServletContext().getAttribute(XMPP_KEY);
if (null != server) {
server.stop();
}
| 155
| 51
| 206
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/admin/AdminManager.java
|
AdminManagerContainer
|
userDeleting
|
class AdminManagerContainer {
private static AdminManager instance = new AdminManager();
}
/**
* Returns the currently-installed AdminProvider. <b>Warning:</b> in virtually all
* cases the admin provider should not be used directly. Instead, the appropriate
* methods in AdminManager should be called. Direct access to the admin provider is
* only provided for special-case logic.
*
* @return the current AdminProvider.
*/
public static AdminProvider getAdminProvider() {
return AdminManagerContainer.instance.provider;
}
/**
* Returns a singleton instance of AdminManager.
*
* @return a AdminManager instance.
*/
public static AdminManager getInstance() {
return AdminManagerContainer.instance;
}
/* Cache of admin accounts */
private List<JID> adminList;
private static AdminProvider provider;
/**
* Constructs a AdminManager, propery listener, and setting up the provider.
*/
private AdminManager() {
// Load an admin provider.
initProvider(ADMIN_PROVIDER.getValue());
UserEventDispatcher.addListener(new UserEventListener() {
@Override
public void userDeleting(final User user, final Map<String, Object> params) {<FILL_FUNCTION_BODY>
|
// OF-2758: Ensure that if a user is re-created with the same name, they're not automatically an admin.
removeAdminAccount(user.getUsername());
| 341
| 48
| 389
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/admin/DefaultAdminProvider.java
|
DefaultAdminProvider
|
convertXMLToProvider
|
class DefaultAdminProvider implements AdminProvider {
private static final SystemProperty<List<JID>> ADMIN_JIDS = SystemProperty.Builder.ofType(List.class)
.setKey("admin.authorizedJIDs")
.setDefaultValue(Collections.emptyList())
.setSorted(true)
.setDynamic(true)
.addListener(jids -> AdminManager.getInstance().refreshAdminAccounts())
.buildList(JID.class);
private static final Logger Log = LoggerFactory.getLogger(DefaultAdminProvider.class);
/**
* Constructs a new DefaultAdminProvider
*/
public DefaultAdminProvider() {
// Convert old openfire.xml style to new provider style, if necessary.
Log.debug("DefaultAdminProvider: Convert XML to provider.");
convertXMLToProvider();
}
/**
* The default provider retrieves the comma separated list from the system property
* {@code admin.authorizedJIDs}
* @see org.jivesoftware.openfire.admin.AdminProvider#getAdmins()
*/
@Override
public List<JID> getAdmins() {
// Add bare JIDs of users that are admins (may include remote users), primarily used to override/add to list of admin users
final List<JID> adminList = ADMIN_JIDS.getValue();
// Prior to 4.4.0, the return value was mutable. To prevent issues, we'll keep that characteristic.
final List<JID> returnValue = new ArrayList<>();
if (adminList.isEmpty()) {
// Add default admin account when none was specified
returnValue.add( new JID("admin", XMPPServer.getInstance().getServerInfo().getXMPPDomain(), null, true));
} else {
returnValue.addAll( adminList );
}
return returnValue;
}
/**
* The default provider sets a comma separated list as the system property
* {@code admin.authorizedJIDs}
* @see org.jivesoftware.openfire.admin.AdminProvider#setAdmins(java.util.List)
*/
@Override
public void setAdmins(final List<JID> admins) {
ADMIN_JIDS.setValue(admins);
}
/**
* The default provider is not read only
* @see org.jivesoftware.openfire.admin.AdminProvider#isReadOnly()
*/
@Override
public boolean isReadOnly() {
return false;
}
/**
* Converts the old openfire.xml style admin list to use the new provider mechanism.
*/
private void convertXMLToProvider() {<FILL_FUNCTION_BODY>}
}
|
if (JiveGlobals.getXMLProperty("admin.authorizedJIDs") == null &&
JiveGlobals.getXMLProperty("admin.authorizedUsernames") == null &&
JiveGlobals.getXMLProperty("adminConsole.authorizedUsernames") == null) {
// No settings in openfire.xml.
return;
}
final List<JID> adminList = new ArrayList<>();
// Add bare JIDs of users that are admins (may include remote users), primarily used to override/add to list of admin users
String jids = JiveGlobals.getXMLProperty("admin.authorizedJIDs");
jids = (jids == null || jids.trim().length() == 0) ? "" : jids;
StringTokenizer tokenizer = new StringTokenizer(jids, ",");
while (tokenizer.hasMoreTokens()) {
final String jid = tokenizer.nextToken().toLowerCase().trim();
try {
adminList.add(new JID(jid));
}
catch (final IllegalArgumentException e) {
Log.warn("Invalid JID found in authorizedJIDs at openfire.xml: " + jid, e);
}
}
// Add the JIDs of the local users that are admins, primarily used to override/add to list of admin users
String usernames = JiveGlobals.getXMLProperty("admin.authorizedUsernames");
if (usernames == null) {
// Fall back to old method for defining admins (i.e. using adminConsole prefix
usernames = JiveGlobals.getXMLProperty("adminConsole.authorizedUsernames");
}
// Add default of admin user if no other users were listed as admins.
usernames = (usernames == null || usernames.trim().length() == 0) ? (adminList.size() == 0 ? "admin" : "") : usernames;
tokenizer = new StringTokenizer(usernames, ",");
while (tokenizer.hasMoreTokens()) {
final String username = tokenizer.nextToken();
try {
adminList.add(XMPPServer.getInstance().createJID(username.toLowerCase().trim(), null));
}
catch (final IllegalArgumentException e) {
// Ignore usernames that when appended @server.com result in an invalid JID
Log.warn("Invalid username found in authorizedUsernames at openfire.xml: " +
username, e);
}
}
setAdmins(adminList);
// Clear out old XML property settings
JiveGlobals.deleteXMLProperty("admin.authorizedJIDs");
JiveGlobals.deleteXMLProperty("admin.authorizedUsernames");
JiveGlobals.deleteXMLProperty("adminConsole.authorizedUsernames");
| 694
| 710
| 1,404
|
<no_super_class>
|
igniterealtime_Openfire
|
Openfire/xmppserver/src/main/java/org/jivesoftware/openfire/admin/GroupBasedAdminProvider.java
|
GroupBasedAdminProvider
|
getAdmins
|
class GroupBasedAdminProvider implements AdminProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupBasedAdminProvider.class);
private static final SystemProperty<String> GROUP_NAME = SystemProperty.Builder.ofType(String.class)
.setKey("provider.group.groupBasedAdminProvider.groupName")
.setDefaultValue("openfire-administrators")
.setDynamic(true)
.build();
@Override
public List<JID> getAdmins() {<FILL_FUNCTION_BODY>}
@Override
public void setAdmins(List<JID> admins) {
throw new UnsupportedOperationException("The GroupAdminProvider is read only");
}
@Override
public boolean isReadOnly() {
return true;
}
}
|
final String groupName = GROUP_NAME.getValue();
try {
// Note; the list of admins is already cached, so if the list is being refreshed force a cache refresh too
return new ArrayList<>(GroupManager.getInstance().getGroup(groupName, true).getMembers());
} catch (GroupNotFoundException e) {
LOGGER.error(String.format("Unable to retrieve members of group '%s' - assuming no administrators", groupName), e);
return new ArrayList<>();
}
| 204
| 123
| 327
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.