file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
Log4j2Logger.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/logger/Log4j2Logger.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* WandoraLogger.java
*/
package org.wandora.utils.logger;
/**
*
* @author akikivela
*
*/
public class Log4j2Logger {
org.apache.logging.log4j.Logger realLogger = org.apache.logging.log4j.LogManager.getLogger(Log4j2Logger.class);
private Log4j2Logger(Class<?> clazz) {
realLogger = org.apache.logging.log4j.LogManager.getLogger(clazz);
}
public static Log4j2Logger getLogger(Class<?> clazz) {
return new Log4j2Logger(clazz);
}
public void debug(String str) {
realLogger.debug(str);
}
public void info(String str) {
realLogger.info(str);
}
public void warn(String str) {
realLogger.warn(str);
}
public void error(String str) {
realLogger.warn(str);
}
public void writelog(String level, String s) {
if("INF".equalsIgnoreCase(level)) {
info(s);
}
else if("DBG".equalsIgnoreCase(level)) {
debug(s);
}
else if("ERR".equalsIgnoreCase(level)) {
error(s);
}
else {
info(s);
}
}
}
| 1,974 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SystemOutLogger.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/logger/SystemOutLogger.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* SimpleLogger.java
*
* Created on July 8, 2004, 4:37 PM
*/
package org.wandora.utils.logger;
import java.io.PrintStream;
/**
*
* @author olli
*/
public class SystemOutLogger extends Logger {
protected PrintStream stream;
/** Creates a new instance of SimpleLogger */
public SystemOutLogger() {
this(System.out);
}
public SystemOutLogger(PrintStream stream) {
this.stream=stream;
}
public void writelog(String level, String s) {
stream.println(level+" "+s);
}
}
| 1,356 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Logger.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/logger/Logger.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* Logger.java
*
* Created on July 8, 2004, 4:30 PM
*/
package org.wandora.utils.logger;
/**
*
* @author olli, akivela
*/
public abstract class Logger {
private static Logger defaultLogger = new SystemOutLogger();
public abstract void writelog(String level, String s);
public void writelog(String s){
writelog("INF", s);
}
public void writelog(String level, String s, Throwable e){
writelog(level,s+"\n"+getStackTrace(e, true));
}
public void writelog(String level, Throwable e){
writelog(level, getStackTrace(e, true));
}
public static void log(String msg) {
defaultLogger.writelog(msg);
}
public static void setLogger(Logger logger){
defaultLogger=logger;
}
public static Logger getLogger() {
return defaultLogger;
}
// ---------------------------------------------
public String getStackTrace(Throwable e, boolean cause){
java.io.StringWriter writer=new java.io.StringWriter();
e.printStackTrace(new java.io.PrintWriter(writer));
if(cause && e.getCause()!=null){
writer.write("\n");
writer.write("Cause:\n");
writer.write(getStackTrace(e.getCause(),true));
}
return writer.toString();
}
}
| 2,162 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableSorter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/TableSorter.java | package org.wandora.utils.swing;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
/*
* This class is from Sun's table Java tutorial
* Original file: http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java
*
* To use, do something like this:
*
* TableSorter sorter = new TableSorter(new MyTableModel());
* JTable table = new JTable(sorter);
* sorter.setTableHeader(table.getTableHeader());
*
* ojl: Added custom mouse listener support.
*
*/
/**
* TableSorter is a decorator for TableModels; adding sorting
* functionality to a supplied TableModel. TableSorter does
* not store or copy the data in its TableModel; instead it maintains
* a map from the row indexes of the view to the row indexes of the
* model. As requests are made of the sorter (like getValueAt(row, col))
* they are passed to the underlying model after the row numbers
* have been translated via the internal mapping array. This way,
* the TableSorter appears to hold another copy of the table
* with the rows in a different order.
* <p/>
* TableSorter registers itself as a listener to the underlying model,
* just as the JTable itself would. Events recieved from the model
* are examined, sometimes manipulated (typically widened), and then
* passed on to the TableSorter's listeners (typically the JTable).
* If a change to the model has invalidated the order of TableSorter's
* rows, a note of this is made and the sorter will resort the
* rows the next time a value is requested.
* <p/>
* When the tableHeader property is set, either by using the
* setTableHeader() method or the two argument constructor, the
* table header may be used as a complete UI for TableSorter.
* The default renderer of the tableHeader is decorated with a renderer
* that indicates the sorting status of each column. In addition,
* a mouse listener is installed with the following behavior:
* <ul>
* <li>
* Mouse-click: Clears the sorting status of all other columns
* and advances the sorting status of that column through three
* values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
* NOT_SORTED again).
* <li>
* SHIFT-mouse-click: Clears the sorting status of all other columns
* and cycles the sorting status of the column through the same
* three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
* <li>
* CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
* that the changes to the column do not cancel the statuses of columns
* that are already sorting - giving a way to initiate a compound
* sort.
* </ul>
* <p/>
* This is a long overdue rewrite of a class of the same name that
* first appeared in the swing table demos in 1997.
*
* @author Philip Milne
* @author Brendon McLean
* @author Dan van Enckevort
* @author Parwinder Sekhon
* @version 2.0 02/27/04
*/
public class TableSorter extends AbstractTableModel {
private static final long serialVersionUID = 1L;
protected TableModel tableModel;
public static final int DESCENDING = -1;
public static final int NOT_SORTED = 0;
public static final int ASCENDING = 1;
private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
public static final Comparator COMPARABLE_COMAPRATOR = new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) o1).compareTo(o2);
}
};
public static final Comparator LEXICAL_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
if(o1==null && o2!=null) return -1;
else if(o1!=null && o2==null) return 1;
else if(o1==null && o2==null) return 0;
else return o1.toString().compareTo(o2.toString());
}
};
private Row[] viewToModel;
private int[] modelToView;
private JTableHeader tableHeader;
private MouseListener mouseListener;
private TableModelListener tableModelListener;
private Map columnComparators = new HashMap();
private List sortingColumns = new ArrayList();
private Vector mouseListeners;
public TableSorter() {
this.mouseListener = new MouseHandler();
this.tableModelListener = new TableModelHandler();
mouseListeners=new Vector();
}
public TableSorter(TableModel tableModel) {
this();
setTableModel(tableModel);
}
public TableSorter(TableModel tableModel, JTableHeader tableHeader) {
this();
setTableHeader(tableHeader);
setTableModel(tableModel);
}
public void addHeaderMouseListener(MouseListener l){
synchronized(mouseListeners){
mouseListeners.add(l);
}
}
public void removeHeaderMouseListener(MouseListener l){
synchronized(mouseListeners){
mouseListeners.remove(l);
}
}
private void clearSortingState() {
viewToModel = null;
modelToView = null;
}
public TableModel getTableModel() {
return tableModel;
}
public void setTableModel(TableModel tableModel) {
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
clearSortingState();
fireTableStructureChanged();
}
public JTableHeader getTableHeader() {
return tableHeader;
}
public void setTableHeader(JTableHeader tableHeader) {
if (this.tableHeader != null) {
this.tableHeader.removeMouseListener(mouseListener);
TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
if (defaultRenderer instanceof SortableHeaderRenderer) {
this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
}
}
this.tableHeader = tableHeader;
if (this.tableHeader != null) {
this.tableHeader.addMouseListener(mouseListener);
this.tableHeader.setDefaultRenderer(
new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer()));
}
}
public boolean isSorting() {
return sortingColumns.size() != 0;
}
private Directive getDirective(int column) {
for (int i = 0; i < sortingColumns.size(); i++) {
Directive directive = (Directive)sortingColumns.get(i);
if (directive.column == column) {
return directive;
}
}
return EMPTY_DIRECTIVE;
}
public int getSortingStatus(int column) {
return getDirective(column).direction;
}
private void sortingStatusChanged() {
clearSortingState();
fireTableDataChanged();
if (tableHeader != null) {
tableHeader.repaint();
}
}
public void setSortingStatus(int column, int status) {
Directive directive = getDirective(column);
if (directive != EMPTY_DIRECTIVE) {
sortingColumns.remove(directive);
}
if (status != NOT_SORTED) {
sortingColumns.add(new Directive(column, status));
}
sortingStatusChanged();
}
protected Icon getHeaderRendererIcon(int column, int size) {
Directive directive = getDirective(column);
if (directive == EMPTY_DIRECTIVE) {
return null;
}
return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
}
private void cancelSorting() {
sortingColumns.clear();
sortingStatusChanged();
}
public void setColumnComparator(Class type, Comparator comparator) {
if (comparator == null) {
columnComparators.remove(type);
} else {
columnComparators.put(type, comparator);
}
}
protected Comparator getComparator(int column) {
Class columnType = tableModel.getColumnClass(column);
Comparator comparator = (Comparator) columnComparators.get(columnType);
if (comparator != null) {
return comparator;
}
if (Comparable.class.isAssignableFrom(columnType)) {
return COMPARABLE_COMAPRATOR;
}
return LEXICAL_COMPARATOR;
}
private Row[] getViewToModel() {
if (viewToModel == null) {
int tableModelRowCount = tableModel.getRowCount();
viewToModel = new Row[tableModelRowCount];
for (int row = 0; row < tableModelRowCount; row++) {
viewToModel[row] = new Row(row);
}
if (isSorting()) {
Arrays.sort(viewToModel);
}
}
return viewToModel;
}
public int modelIndex(int viewIndex) {
if(viewIndex > -1) return getViewToModel()[viewIndex].modelIndex;
else return -1;
}
public int viewIndex(int modelIndex){
if(modelIndex > -1) return getModelToView()[modelIndex];
return -1;
}
private int[] getModelToView() {
if (modelToView == null) {
int n = getViewToModel().length;
modelToView = new int[n];
for (int i = 0; i < n; i++) {
modelToView[modelIndex(i)] = i;
}
}
return modelToView;
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : tableModel.getRowCount();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(modelIndex(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(modelIndex(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, modelIndex(row), column);
}
// Helper classes
private class Row implements Comparable {
private int modelIndex;
public Row(int index) {
this.modelIndex = index;
}
public int compareTo(Object o) {
int row1 = modelIndex;
int row2 = ((Row) o).modelIndex;
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
Directive directive = (Directive) it.next();
int column = directive.column;
Object o1 = tableModel.getValueAt(row1, column);
Object o2 = tableModel.getValueAt(row2, column);
int comparison = 0;
// Define null less than everything, except null.
if (o1 == null && o2 == null) {
comparison = 0;
} else if (o1 == null) {
comparison = -1;
} else if (o2 == null) {
comparison = 1;
} else {
comparison = getComparator(column).compare(o1, o2);
}
if (comparison != 0) {
return directive.direction == DESCENDING ? -comparison : comparison;
}
}
return 0;
}
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not sorting by anything, just pass the event along.
if (!isSorting()) {
clearSortingState();
fireTableChanged(e);
return;
}
// If the table structure has changed, cancel the sorting; the
// sorting columns may have been either moved or deleted from
// the model.
if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
cancelSorting();
fireTableChanged(e);
return;
}
// We can map a cell event through to the view without widening
// when the following conditions apply:
//
// a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
// b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
// c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
// d) a reverse lookup will not trigger a sort (modelToView != null)
//
// Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
//
// The last check, for (modelToView != null) is to see if modelToView
// is already allocated. If we don't do this check; sorting can become
// a performance bottleneck for applications where cells
// change rapidly in different parts of the table. If cells
// change alternately in the sorting column and then outside of
// it this class can end up re-sorting on alternate cell updates -
// which can be a performance problem for large tables. The last
// clause avoids this problem.
int column = e.getColumn();
if (e.getFirstRow() == e.getLastRow()
&& column != TableModelEvent.ALL_COLUMNS
&& getSortingStatus(column) == NOT_SORTED
&& modelToView != null) {
int viewIndex = getModelToView()[e.getFirstRow()];
fireTableChanged(new TableModelEvent(TableSorter.this,
viewIndex, viewIndex,
column, e.getType()));
return;
}
// Something has happened to the data that may have invalidated the row order.
clearSortingState();
fireTableDataChanged();
return;
}
}
private class MouseHandler extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
synchronized(mouseListeners){
Iterator iter=mouseListeners.iterator();
while(iter.hasNext()){
MouseListener l=(MouseListener)iter.next();
l.mouseClicked(e);
}
}
if(e.isConsumed()) return;
JTableHeader h = (JTableHeader) e.getSource();
TableColumnModel columnModel = h.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = columnModel.getColumn(viewColumn).getModelIndex();
if (column != -1) {
int status = getSortingStatus(column);
if (!e.isControlDown()) {
cancelSorting();
}
// Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
// {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
status = status + (e.isShiftDown() ? -1 : 1);
status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
setSortingStatus(column, status);
}
}
public void mouseExited(MouseEvent e) {
synchronized(mouseListeners){
Iterator iter=mouseListeners.iterator();
while(iter.hasNext()){
MouseListener l=(MouseListener)iter.next();
l.mouseExited(e);
}
}
}
public void mousePressed(MouseEvent e) {
synchronized(mouseListeners){
Iterator iter=mouseListeners.iterator();
while(iter.hasNext()){
MouseListener l=(MouseListener)iter.next();
l.mousePressed(e);
}
}
}
}
private static class Arrow implements Icon {
private boolean descending;
private int size;
private int priority;
public Arrow(boolean descending, int size, int priority) {
this.descending = descending;
this.size = size;
this.priority = priority;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Color color = c == null ? Color.GRAY : c.getBackground();
// In a compound sort, make each succesive triangle 20%
// smaller than the previous one.
int dx = (int)(size/2*Math.pow(0.8, priority));
int dy = descending ? dx : -dx;
// Align icon (roughly) with font baseline.
y = y + 5*size/6 + (descending ? -dy : 0);
int shift = descending ? 1 : -1;
g.translate(x, y);
// Right diagonal.
g.setColor(color.darker());
g.drawLine(dx / 2, dy, 0, 0);
g.drawLine(dx / 2, dy + shift, 0, shift);
// Left diagonal.
g.setColor(color.brighter());
g.drawLine(dx / 2, dy, dx, 0);
g.drawLine(dx / 2, dy + shift, dx, shift);
// Horizontal line.
if (descending) {
g.setColor(color.darker().darker());
} else {
g.setColor(color.brighter().brighter());
}
g.drawLine(dx, 0, 0, 0);
g.setColor(color);
g.translate(-x, -y);
}
public int getIconWidth() {
return size;
}
public int getIconHeight() {
return size;
}
}
private class SortableHeaderRenderer implements TableCellRenderer {
private TableCellRenderer tableCellRenderer;
public SortableHeaderRenderer(TableCellRenderer tableCellRenderer) {
this.tableCellRenderer = tableCellRenderer;
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = tableCellRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
if (c instanceof JLabel) {
JLabel l = (JLabel) c;
l.setHorizontalTextPosition(JLabel.LEFT);
int modelColumn = table.convertColumnIndexToModel(column);
l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
}
return c;
}
}
private static class Directive {
private int column;
private int direction;
public Directive(int column, int direction) {
this.column = column;
this.direction = direction;
}
}
}
| 20,206 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
InputDialogWithHistory.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/InputDialogWithHistory.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* InputDialogWithHistory.java
*
* Created on 25. maaliskuuta 2005, 15:40
*/
package org.wandora.utils.swing;
import java.awt.Font;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleComboBox;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.utils.Textbox;
/**
*
* @author akivela
*/
public class InputDialogWithHistory extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
public static int HISTORYMAXSIZE = 40;
public java.awt.Frame parent = null;
public boolean accepted = true;
public static Font buttonLabelFont = new Font("SansSerif", Font.PLAIN, 11);
public static Font labelFont = new Font("SansSerif", Font.PLAIN, 12);
/** Creates new form InputDialogWithHistory */
public InputDialogWithHistory(java.awt.Frame parent, boolean modal, String label, String title) {
super(parent, modal);
initComponents();
this.setTitle(title);
this.label.setText(label);
this.parent = parent;
this.options.addItem("");
centerWindow();
}
public String showDialog() {
String sel = "";
try {
accepted = false;
this.options.setSelectedIndex(0);
centerWindow();
this.setVisible(true);
sel = (String) this.options.getSelectedItem();
sel = Textbox.trimExtraSpaces(sel);
if(accepted && sel.length() > 0) options.addItem(sel);
if(this.options.getItemCount() > HISTORYMAXSIZE) this.options.removeItemAt(1);
}
catch (Exception e) {
e.printStackTrace();
}
return sel;
}
public void centerWindow() {
if(parent != null) {
this.setLocation(parent.getX()+parent.getWidth()/2-this.getWidth()/2,parent.getY()+parent.getHeight()/2-this.getHeight()/2);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
label = new SimpleLabel();
options = new SimpleComboBox();
jPanel2 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
okButton = new SimpleButton();
cancelButton = new SimpleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jPanel1.setLayout(new java.awt.GridBagLayout());
label.setFont(labelFont);
label.setText("Input");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 10, 4, 10);
jPanel1.add(label, gridBagConstraints);
options.setEditable(true);
options.setFont(labelFont);
options.setMinimumSize(new java.awt.Dimension(400, 20));
options.setPreferredSize(new java.awt.Dimension(400, 20));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
jPanel1.add(options, gridBagConstraints);
jPanel2.setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel2.add(jPanel3, gridBagConstraints);
okButton.setFont(buttonLabelFont);
okButton.setText("OK");
okButton.setMinimumSize(new java.awt.Dimension(80, 23));
okButton.setPreferredSize(new java.awt.Dimension(80, 23));
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
jPanel2.add(okButton, gridBagConstraints);
cancelButton.setFont(buttonLabelFont);
cancelButton.setText("Cancel");
cancelButton.setMinimumSize(new java.awt.Dimension(80, 23));
cancelButton.setPreferredSize(new java.awt.Dimension(80, 23));
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
jPanel2.add(cancelButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 8, 10);
jPanel1.add(jPanel2, gridBagConstraints);
getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
accepted = false;
this.setVisible(false);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
accepted = true;
this.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JLabel label;
private javax.swing.JButton okButton;
private javax.swing.JComboBox options;
// End of variables declaration//GEN-END:variables
}
| 7,449 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SwingTools.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/SwingTools.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* SwingTools.java
*
* Created on 18. toukokuuta 2005, 16:36
*
* Copyright 2004-2005 Grip Studios Interactive Oy (office@gripstudios.com)
* Created by Olli Lyytinen, AKi Kivela
*/
package org.wandora.utils.swing;
import java.awt.EventQueue;
import javax.swing.SwingUtilities;
import org.wandora.utils.Semaphore;
/**
*
* @author olli
*/
public class SwingTools {
/**
* Use this to debug access to Swing objects outside event dispatch thread.
*/
public static void debugCheckEventThread(){
if(!EventQueue.isDispatchThread()){
System.out.println("WARNING: not event dispatch thread");
try{
throw new Exception("Not event dispatch thread");
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* Runs the given Runnable immediately if called from event dispatch thread
* or at some later time inside event dispatch thread otherwise.
*/
public static void swingOperation(Runnable run){
if(!EventQueue.isDispatchThread()) SwingUtilities.invokeLater(run);
else run.run();
}
/**
* Runs the given Runnable immediately if called from event dispatch thread
* or at some later time inside event dispatch thread otherwise and blocks
* until it is ready. Doesn't throw exceptions. Instead returns false in
* case of an exception.
*/
public static boolean swingOperationBlock(Runnable run) {
if(!EventQueue.isDispatchThread()) {
try{
SwingUtilities.invokeAndWait(run);
return true;
}
catch(Exception e){
return false;
}
}
else {
run.run();
return true;
}
}
/**
* Runs the given RunnableReturn immediately if called from event dispatch thread
* or at some later time inside event dispatch thread otherwise. Returns
* a special return value which can be used to get the return value of
* RunnableReturn parameter.
*/
public static <R> SwingReturn<R> swingOperation(final RunnableReturn<R> run){
if(!EventQueue.isDispatchThread()) {
final ValueContainer<R> container=new ValueContainer<R>();
final Semaphore semaphore=new Semaphore(0);
swingOperation(new Runnable(){public void run(){
R r=run.run();
container.setValue(r);
semaphore.release();
}});
return new SwingReturn(semaphore,container);
}
else return new SwingReturn<R>(new Semaphore(1),new ValueContainer<R>(run.run()));
}
/**
* Runs the given RunnableReturn immediately if called from event dispatch thread
* or at some later time inside event dispatch thread otherwise. Blocks until
* ready and returns value from RunnableReturn param.
*/
public static <R> R swingOperationBlock(final RunnableReturn<R> run){
SwingReturn<R> ret=swingOperation(run);
return ret.getValueNoInterrupt();
}
public static interface RunnableReturn<R>{
public R run();
}
/**
* A class used for the return value of swingOperation(RunnableReturn). The
* getValue method will return the return value of the operation when it is
* ready. It will block if necessary.
*/
public static class SwingReturn<R>{
protected Semaphore semaphore;
protected ValueContainer<R> container;
protected SwingReturn(Semaphore semaphore,ValueContainer<R> container){
this.semaphore=semaphore;
this.container=container;
}
public R getValue() throws InterruptedException {
semaphore.acquire();
return container.getValue();
}
public R getValueNoInterrupt(){
try{
return getValue();
}
catch(InterruptedException e){
return null;
}
}
}
public static class ValueContainer<T>{
private T value;
public ValueContainer(){}
public ValueContainer(T v){
value=v;
}
public synchronized T getValue(){return value;}
public synchronized void setValue(T v){value=v;}
}
private static final Object workLock=new Object();
private static Thread workThread=null;
public static boolean doWork(final Runnable run,final WaitNotificationHandler wnh){
boolean runInCurrent=false;
SyncBlock: synchronized(workLock){
if(Thread.currentThread()==workThread) {
runInCurrent=true;
break SyncBlock;
}
if(workThread!=null) {System.out.println("Work ignored"); return false;}
final ValueContainer<Integer> container=new ValueContainer<Integer>(0);
Thread dialogThread=new Thread(){
@Override
public void run(){
try{
Thread.sleep(500);
}catch(InterruptedException ie){}
int v=0;
synchronized(workLock){
container.setValue(container.getValue()+1);
v=container.getValue();
}
if(v==1) wnh.showNotification();
}
};
workThread = new Thread(){
@Override
public void run(){
Exception exception=null;
try{
run.run();
}
catch(Exception e){
e.printStackTrace();
exception=e;
}
int v=0;
synchronized(workLock){
v=container.getValue();
container.setValue(container.getValue()-1);
workThread=null;
}
if(v==1){
while(!wnh.isNotificationVisible()){
Thread.yield();
}
wnh.hideNotification();
}
/* if(exception!=null && wdh!=null){
wdh.showExceptionDialog(exception);
}*/
}
};
dialogThread.start();
workThread.start();
return true;
}
if(runInCurrent){
run.run();
return true;
}
else return false; // should not happen
}
}
| 7,550 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GuiTools.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/GuiTools.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* GuiTools.java
*
* Created on 6.7.2005, 9:46
*/
package org.wandora.utils.swing;
import java.awt.Component;
import java.awt.Window;
import javax.swing.JViewport;
/**
*
* @author olli
*/
public class GuiTools {
/** Creates a new instance of GuiTools */
private GuiTools() {
// Private
}
public static void centerWindow(Window wnd,Component parent){
int x=parent.getLocation().x+parent.getWidth()/2-wnd.getWidth()/2;
int y=parent.getLocation().y+parent.getHeight()/2-wnd.getHeight()/2;
if(x<0) x=0;
if(y<0) y=0;
wnd.setLocation(x,y);
}
public static Window getWindow(Component c){
while(!(c instanceof Window) && c!=null){
c=c.getParent();
}
return (Window)c;
}
public static JViewport getViewport(Component c){
c=c.getParent();
if(c==null) return null;
if(c instanceof JViewport) return (JViewport)c;
return getViewport(c);
}
}
| 1,824 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TextLineNumber.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/TextLineNumber.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.swing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashMap;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.StyleConstants;
import javax.swing.text.Utilities;
/**
* Based on
* https://tips4java.wordpress.com/2009/05/23/text-component-line-number/
*
* This class will display line numbers for a related text component. The text
* component must use the same line height for each line. TextLineNumber
* supports wrapped lines and will highlight the line number of the current line
* in the text component.
*
* This class was designed to be used as a component added to the row header of
* a JScrollPane.
*
* Simple usage:
* JTextPane textPane = new JTextPane();
* JScrollPane scrollPane = new JScrollPane(textPane);
* TextLineNumber tln = new TextLineNumber(textPane);
* scrollPane.setRowHeaderView( tln );
*
*/
public class TextLineNumber extends JPanel implements CaretListener, DocumentListener, PropertyChangeListener {
private static final long serialVersionUID = 1L;
public final static float LEFT = 0.0f;
public final static float CENTER = 0.5f;
public final static float RIGHT = 1.0f;
private final static Border OUTER = new MatteBorder(0, 0, 0, 1, Color.GRAY);
private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
// Text component this TextTextLineNumber component is in sync with
private JTextComponent component;
// Properties that can be changed
private boolean updateFont;
private int borderGap;
private Color currentLineForeground;
private float digitAlignment;
private int minimumDisplayDigits;
// Keep history information to reduce the number of times the component
// needs to be repainted
private int lastDigits;
private int lastHeight;
private int lastLine;
private HashMap<String, FontMetrics> fonts;
/**
* Create a line number component for a text component. This minimum display
* width will be based on 3 digits.
*
* @param component the related text component
*/
public TextLineNumber(JTextComponent component) {
this(component, 3);
}
/**
* Create a line number component for a text component.
*
* @param component the related text component
* @param minimumDisplayDigits the number of digits used to calculate the
* minimum width of the component
*/
public TextLineNumber(JTextComponent component, int minimumDisplayDigits) {
this.component = component;
setFont(component.getFont());
setBorderGap(5);
setCurrentLineForeground(Color.RED);
setDigitAlignment(RIGHT);
setMinimumDisplayDigits(minimumDisplayDigits);
component.getDocument().addDocumentListener(this);
component.addCaretListener(this);
component.addPropertyChangeListener("font", this);
}
/**
* Gets the update font property
*
* @return the update font property
*/
public boolean getUpdateFont() {
return updateFont;
}
/**
* Set the update font property. Indicates whether this Font should be
* updated automatically when the Font of the related text component is
* changed.
*
* @param updateFont when true update the Font and repaint the line numbers,
* otherwise just repaint the line numbers.
*/
public void setUpdateFont(boolean updateFont) {
this.updateFont = updateFont;
}
/**
* Gets the border gap
*
* @return the border gap in pixels
*/
public int getBorderGap() {
return borderGap;
}
/**
* The border gap is used in calculating the left and right insets of the
* border. Default value is 5.
*
* @param borderGap the gap in pixels
*/
public void setBorderGap(int borderGap) {
this.borderGap = borderGap;
Border inner = new EmptyBorder(0, borderGap, 0, borderGap);
setBorder(new CompoundBorder(OUTER, inner));
lastDigits = 0;
setPreferredWidth();
}
/**
* Gets the current line rendering Color
*
* @return the Color used to render the current line number
*/
public Color getCurrentLineForeground() {
return currentLineForeground == null ? getForeground() : currentLineForeground;
}
/**
* The Color used to render the current line digits. Default is Coolor.RED.
*
* @param currentLineForeground the Color used to render the current line
*/
public void setCurrentLineForeground(Color currentLineForeground) {
this.currentLineForeground = currentLineForeground;
}
/**
* Gets the digit alignment
*
* @return the alignment of the painted digits
*/
public float getDigitAlignment() {
return digitAlignment;
}
/**
* Specify the horizontal alignment of the digits within the component.
* Common values would be:
* <ul>
* <li>TextLineNumber.LEFT
* <li>TextLineNumber.CENTER
* <li>TextLineNumber.RIGHT (default)
* </ul>
*
* @param currentLineForeground the Color used to render the current line
*/
public void setDigitAlignment(float digitAlignment) {
this.digitAlignment
= digitAlignment > 1.0f ? 1.0f : digitAlignment < 0.0f ? -1.0f : digitAlignment;
}
/**
* Gets the minimum display digits
*
* @return the minimum display digits
*/
public int getMinimumDisplayDigits() {
return minimumDisplayDigits;
}
/**
* Specify the mimimum number of digits used to calculate the preferred
* width of the component. Default is 3.
*
* @param minimumDisplayDigits the number digits used in the preferred width
* calculation
*/
public void setMinimumDisplayDigits(int minimumDisplayDigits) {
this.minimumDisplayDigits = minimumDisplayDigits;
setPreferredWidth();
}
/**
* Calculate the width needed to display the maximum line number
*/
private void setPreferredWidth() {
Element root = component.getDocument().getDefaultRootElement();
int lines = root.getElementCount();
int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits);
// Update sizes when number of digits in the line number changes
if (lastDigits != digits) {
lastDigits = digits;
FontMetrics fontMetrics = getFontMetrics(getFont());
int width = fontMetrics.charWidth('0') * digits;
Insets insets = getInsets();
int preferredWidth = insets.left + insets.right + width;
Dimension d = getPreferredSize();
d.setSize(preferredWidth, HEIGHT);
setPreferredSize(d);
setSize(d);
}
}
/**
* Draw the line numbers
*/
@Override
public void paintComponent(Graphics g) {
if(g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
}
super.paintComponent(g);
// Determine the width of the space available to draw the line number
FontMetrics fontMetrics = component.getFontMetrics(component.getFont());
Insets insets = getInsets();
int availableWidth = getSize().width - insets.left - insets.right;
// Determine the rows to draw within the clipped bounds.
Rectangle clip = g.getClipBounds();
int rowStartOffset = component.viewToModel(new Point(0, clip.y));
int endOffset = component.viewToModel(new Point(0, clip.y + clip.height));
while (rowStartOffset <= endOffset) {
try {
if (isCurrentLine(rowStartOffset)) {
g.setColor(getCurrentLineForeground());
} else {
g.setColor(getForeground());
}
// Get the line number as a string and then determine the
// "X" and "Y" offsets for drawing the string.
String lineNumber = getTextLineNumber(rowStartOffset);
int stringWidth = fontMetrics.stringWidth(lineNumber);
int x = getOffsetX(availableWidth, stringWidth) + insets.left;
int y = getOffsetY(rowStartOffset, fontMetrics);
g.drawString(lineNumber, x, y);
// Move to the next row
rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1;
} catch (Exception e) {
break;
}
}
}
/*
* We need to know if the caret is currently positioned on the line we
* are about to paint so the line number can be highlighted.
*/
private boolean isCurrentLine(int rowStartOffset) {
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) {
return true;
} else {
return false;
}
}
/*
* Get the line number to be drawn. The empty string will be returned
* when a line of text has wrapped.
*/
protected String getTextLineNumber(int rowStartOffset) {
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex(rowStartOffset);
Element line = root.getElement(index);
if (line.getStartOffset() == rowStartOffset) {
return String.valueOf(index + 1);
} else {
return "";
}
}
/*
* Determine the X offset to properly align the line number when drawn
*/
private int getOffsetX(int availableWidth, int stringWidth) {
return (int) ((availableWidth - stringWidth) * digitAlignment);
}
/*
* Determine the Y offset for the current row
*/
private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics)
throws BadLocationException {
// Get the bounding rectangle of the row
Rectangle r = component.modelToView(rowStartOffset);
int lineHeight = fontMetrics.getHeight();
int y = r.y + r.height;
int descent = 0;
// The text needs to be positioned above the bottom of the bounding
// rectangle based on the descent of the font(s) contained on the row.
if (r.height == lineHeight) // default font is being used
{
descent = fontMetrics.getDescent();
} else // We need to check all the attributes for font changes
{
if (fonts == null) {
fonts = new HashMap<String, FontMetrics>();
}
Element root = component.getDocument().getDefaultRootElement();
int index = root.getElementIndex(rowStartOffset);
Element line = root.getElement(index);
for (int i = 0; i < line.getElementCount(); i++) {
Element child = line.getElement(i);
AttributeSet as = child.getAttributes();
String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily);
Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize);
String key = fontFamily + fontSize;
FontMetrics fm = fonts.get(key);
if (fm == null) {
Font font = new Font(fontFamily, Font.PLAIN, fontSize);
fm = component.getFontMetrics(font);
fonts.put(key, fm);
}
descent = Math.max(descent, fm.getDescent());
}
}
return y - descent;
}
//
// Implement CaretListener interface
//
@Override
public void caretUpdate(CaretEvent e) {
// Get the line the caret is positioned on
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
int currentLine = root.getElementIndex(caretPosition);
// Need to repaint so the correct line number can be highlighted
if (lastLine != currentLine) {
repaint();
lastLine = currentLine;
}
}
//
// Implement DocumentListener interface
//
@Override
public void changedUpdate(DocumentEvent e) {
documentChanged();
}
@Override
public void insertUpdate(DocumentEvent e) {
documentChanged();
}
@Override
public void removeUpdate(DocumentEvent e) {
documentChanged();
}
/*
* A document change may affect the number of displayed lines of text.
* Therefore the lines numbers will also change.
*/
private void documentChanged() {
// View of the component has not been updated at the time
// the DocumentEvent is fired
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
int endPos = component.getDocument().getLength();
Rectangle rect = component.modelToView(endPos);
if (rect != null && rect.y != lastHeight) {
setPreferredWidth();
repaint();
lastHeight = rect.y;
}
} catch (BadLocationException ex) { /* nothing to do */ }
}
});
}
//
// Implement PropertyChangeListener interface
//
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() instanceof Font) {
if (updateFont) {
Font newFont = (Font) evt.getNewValue();
setFont(newFont);
lastDigits = 0;
setPreferredWidth();
} else {
repaint();
}
}
}
}
| 15,815 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ImagePanel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/ImagePanel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* ImagePanel.java
*
* Created on August 30, 2004, 4:13 PM
*/
package org.wandora.utils.swing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
*
* @author akivela
*/
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private URL url;
private File file;
private BufferedImage image;
private Dimension imageDimensions;
/** Creates a new instance of ImagePanel */
public ImagePanel(String imageLocator) {
setImage(imageLocator);
}
public ImagePanel(String imageLocator, Color bgcolor) {
setImage(imageLocator);
this.setBackground(bgcolor);
}
public void setImage(String imageLocator) {
if(imageLocator != null) {
image = null;
try {
this.url = new URL(imageLocator);
this.image = ImageIO.read(url);
//System.out.println("ImagePanel initialized with URL "+ imageLocator);
}
catch (Exception e) {
try {
this.file = new File(imageLocator);
this.image = ImageIO.read(file);
//System.out.println("ImagePanel initialized with FILE "+ imageLocator);
}
catch (Exception e2) {
try {
this.url = ClassLoader.getSystemResource(imageLocator);
this.image = ImageIO.read(url);
//System.out.println("ImagePanel initialized with URL (System Resource) "+ imageLocator);
}
catch (Exception e3) {
//System.out.println("Unable to initialize ImagePanel with "+ imageLocator);
e2.printStackTrace();
}
}
}
if(image != null) {
imageDimensions = new Dimension(image.getWidth(), image.getHeight());
this.setPreferredSize(imageDimensions);
this.setMaximumSize(imageDimensions);
this.setMinimumSize(imageDimensions);
}
}
this.revalidate();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if(image != null) {
//System.out.println(" image x =" + imageDimensions.width + ", y=" + imageDimensions.height );
int x = (this.getSize().width - imageDimensions.width) / 2;
int y = (this.getSize().height - imageDimensions.height) / 2;
if(x < 0) x = 0;
if(y < 0) y = 0;
g.drawImage(image,x ,y ,this);
}
}
}
| 3,683 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DragJTree.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/DragJTree.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* DragJTree.java
*
* Created on 2.6.2005, 10:19
*
* Copyright 2004-2005 Grip Studios Interactive Oy (office@gripstudios.com)
* Created by Olli Lyytinen, AKi Kivela
*/
package org.wandora.utils.swing;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.Autoscroll;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceContext;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
/**
* A JTree that allows moving nodes in the tree with drag and drop. You will need to
* implement allowDrop and doDrop. allowDrop checks if drop is allowed in the location
* where user holds the mouse. doDrop is called when the user finishes the drag and
* drop event. It must modify the model of the tree and notify the tree of changes in
* the model.
*
* @author olli
*/
public abstract class DragJTree extends JTree implements Autoscroll {
private static final long serialVersionUID = 1L;
protected TreePath selectedTreePath = null;
private Point offsetPoint = new Point();
private BufferedImage ghostImage;
private DragSource dragSource = null;
private DragSourceContext dragSourceContext = null;
private TreePath currentParent = null;
private TreePath currentPosition = null;
protected boolean enableDrag;
protected boolean localDragging;
/** Creates a new instance of DragJTree */
public DragJTree() {
super();
initialize();
}
public DragJTree(Hashtable<?,?> value){
super(value);
initialize();
}
public DragJTree(Object[] value){
super(value);
initialize();
}
public DragJTree(TreeModel model){
super(model);
initialize();
}
public DragJTree(TreeNode root){
super(root);
initialize();
}
public DragJTree(TreeNode root,boolean asksAllowsChildren){
super(root,asksAllowsChildren);
initialize();
}
public DragJTree(Vector<?> value){
super(value);
initialize();
}
protected void initialize(){
enableDrag=true;
localDragging=false;
dragSource = DragSource.getDefaultDragSource();
final DragSourceListener dragSourceListener = new DragSourceListener(){
public void dragDropEnd(DragSourceDropEvent dsde){
localDragging=false;
}
public void dragEnter(DragSourceDragEvent dsde){
}
public void dragExit(DragSourceEvent dse){
}
public void dragOver(DragSourceDragEvent dsde){
}
public void dropActionChanged(DragSourceDragEvent dsde){
}
};
DragGestureListener dragGestureListener = new DragGestureListener(){
public void dragGestureRecognized(DragGestureEvent dge) {
if(!enableDrag) return;
Point dragOrigin=dge.getDragOrigin();
TreePath path=getPathForLocation(dragOrigin.x,dragOrigin.y);
if(path!=null && !isRootPath(path)){
Rectangle pathRect=getPathBounds(path);
offsetPoint.setLocation(dragOrigin.x-pathRect.x,dragOrigin.y-pathRect.y);
Component comp = getCellRenderer().getTreeCellRendererComponent(DragJTree.this,path.getLastPathComponent(),
false,isExpanded(path),
getModel().isLeaf(path.getLastPathComponent()),
0,false);
comp.setSize((int)pathRect.getWidth(),(int)pathRect.getHeight());
ghostImage = new BufferedImage((int)pathRect.getWidth(),(int)pathRect.getHeight(),BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D g2 = ghostImage.createGraphics();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC,0.5f));
comp.paint(g2);
g2.dispose();
selectedTreePath=path;
setSelectionPath(path);
currentParent=null;
currentPosition=null;
Transferable transferable=getTransferable(path);
localDragging=true;
dge.startDrag(null, ghostImage, new Point(5,5), transferable, dragSourceListener);
}
}
};
DragGestureRecognizer dgr = dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, dragGestureListener);
dgr.setSourceActions(dgr.getSourceActions() & ~InputEvent.BUTTON3_MASK);
DropTarget dropTarget = new DropTarget(this,new MyDropTargetListener());
}
public boolean isDragEnabled(){return enableDrag;}
/**
* Enable or disable dragging. If disabled DragJTree behaves like a regular
* JTree.
*/
// Does this intentionally override JTree method or accidentally?
@Override
public void setDragEnabled(boolean val){
enableDrag=val;
}
private static final int AUTOSCROLL_MARGIN = 12;
public void autoscroll(Point pt) {
// Figure out which row we are on.
int nRow = getRowForLocation(pt.x, pt.y);
// If we are not on a row then ignore this autoscroll request
if (nRow < 0) return;
Rectangle raOuter = getBounds();
nRow = (pt.y + raOuter.y <= AUTOSCROLL_MARGIN) // Is row at top of screen?
?
(nRow <= 0 ? 0 : nRow - 1) // Yes, scroll up one row
:
(nRow < getRowCount() - 1 ? nRow + 1 : nRow); // No, scroll down one row
scrollRowToVisible(nRow);
}
public Insets getAutoscrollInsets() {
Rectangle raOuter = getBounds();
Rectangle raInner = getParent().getBounds();
return new Insets(
raInner.y - raOuter.y + AUTOSCROLL_MARGIN, raInner.x - raOuter.x + AUTOSCROLL_MARGIN,
raOuter.height - raInner.height - raInner.y + raOuter.y + AUTOSCROLL_MARGIN,
raOuter.width - raInner.width - raInner.x + raOuter.x + AUTOSCROLL_MARGIN);
}
protected Transferable getTransferable(TreePath path){
return new TransferableTreePath(path);
}
private boolean isRootPath(TreePath path) {
return isRootVisible() && getRowForPath(path) == 0;
}
/**
* Checks if drop is allowed in the destination.
* @param destinationParent The parent of the destination where user is about to drop something.
* @param destinationPosition The position after which user is about to drop something. May be
* null in which case the item is to be dropped as the first child of
* destinationParent.
* @param source The item being dragged.
* @return One of action constants in java.awt.dnd.DnDConstants representing the possible drop actions.
*/
public abstract int allowDrop(TreePath destinationParent,TreePath destinationPosition,TreePath source);
/**
* Performs the drop event. Must modify the tree model to actually make the changes in the tree and
* also notify the model of these changes so that the UI can be updated.
*
* @param destinationParent The parent of the destination where user is about to drop something.
* @param destinationPosition The position after which user is about to drop something. May be
* null in which case the item is to be dropped as the first child of
* destinationParent.
* @param source The item being dragged.
* @param action The drop action. One of the action constants in java.awt.dnd.DnDConstants.
*/
public abstract void doDrop(TreePath destinationParent,TreePath destinationPosition, TreePath source, int action);
/**
* Override this method if you wish to process drag and drop events originating from
* outside this component. Default implementation calls dtde.rejectDrop().
*/
public void nonLocalDrop(DropTargetDropEvent dtde){
dtde.rejectDrop();
}
/**
* Override this method if you wish to process drag and drop events originating from
* outside this component. Default implementation calls dtde.rejectDrag().
*/
public void nonLocalDragEnter(DropTargetDragEvent dtde){
dtde.rejectDrag();
}
/**
* Override this method if you wish to process drag and drop events originating from
* outside this component. Default implementation calls dtde.rejectDrag().
*/
public void nonLocalDragOver(DropTargetDragEvent dtde){
dtde.rejectDrag();
}
/**
* Override this method if you wish to process drag and drop events originating from
* outside this component. Default implementation does nothing.
*/
public void nonLocalDragExit(DropTargetEvent dtde){
}
/**
* Override this method if you wish to process drag and drop events originating from
* outside this component. Default implementation calls dtde.rejectDrag().
*/
public void nonLocalDropActionChanged(DropTargetDragEvent dtde) {
dtde.rejectDrag();
}
private class MyDropTargetListener implements DropTargetListener {
private TreePath lastPath = null;
private Rectangle2D cueLineRect = new Rectangle2D.Float();
private Rectangle2D ghostRect = new Rectangle2D.Float();
private Color cueLineColor;
private Point lastPoint = new Point();
private Timer hoverTimer;
public MyDropTargetListener(){
cueLineColor = new Color(SystemColor.controlShadow.getRed(),
SystemColor.controlShadow.getGreen(),
SystemColor.controlShadow.getBlue(), 128);
hoverTimer = new Timer(3000, new ActionListener(){
public void actionPerformed(ActionEvent e){
if(lastPath==null || isRootPath(lastPath)) return;
if(!isExpanded(lastPath)) expandPath(lastPath);
}
});
hoverTimer.setRepeats(false);
}
public void drop(DropTargetDropEvent dtde) {
if(!localDragging){
nonLocalDrop(dtde);
return;
}
hoverTimer.stop();
int action=dtde.getDropAction();
int accepted=allowDrop(currentParent,currentPosition,selectedTreePath);
if(accepted==action ||
(accepted==DnDConstants.ACTION_COPY_OR_MOVE && (action==DnDConstants.ACTION_COPY || action==DnDConstants.ACTION_MOVE))){
dtde.acceptDrop(accepted);
}
else{
dtde.rejectDrop();
return;
}
Transferable transferable = dtde.getTransferable();
if(!transferable.isDataFlavorSupported(TransferableTreePath.FLAVOR)) {
dtde.rejectDrop();
return;
}
doDrop(currentParent,currentPosition,selectedTreePath,action);
repaint();
}
public void dragEnter(DropTargetDragEvent dtde) {
if(!localDragging){
nonLocalDragEnter(dtde);
return;
}
int accepted=allowDrop(currentParent,currentPosition,selectedTreePath);
if(accepted!=DnDConstants.ACTION_NONE) dtde.acceptDrag(accepted);
else dtde.rejectDrag();
}
public void dragExit(DropTargetEvent dte) {
if(!localDragging){
nonLocalDragExit(dte);
return;
}
if(!DragSource.isDragImageSupported()){
repaint(ghostRect.getBounds());
}
}
public void dragOver(DropTargetDragEvent dtde) {
if(!localDragging){
nonLocalDragOver(dtde);
return;
}
Point pt = dtde.getLocation();
if(pt.equals(lastPoint)) return;
Graphics2D g2 = (Graphics2D)getGraphics();
// Drag image support has been disabled as the image flickers.
if(false && !DragSource.isDragImageSupported()) {
paintImmediately(ghostRect.getBounds());
ghostRect.setRect(pt.x-offsetPoint.x,pt.y-offsetPoint.y, ghostImage.getWidth(), ghostImage.getHeight());
g2.drawImage(ghostImage, AffineTransform.getTranslateInstance(ghostRect.getX(),ghostRect.getY()),null);
}
int row=getClosestRowForLocation(pt.x,pt.y);
TreePath path=getPathForRow(row);
if(path!=lastPath) {
lastPath=path;
hoverTimer.restart();
}
Rectangle pathRect=getPathBounds(path);
int accepted=DnDConstants.ACTION_NONE;
if((pt.y>=pathRect.y+pathRect.height/4 || (row==0 && DragJTree.this.isRootVisible())) && pt.y<pathRect.y+pathRect.height*3/4){
cueLineRect.setRect(pathRect);
currentParent=path;
currentPosition=null;
accepted=allowDrop(currentParent,currentPosition,selectedTreePath);
}
if(accepted==DnDConstants.ACTION_NONE){
int x=pathRect.x;
TreePath next=getPathForRow(row+1);
TreePath prev=getPathForRow(row-1);
if(row==0 && !DragJTree.this.isRootVisible()) prev=new TreePath(getModel().getRoot());
if(pt.y<pathRect.y+pathRect.height/2 && prev!=null){
next=path;
path=prev;
prev=getPathForRow(row-2);
if(row==1 && !DragJTree.this.isRootVisible()) prev=new TreePath(getModel().getRoot());
if(path.getPathCount()==1 && !DragJTree.this.isRootVisible())
pathRect=new Rectangle(0,0,pathRect.width,0);
else pathRect=getPathBounds(path);
}
currentParent=path.getParentPath();
currentPosition=path;
if(next!=null && next.getParentPath().getLastPathComponent()==path.getLastPathComponent()){
x=getPathBounds(next).x;
currentParent=path;
currentPosition=null;
}
else if(pt.y>=pathRect.y+pathRect.height){
if(next==null || next.getParentPath().getLastPathComponent()!=path.getParentPath().getLastPathComponent()){
if(path.getParentPath().getParentPath()!=null){
x=getPathBounds(path.getParentPath()).x;
currentParent=path.getParentPath().getParentPath();
currentPosition=path.getParentPath();
}
}
}
cueLineRect.setRect(x,pathRect.y+(int)pathRect.getHeight(),getWidth()-x,2);
accepted=allowDrop(currentParent,currentPosition,selectedTreePath);
}
if(accepted!=DnDConstants.ACTION_NONE){
g2.setColor(cueLineColor);
g2.fill(cueLineRect);
ghostRect = ghostRect.createUnion(cueLineRect);
dtde.acceptDrag(accepted);
}
else{
dtde.rejectDrag();
}
}
public void dropActionChanged(DropTargetDragEvent dtde) {
if(!localDragging){
nonLocalDropActionChanged(dtde);
return;
}
Point pt = dtde.getLocation();
TreePath path=getClosestPathForLocation(pt.x,pt.y);
int accepted=allowDrop(currentParent,currentPosition,selectedTreePath);
if(accepted!=DnDConstants.ACTION_NONE){
dtde.acceptDrag(accepted);
}
else{
dtde.rejectDrag();
}
}
}
public static class TransferableTreePath implements Transferable {
public static final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType,"TreePath");
private TreePath path;
private DataFlavor[] flavors=new DataFlavor[]{FLAVOR};
public TransferableTreePath(TreePath path){
this.path=path;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor==FLAVOR;
}
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if(!isDataFlavorSupported(flavor)) throw new UnsupportedFlavorException(flavor);
return path;
}
}
public static boolean isDescendant(TreePath parent,TreePath child){
Object last=parent.getLastPathComponent();
for(Object n : child.getPath()){
if(n==last) return true;
}
return false;
}
public static void main(String[] args){
final JFrame w=new JFrame();
w.add(new DragJTree(){
public int allowDrop(TreePath destinationParent,TreePath destinationPosition,TreePath source){
if(destinationParent==null) return DnDConstants.ACTION_NONE;
if(isDescendant(source,destinationParent)) return DnDConstants.ACTION_NONE;
return DnDConstants.ACTION_MOVE;
}
public void doDrop(TreePath destinationParent,TreePath destinationPosition,TreePath source,int action){
System.out.println("Moving "+source+" to "+destinationParent+", "+destinationPosition);
}
});
w.pack();
w.setSize(400,400);
w.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
w.setVisible(false);
w.dispose();
System.exit(0);
}
});
w.setVisible(true);
}
}
| 20,905 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MultiLineLabel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/MultiLineLabel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* MultiLineLabel.java
*
* Created on September 11, 2004, 4:51 PM
*/
package org.wandora.utils.swing;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class MultiLineLabel extends Canvas {
private static final long serialVersionUID = 1L;
public static final int LEFT = 0;
public final int CENTER = 1;
public final int RIGHT = 2;
protected String[] lines;
protected int num_lines;
protected int margin_width;
protected int margin_height;
protected int line_width;
protected int line_height;
protected int line_ascent;
protected int[] line_widths;
protected int max_width;
protected int alignment = LEFT;
private List<String []> history;
private int historyMaxSize = 1000;
protected void newLabel(String label) {
if(lines != null) {
if(history.size() > historyMaxSize) {
history.remove(0);
}
history.add(lines);
}
StringTokenizer t = new StringTokenizer(label, "\n");
num_lines = t.countTokens();
lines = new String[num_lines];
line_widths = new int[num_lines];
for(int i=0; i<num_lines;i++) lines[i] = t.nextToken();
}
protected void measure() {
FontMetrics fm = this.getFontMetrics(this.getFont());
if(fm == null) return;
line_height = fm.getHeight();
line_ascent = fm.getAscent();
max_width = 0;
for(int i=0; i<num_lines; i++) {
line_widths[i] = fm.stringWidth(lines[i]);
if(line_widths[i] > max_width) max_width = line_widths[i];
}
}
public MultiLineLabel(String label, int margin_width, int margin_height, int alignment) {
history = new ArrayList<>();
newLabel(label);
this.margin_width = margin_width;
this.margin_height = margin_height;
this.alignment = alignment;
}
public MultiLineLabel(String label, int margin_width, int margin_height) {
this(label, margin_width, margin_height, LEFT);
}
public MultiLineLabel(String label, int alignment) {
this(label,10,10,alignment);
}
public MultiLineLabel(String label) {
this(label,10,10,LEFT);
}
public void setText(String text) {
setLabel(text);
}
public void setLabel(String label) {
newLabel(label);
measure();
repaint();
}
@Override
public void setFont(Font f) {
super.setFont(f);
measure();
repaint();
}
@Override
public void setForeground(Color c) {
super.setForeground(c);
repaint();
}
public void setAlignment(int a) { alignment = a; repaint(); }
public void setMarginWidth(int mw) { margin_width = mw; repaint(); }
public void setMarginHeight(int mh) { margin_height = mh; repaint(); }
public int getAlignment() { return alignment; }
public int getMarginWidth() { return margin_width; }
public int getMarginHeight() { return margin_height; }
@Override
public void addNotify() { super.addNotify(); measure(); }
@Override
public Dimension getPreferredSize() {
Dimension superPreferred = super.getPreferredSize();
Dimension thiPreferred = new Dimension(max_width + 2*margin_width, num_lines*line_height + 2*margin_height);
int px = superPreferred.width > thiPreferred.width ? superPreferred.width : thiPreferred.width;
int py = superPreferred.height > thiPreferred.height ? superPreferred.height : thiPreferred.height;
return new Dimension(px, py);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(max_width, num_lines*line_height);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if(g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
}
try {
int x,y;
Dimension d = this.getSize(); // size();
y = line_ascent + (d.height - num_lines * line_height) / 2;
for(int i=0; i<num_lines; i++, y+=line_height) {
switch(alignment) {
case LEFT: x=margin_width; break;
case CENTER:
default: x=(d.width - line_widths[i])/2; break;
case RIGHT: x=d.width - margin_width -line_widths[i]; break;
}
g.drawString(lines[i],x,y);
}
}
catch(Exception e) {
}
}
public void setHistoryMaxSize(int maxSize) {
historyMaxSize = maxSize;
if(history.size() > historyMaxSize) {
for(int i=historyMaxSize-history.size(); i>0; i--) {
history.remove(0);
}
}
}
public String getHistoryAsString() {
StringBuilder sb = new StringBuilder("");
for(int i=0; i<history.size(); i++) {
String[] historyStrings = history.get(i);
for(int j=0; j<historyStrings.length; j++) {
sb.append(historyStrings[j]).append(" ");
}
sb.append("\n");
}
return sb.toString();
}
}
| 6,380 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
JPanelWithBackground.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/JPanelWithBackground.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* JPanelWithBackground.java
*
* Created on 27. huhtikuuta 2007, 14:07
*
*/
package org.wandora.utils.swing;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
*
* @author akivela
*/
public class JPanelWithBackground extends JPanel {
private static final long serialVersionUID = 1L;
private URL url;
private File file;
private BufferedImage image;
public static final int TOP_LEFT_ALIGN = 100;
public static final int BOTTOM_LEFT_ALIGN = 200;
public int align = TOP_LEFT_ALIGN;
/** Creates a new instance of JPanelWithBackground */
public JPanelWithBackground() {
}
public void setAlign(int newAlign) {
this.align = newAlign;
}
public void setImage(String imageLocator) {
if(imageLocator != null) {
image = null;
try {
this.url = new URL(imageLocator);
this.image = ImageIO.read(url);
//System.out.println("ImagePanel initialized with URL "+ imageLocator);
}
catch (Exception e) {
try {
this.file = new File(imageLocator);
this.image = ImageIO.read(file);
//System.out.println("ImagePanel initialized with FILE "+ imageLocator);
}
catch (Exception e2) {
try {
this.url = ClassLoader.getSystemResource(imageLocator);
this.image = ImageIO.read(url);
//System.out.println("ImagePanel initialized with URL (System Resource) "+ imageLocator);
}
catch (Exception e3) {
//System.out.println("Unable to initialize ImagePanel with "+ imageLocator);
e2.printStackTrace();
}
}
}
}
this.revalidate();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension d = getSize();
if(image != null) {
switch(align) {
case TOP_LEFT_ALIGN: {
g.drawImage(image, 0,0, this);
break;
}
case BOTTOM_LEFT_ALIGN: {
int yoffset = d.height - image.getHeight();
g.drawImage(image, 0, yoffset, this);
break;
}
}
}
}
}
| 3,492 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
WaitNotificationHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/WaitNotificationHandler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* WaitNotificationHandler.java
*
* Created on 1.6.2005, 11:23
*
* Copyright 2004-2005 Grip Studios Interactive Oy (office@gripstudios.com)
* Created by Olli Lyytinen, AKi Kivela
*/
package org.wandora.utils.swing;
import org.wandora.utils.Delegate;
/**
*
* @author olli
*/
public class WaitNotificationHandler {
private Delegate<Delegate.Void,Boolean> listener=null;
/** Creates a new instance of WaitNotificationHandler */
public WaitNotificationHandler() {
}
public WaitNotificationHandler(Delegate<Delegate.Void,Boolean> l) {
setListener(l);
}
private int counter=0;
public void showNotification(){
counter++;
if(listener!=null) listener.invoke(isNotificationVisible());
}
public void hideNotification(){
counter--;
if(listener!=null) listener.invoke(isNotificationVisible());
}
public boolean isNotificationVisible(){
return counter>0;
}
public void setListener(Delegate<Delegate.Void,Boolean> l){
this.listener=l;
}
}
| 1,882 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableSelectionEvent.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/anyselectiontable/TableSelectionEvent.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.utils.swing.anyselectiontable;
import javax.swing.event.ListSelectionEvent;
/**
* An event that characterizes a change in the current selection.
* @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
*/
public class TableSelectionEvent extends ListSelectionEvent {
private static final long serialVersionUID = 1L;
/**
* The index of the column whose selection has changed.
*/
protected int columnIndex;
public TableSelectionEvent(Object source, int firstRowIndex, int lastRowIndex, int columnIndex, boolean isAdjusting) {
super(source, firstRowIndex, lastRowIndex, isAdjusting);
this.columnIndex = columnIndex;
}
/**
* Returns the index of the column whose selection has changed.
* @return The last column whose selection value has changed, where zero is the first column.
*/
public int getColumnIndex() {
return columnIndex;
}
}
| 1,753 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableSelectionModel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/anyselectiontable/TableSelectionModel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.utils.swing.anyselectiontable;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import javax.swing.DefaultListSelectionModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
/**
* This class represents the current state of the selection of
* the AnySelectionTable.
* It keeps the information in a list of ListSelectionModels, where
* each Model represents the selection of a column.
* @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
*/
// This class is added to the Table as aPropertyChangeListener. It
// will be noticed when the Table has a new TableModel. So it can
// adjust itself to the new TableModel and can add itself
// as a TableModelListener to the new TableModel.
// This class is added to the TableModel as a TableModelListener to
// be noticed when the TableModel changes. The number of
// ListSelectionModels in this class must be the same as the
// number of rows in the TableModel.
// This class implements a ListSelectionListener and is added to
// all its ListSelectionModels. If this class
// changes one of its ListSelectionModels, the ListSelectionModel
// fires a new ListSelectionEvent which is received by this class.
// After receiving that event, this class fires a TableSelectionEvent.
// That approach saves me from calculating 'firstIndex' and 'lastIndex'
// for myself and makes sure that a TableSelectionEvent is fired
// whenever the selection changes.
public class TableSelectionModel implements PropertyChangeListener, ListSelectionListener, TableModelListener {
/** List of Listeners which will be notified when the selection value changes */
protected EventListenerList listenerList = new EventListenerList();
/** contains a ListSelectionModel for each column */
protected List<ListSelectionModel> listSelectionModels = new ArrayList<>();
public TableSelectionModel() {
}
/**
* Forwards the request to the ListSelectionModel
* at the specified column.
*/
public void addSelection(int row, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
lsm.addSelectionInterval(row, row);
}
/**
* Forwards the request to the ListSelectionModel
* at the specified column.
*/
public void setSelection(int row, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
lsm.setSelectionInterval(row, row);
}
/**
* Forwards the request to the ListSelectionModel
* at the specified column.
*/
public void setSelectionInterval(int row1, int row2, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
lsm.setSelectionInterval(row1, row2);
}
/**
* Forwards the request to the ListSelectionModel
* at the specified column.
*/
public void setLeadSelectionIndex(int row, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
if (lsm.isSelectionEmpty())
lsm.setSelectionInterval(row, row);
else
//calling that method throws an IndexOutOfBoundsException when selection is empty (?, JDK 1.1.8, Swing 1.1)
lsm.setLeadSelectionIndex(row);
}
/**
* Forwards the request to the ListSelectionModel
* at the specified column.
*/
public void removeSelection(int row, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
lsm.removeSelectionInterval(row, row);
}
/**
* Calls clearSelection() of all ListSelectionModels.
*/
public void clearSelection() {
for(Iterator<ListSelectionModel> enu=listSelectionModels.iterator(); enu.hasNext();) {
ListSelectionModel lm = enu.next();
lm.clearSelection();
}
}
/**
* @return true, if the specified cell is selected.
*/
public boolean isSelected(int row, int column) {
ListSelectionModel lsm = getListSelectionModelAt(column);
if(lsm != null) return lsm.isSelectedIndex(row);
return false;
}
/**
* Returns the ListSelectionModel at the specified column
* @param index the column
*/
public ListSelectionModel getListSelectionModelAt(int index) {
if(index < listSelectionModels.size())
return listSelectionModels.get(index);
else
return null;
}
/**
* Set the number of columns.
* @param count the number of columns
*/
public void setColumns(int count) {
listSelectionModels = new ArrayList<>();
for (int i=0; i<count; i++) {
addColumn();
}
}
/**
* Add a column to the end of the model.
*/
protected void addColumn() {
DefaultListSelectionModel newListModel = new DefaultListSelectionModel();
listSelectionModels.add(newListModel);
newListModel.addListSelectionListener(this);
}
/**
* Remove last column from model.
*/
protected void removeColumn() {
//get last element
ListSelectionModel removedModel = listSelectionModels.get(listSelectionModels.size()-1);
removedModel.removeListSelectionListener(this);
listSelectionModels.remove(removedModel);
}
/**
* When the TableModel changes, the TableSelectionModel
* has to adapt to the new Model. This method is called
* if a new TableModel is set to the JTable.
*/
// implements PropertyChangeListener
public void propertyChange(PropertyChangeEvent evt) {
if ("model".equals(evt.getPropertyName())) {
TableModel newModel = (TableModel)(evt.getNewValue());
setColumns(newModel.getColumnCount());
TableModel oldModel = (TableModel)(evt.getOldValue());
if (oldModel != null)
oldModel.removeTableModelListener(this);
//TableSelectionModel must be aware of changes in the TableModel
newModel.addTableModelListener(this);
}
}
/**
* Add a listener to the list that's notified each time a
* change to the selection occurs.
*/
public void addTableSelectionListener(TableSelectionListener l) {
listenerList.add(TableSelectionListener.class, l);
}
/**
* Remove a listener from the list that's notified each time a
* change to the selection occurs.
*/
public void removeTableSelectionListener(TableSelectionListener l) {
listenerList.remove(TableSelectionListener.class, l);
}
/**
* Is called when the TableModel changes. If the number of columns
* had changed this class will adapt to it.
*/
//implements TableModelListener
public void tableChanged(TableModelEvent e) {
TableModel tm = (TableModel)e.getSource();
int count = listSelectionModels.size();
int tmCount = tm.getColumnCount();
//works, because you can't insert columns into a TableModel (only add/romove(?)):
//if columns were removed from the TableModel
while (count-- > tmCount) {
removeColumn();
}
//count == tmCount if was in the loop, else count < tmCount
//if columns were added to the TableModel
while (tmCount > count++) {
addColumn();
}
}
/**
* Is called when the selection of a ListSelectionModel
* of a column has changed.
* @see #fireValueChanged(Object source, int firstIndex, int lastIndex, int columnIndex, boolean isAdjusting)
*/
//implements ListSelectionListener
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int columnIndex = listSelectionModels.lastIndexOf(lsm);
if (columnIndex > -1) {
fireValueChanged(this, e.getFirstIndex(), e.getLastIndex(), columnIndex, e.getValueIsAdjusting());
}
}
/**
* Notify listeners that we have ended a series of adjustments.
*/
protected void fireValueChanged(Object source, int firstIndex, int lastIndex, int columnIndex, boolean isAdjusting) {
Object[] listeners = listenerList.getListenerList();
TableSelectionEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == TableSelectionListener.class) {
if (e == null) {
e = new TableSelectionEvent(source, firstIndex, lastIndex, columnIndex, false);
}
((TableSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
@Override
public String toString() {
String ret = "[\n";
for (int col=0; col<listSelectionModels.size(); col++) {
ret += "\'"+col+"\'={";
ListSelectionModel lsm = getListSelectionModelAt(col);
int startRow = lsm.getMinSelectionIndex();
int endRow = lsm.getMaxSelectionIndex();
for(int row=startRow; row<endRow; row++) {
if(lsm.isSelectedIndex(row))
ret += row + ", ";
}
if(lsm.isSelectedIndex(endRow))
ret += endRow;
ret += "}\n";
}
ret += "]";
/*String ret = "";
for (int col=0; col<listSelectionModels.size(); col++) {
ret += "\'"+col+"\'={"+getListSelectionModelAt(col)+"}";
}*/
return ret;
}
}
| 10,610 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TableSelectionListener.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/anyselectiontable/TableSelectionListener.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.utils.swing.anyselectiontable;
import java.util.EventListener;
/**
* The listener that's notified when a table selection value changes.
* @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
*/
public interface TableSelectionListener extends EventListener {
/**
* Called whenever the value of the selection changes.
*/
public void valueChanged(TableSelectionEvent e);
}
| 1,250 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AnySelectionTable.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/anyselectiontable/AnySelectionTable.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.utils.swing.anyselectiontable;
import java.util.List;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableModel;
/**
* A JTable which allows any selection of cells.
* @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
* @author Aki Kivela / Wandora Team
*/
public class AnySelectionTable extends JTable {
private static final long serialVersionUID = 1L;
private TableSelectionModel tableSelectionModel;
/**
* Doing almost the same as its parent except
* creating its own SelectionModel and UI
*/
public AnySelectionTable() {
super();
createDefaultTableSelectionModel();
setUI(new AnySelectionTableUI());
}
/**
* Doing almost the same as its parent except
* creating its own SelectionModel and UI
*/
public AnySelectionTable(TableModel dm) {
super(dm);
createDefaultTableSelectionModel();
setUI(new AnySelectionTableUI());
}
/**
* refers to its TableSelectionModel.
*/
@Override
public boolean isCellSelected(int row, int column) {
return tableSelectionModel.isSelected(row, convertColumnIndexToModel(column));
}
/**
* Creates a default TableSelectionModel.
*/
public void createDefaultTableSelectionModel() {
TableSelectionModel tsm = new TableSelectionModel();
setTableSelectionModel(tsm);
}
/**
* same intention as setSelectionModel(ListSelectionModel newModel)
*/
public void setTableSelectionModel(TableSelectionModel newModel) {
//the TableSelectionModel shouldn't be null
if (newModel == null) {
throw new IllegalArgumentException("Can't set a null TableSelectionModel");
}
//save the old Model
TableSelectionModel oldModel = this.tableSelectionModel;
//set the new Model
this.tableSelectionModel = newModel;
//The model needs to know how many columns are there
newModel.setColumns(getColumnModel().getColumnCount());
getModel().addTableModelListener(newModel);
if (oldModel != null) {
removePropertyChangeListener(oldModel);
}
addPropertyChangeListener(newModel);
firePropertyChange("tableSelectionModel", oldModel, newModel);
}
/**
* @return the current TableSelectionModel.
*/
public TableSelectionModel getTableSelectionModel() {
return tableSelectionModel;
}
@Override
public void clearSelection() {
if(tableSelectionModel != null) {
tableSelectionModel.clearSelection();
}
super.getSelectionModel().clearSelection();
super.getColumnModel().getSelectionModel().clearSelection();
this.repaint();
}
@Override
public void selectAll() {
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
for(int c=0; c<colCount; c++) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
columnSelectionModel.addSelectionInterval(0, rowCount);
}
}
}
this.repaint();
}
public void invertSelection() {
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
for(int c=0; c<colCount; c++) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
for(int r=0; r<rowCount; r++) {
if(columnSelectionModel.isSelectedIndex(r)) {
columnSelectionModel.removeSelectionInterval(r, r);
}
else {
columnSelectionModel.addSelectionInterval(r, r);
}
}
}
}
}
this.repaint();
}
public void selectColumn(int column) {
int rowCount = this.getRowCount();
int colCount = this.getColumnCount();
if(tableSelectionModel != null && column < colCount) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(column);
if(columnSelectionModel != null) {
columnSelectionModel.addSelectionInterval(0, rowCount-1);
}
}
this.repaint();
}
public void deselectColumn(int column) {
int rowCount = this.getRowCount();
int colCount = this.getColumnCount();
if(tableSelectionModel != null && column < colCount) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(column);
if(columnSelectionModel != null) {
columnSelectionModel.removeSelectionInterval(0, rowCount-1);
}
}
this.repaint();
}
public void selectColumns() {
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
for(int c=0; c<colCount; c++) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
if(!columnSelectionModel.isSelectionEmpty()) {
columnSelectionModel.addSelectionInterval(0, rowCount-1);
}
}
}
}
this.repaint();
}
public void selectRow(int row) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
if(tableSelectionModel != null && row < rowCount) {
ListSelectionModel columnSelectionModel = null;
for(int c=0; c<colCount; c++) {
columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
columnSelectionModel.addSelectionInterval(row, row);
}
}
}
this.repaint();
}
public void deselectRow(int row) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
if(tableSelectionModel != null && row < rowCount) {
ListSelectionModel columnSelectionModel = null;
for(int c=0; c<colCount; c++) {
columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
columnSelectionModel.removeSelectionInterval(row, row);
}
}
}
this.repaint();
}
public void selectRows() {
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
ListSelectionModel columnSelectionModel = null;
for(int r=0; r<rowCount; r++) {
boolean selectRow = false;
for(int c=0; c<colCount; c++) {
columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
if(columnSelectionModel.isSelectedIndex(r)) {
selectRow = true;
break;
}
}
}
if(selectRow) {
for(int c=0; c<colCount; c++) {
columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
columnSelectionModel.addSelectionInterval(r, r);
}
}
}
}
}
this.repaint();
}
public void selectCells(List<int[]> cells) {
if(cells != null && !cells.isEmpty()) {
for(int[] cell : cells) {
if(cell != null && cell.length == 2) {
selectCell(cell[1], cell[0]);
}
}
}
}
public void selectCell(int c, int r) {
//System.out.println("Selecting c,r == "+c+","+r);
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
if(c >= 0 && c < colCount && r >= 0 && r < rowCount) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
//System.out.println("Selecting c,r == "+c+","+r);
columnSelectionModel.addSelectionInterval(r, r);
}
}
}
this.repaint();
}
public void selectArea(int c1, int r1, int c2, int r2) {
if(tableSelectionModel != null) {
int colCount = this.getColumnCount();
int rowCount = this.getRowCount();
c1 = Math.min(c1, colCount);
c2 = Math.min(c2, colCount);
r1 = Math.min(r1, rowCount);
r2 = Math.min(r2, rowCount);
int cs = c1;
int ce = c2;
if(c2 < c1) {
cs = c2;
ce = c1;
}
int rs = r1;
int re = r2;
if(r2 < r1) {
rs = r2;
re = r1;
}
for(int c=cs; c<=ce; c++) {
ListSelectionModel columnSelectionModel = tableSelectionModel.getListSelectionModelAt(c);
if(columnSelectionModel != null) {
columnSelectionModel.addSelectionInterval(rs, re);
}
}
}
this.repaint();
}
}
| 11,015 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AnySelectionTableUI.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/anyselectiontable/AnySelectionTableUI.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.utils.swing.anyselectiontable;
import java.awt.Point;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.TableCellEditor;
/**
* This class doesn't change the L&F of the JTable but
* listens to mouse clicks and updates the TableSelectionModel.
*
* @author Jan-Friedrich Mutter (jmutter@bigfoot.de)
* @author Aki Kivela / Wandora Team
*/
public class AnySelectionTableUI extends BasicTableUI {
private int lastTableSelectionRow = -1;
private int lastTableSelectionColumn = -1;
public static ComponentUI createUI(JComponent c) {
return new AnySelectionTableUI();
}
@Override
protected MouseInputListener createMouseInputListener() {
return new AnySelectionMouseInputHandler();
}
/**
* to get access to the table from the inner class MyMouseInputHandler
*/
protected JTable getTable() {
return table;
}
/**
* updates the TableSelectionModel.
*/
protected void updateTableSelectionModel(int row, int column, boolean ctrlDown, boolean shiftDown, boolean isDrag) {
AnySelectionTable t = (AnySelectionTable)getTable();
column = t.convertColumnIndexToModel(column);
TableSelectionModel tsm = t.getTableSelectionModel();
if(ctrlDown) {
if (tsm.isSelected(row, column)) {
lastTableSelectionRow = -1;
lastTableSelectionColumn = -1;
tsm.removeSelection(row, column);
}
else {
lastTableSelectionRow = row;
lastTableSelectionColumn = column;
tsm.addSelection(row, column);
}
}
else if(shiftDown && lastTableSelectionRow != -1 && lastTableSelectionColumn != -1) {
t.selectArea(lastTableSelectionColumn, lastTableSelectionRow, column, row);
}
else if(!isDrag) {
lastTableSelectionRow = row;
lastTableSelectionColumn = column;
t.clearSelection();
tsm.setSelection(row, column);
}
}
public class AnySelectionMouseInputHandler extends MouseInputHandler {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
if(!SwingUtilities.isLeftMouseButton(e)) {
return;
}
JTable t = getTable();
if(!t.isEnabled()) {
return;
}
Point p = e.getPoint();
int row = t.rowAtPoint(p);
int column = t.columnAtPoint(p);
int rowCount = t.getRowCount();
int columnCount = t.getColumnCount();
if(column < 0 || row < 0 || column >= columnCount || row >= rowCount ) {
return;
}
TableCellEditor tce = t.getCellEditor();
if((tce==null) || (tce.shouldSelectCell(e))) {
t.requestFocus();
updateTableSelectionModel(row, column, e.isControlDown(), e.isShiftDown(), false);
t.repaint();
}
}
@Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
if(!SwingUtilities.isLeftMouseButton(e)) {
return;
}
JTable t = getTable();
if(!t.isEnabled()) {
return;
}
Point p = e.getPoint();
int row = t.rowAtPoint(p);
int column = t.columnAtPoint(p);
int rowCount = t.getRowCount();
int columnCount = t.getColumnCount();
if(column < 0 || row < 0 || column >= columnCount || row >= rowCount ) {
return;
}
TableCellEditor tce = t.getCellEditor();
if(tce==null) {
t.requestFocus();
updateTableSelectionModel(row, column, e.isControlDown(), !e.isShiftDown(), true);
t.repaint();
}
}
}
}
| 5,157 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TreeTableModelAdapter.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/treetable/TreeTableModelAdapter.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.swing.treetable;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.table.AbstractTableModel;
/**
*
* @author olli
*/
public class TreeTableModelAdapter extends AbstractTableModel {
private static final long serialVersionUID = 1L;
protected JTree tree;
protected TreeTableModel treeTableModel;
public TreeTableModelAdapter(TreeTableModel treeTableModel, JTree tree){
this.treeTableModel=treeTableModel;
this.tree=tree;
tree.addTreeExpansionListener(new TreeExpansionListener(){
public void treeExpanded(TreeExpansionEvent event){
fireTableDataChanged();
}
public void treeCollapsed(TreeExpansionEvent event){
fireTableDataChanged();
}
});
}
@Override
public String getColumnName(int column){
return treeTableModel.getColumnName(column);
}
public int getColumnCount() {
return treeTableModel.getColumnCount();
}
public int getRowCount() {
return tree.getRowCount();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return treeTableModel.getValueAt(tree.getPathForRow(rowIndex).getLastPathComponent(), columnIndex);
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return treeTableModel.isCellEditable(tree.getPathForRow(rowIndex).getLastPathComponent(), columnIndex);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
treeTableModel.setValueAt(aValue, tree.getPathForRow(rowIndex).getLastPathComponent(), columnIndex);
}
@Override
public Class getColumnClass(int column){
return treeTableModel.getColumnClass(column);
}
}
| 2,728 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TreeTable.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/treetable/TreeTable.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.swing.treetable;
import java.awt.Component;
import java.awt.Graphics;
import java.util.EventObject;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
/**
*
* @author olli
*/
public class TreeTable extends JTable {
private static final long serialVersionUID = 1L;
protected TreeTableCellRenderer tree;
public TreeTable(TreeTableModel treeTableModel){
super();
tree=new TreeTableCellRenderer(treeTableModel);
super.setModel(new TreeTableModelAdapter(treeTableModel, tree));
tree.setSelectionModel(new DefaultTreeSelectionModel() {
{
setSelectionModel(listSelectionModel);
}
});
tree.setRowHeight(getRowHeight());
setDefaultRenderer(TreeTableModel.class, tree);
setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
// setShowGrid(false);
// setIntercellSpacing(new Dimension(0,0));
}
public JTree getTree(){
return tree;
}
public Object getValueForRow(int row){
TreePath path=tree.getPathForRow(row);
if(path==null) return null;
return path.getLastPathComponent();
}
@Override
public int getEditingRow(){
return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 : editingRow;
}
public class TreeTableCellRenderer extends JTree implements TableCellRenderer {
protected int visibleRow;
public TreeTableCellRenderer(TreeModel model) {
super(model);
}
@Override
public void setBounds(int x, int y, int w, int h) {
super.setBounds(x, 0, w, TreeTable.this.getHeight());
}
@Override
public void paint(Graphics g) {
g.translate(0, -visibleRow * getRowHeight());
super.paint(g);
}
public Component getTableCellRendererComponent(JTable table,Object value,
boolean isSelected,boolean hasFocus,int row, int column) {
if(isSelected) setBackground(table.getSelectionBackground());
else setBackground(table.getBackground());
visibleRow = row;
return this;
}
}
public class TreeTableCellEditor implements TableCellEditor {
protected EventListenerList listeners;
public TreeTableCellEditor(){
listeners=new EventListenerList();
}
public Object getCellEditorValue() { return null; }
public boolean isCellEditable(EventObject e) { return true; }
public boolean shouldSelectCell(EventObject anEvent) { return false; }
public boolean stopCellEditing() { return true; }
public void cancelCellEditing() {}
public void addCellEditorListener(CellEditorListener l) {
listeners.add(CellEditorListener.class, l);
}
public void removeCellEditorListener(CellEditorListener l) {
listeners.remove(CellEditorListener.class, l);
}
protected void fireEditingStopped() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingStopped(new ChangeEvent(this));
}
}
}
protected void fireEditingCanceled() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CellEditorListener.class) {
((CellEditorListener)listeners[i+1]).editingCanceled(new ChangeEvent(this));
}
}
}
public Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int r, int c) {
return tree;
}
}
}
| 5,026 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TreeTableModel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/treetable/TreeTableModel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.swing.treetable;
import javax.swing.tree.TreeModel;
/**
*
* @author olli
*/
public interface TreeTableModel extends TreeModel {
public int getColumnCount();
public String getColumnName(int column);
public Class getColumnClass(int cloumn);
public Object getValueAt(Object node,int column);
public boolean isCellEditable(Object node,int column);
public void setValueAt(Object aValue,Object node,int column);
}
| 1,266 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractTreeTableModel.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/swing/treetable/AbstractTreeTableModel.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.swing.treetable;
import javax.swing.event.EventListenerList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreePath;
/**
*
* @author olli
*/
public abstract class AbstractTreeTableModel implements TreeTableModel {
protected EventListenerList listeners;
protected Object root;
// public int getColumnCount();
// public String getColumnName();
// public Object getValueAt(Object node, int column);
// public Object getChild(Object parent, int index);
// public int getChildCount(Object parent);
public AbstractTreeTableModel(Object root){
this.root=root;
listeners=new EventListenerList();
}
public Class getColumnClass(int cloumn){
return Object.class;
}
public boolean isCellEditable(Object node, int column) {
return getColumnClass(column) == TreeTableModel.class;
}
public void setValueAt(Object aValue, Object node, int column) {
}
public void addTreeModelListener(TreeModelListener l) {
listeners.add(TreeModelListener.class, l);
}
public int getIndexOfChild(Object parent, Object child) {
for (int i = 0; i < getChildCount(parent); i++) {
if (getChild(parent, i).equals(child)) {
return i;
}
}
return -1;
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return getChildCount(node)==0;
}
public void removeTreeModelListener(TreeModelListener l) {
listeners.remove(TreeModelListener.class, l);
}
public void valueForPathChanged(TreePath path, Object newValue) {
}
public void fireTreeNodesChanged(Object source, Object[] path, int[] childIndices, Object[] children) {
Object[] ls = listeners.getListenerList();
TreeModelEvent e = null;
for (int i = ls.length-2; i>=0; i-=2) {
if (ls[i]==TreeModelListener.class) {
if (e == null) e = new TreeModelEvent(source, path, childIndices, children);
((TreeModelListener)ls[i+1]).treeNodesChanged(e);
}
}
}
public void fireTreeNodesInserted(Object source, Object[] path, int[] childIndices, Object[] children) {
Object[] ls = listeners.getListenerList();
TreeModelEvent e = null;
for (int i = ls.length-2; i>=0; i-=2) {
if (ls[i]==TreeModelListener.class) {
if (e == null) e = new TreeModelEvent(source, path, childIndices, children);
((TreeModelListener)ls[i+1]).treeNodesInserted(e);
}
}
}
public void fireTreeNodesRemoved(Object source, Object[] path, int[] childIndices, Object[] children) {
Object[] ls = listeners.getListenerList();
TreeModelEvent e = null;
for (int i = ls.length-2; i>=0; i-=2) {
if (ls[i]==TreeModelListener.class) {
if (e == null) e = new TreeModelEvent(source, path, childIndices, children);
((TreeModelListener)ls[i+1]).treeNodesRemoved(e);
}
}
}
public void fireTreeStructureChanged(Object source, Object[] path, int[] childIndices, Object[] children) {
Object[] ls = listeners.getListenerList();
TreeModelEvent e = null;
for (int i = ls.length-2; i>=0; i-=2) {
if (ls[i]==TreeModelListener.class) {
if (e == null) e = new TreeModelEvent(source, path, childIndices, children);
((TreeModelListener)ls[i+1]).treeStructureChanged(e);
}
}
}
}
| 4,510 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LanguageBox.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/language/LanguageBox.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.utils.language;
import java.util.HashMap;
import org.wandora.topicmap.Locator;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.XTMPSI;
/**
*
* @author akivela
*/
public class LanguageBox {
public static final String[] languageNamesAndCodes = new String[] {
"Abkhazian", "abk", "ab",
"Afar", "aar", "aa",
"Afrikaans", "afr", "af",
"Akan", "aka", "ak",
"Albanian", "alb", "sq",
"Amharic", "amh", "am",
"Arabic", "ara", "ar",
"Aragonese", "arg", "an",
"Armenian", "arm", "hy",
"Assamese", "asm", "as",
"Avaric", "ava", "av",
"Avestan", "ave", "ae",
"Aymara", "aym", "ay",
"Azerbaijani", "aze", "az",
"Bambara", "bam", "bm",
"Bashkir", "bak", "ba",
"Basque", "baq", "eu",
"Belarusian", "bel", "be",
"Bengali", "ben", "bn",
"Bihari", "bih", "bh",
"Bislama", "bis", "bi",
"Bosnian", "bos", "bs",
"Breton", "bre", "br",
"Bulgarian", "bul", "bg",
"Burmese", "bur", "my",
"Catalan", "cat", "ca",
"Chamorro", "cha", "ch",
"Chechen", "che", "ce",
"Chinese", "chi", "zh",
"Chuang", "zha", "za",
"Church Slavic", "chu", "cu",
"Chuvash", "chv", "cv",
"Cornish", "cor", "kw",
"Corsican", "cos", "co",
"Cree", "cre", "cr",
"Croatian", "scr", "hr",
"Czech", "cze", "cs",
"Danish", "dan", "da",
"Divehi", "div", "dv",
"Dutch", "dut", "nl",
"Dzongkha", "dzo", "dz",
"English", "eng", "en",
"Esperanto", "epo", "eo",
"Estonian", "est", "et",
"Ewe", "ewe", "ee",
"Faroese", "fao", "fo",
"Fijian", "fij", "fj",
"Finnish", "fin", "fi",
"French", "fre", "fr",
"Frisian", "fry", "fy",
"Fulah", "ful", "ff",
"Gaelic", "gla", "gd",
"Galician", "glg", "gl",
"Ganda", "lug", "lg",
"Georgian", "geo", "ka",
"German", "ger", "de",
"Gikuyu", "kik", "ki",
"Greek", "gre", "el",
"Greenlandic", "kal", "kl",
"Guarani", "grn", "gn",
"Gujarati", "guj", "gu",
"Haitian", "hat", "ht",
"Hausa", "hau", "ha",
"Hebrew", "heb", "he",
"Herero", "her", "hz",
"Hindi", "hin", "hi",
"Hiri Motu", "hmo", "ho",
"Hungarian", "hun", "hu",
"Icelandic", "ice", "is",
"Ido", "ido", "io",
"Igbo", "ibo", "ig",
"Indonesian", "ind", "id",
"Interlingua", "ina", "ia",
"Interlingue", "ile", "ie",
"Inuktitut", "iku", "iu",
"Inupiaq", "ipk", "ik",
"Irish", "gle", "ga",
"Italian", "ita", "it",
"Japanese", "jpn", "ja",
"Javanese", "jav", "jv",
"Kannada", "kan", "kn",
"Kanuri", "kau", "kr",
"Kashmiri", "kas", "ks",
"Kazakh", "kaz", "kk",
"Khmer", "khm", "km",
"Kikuyu", "kik", "ki",
"Kinyarwanda", "kin", "rw",
"Kirghiz", "kir", "ky",
"Komi", "kom", "kv",
"Kongo", "kon", "kg",
"Korean", "kor", "ko",
"Kuanyama", "kua", "kj",
"Kurdish", "kur", "ku",
"Kwanyama", "kua", "kj",
"Lao", "lao", "lo",
"Latin", "lat", "la",
"Latvian", "lav", "lv",
"Luxembourgish", "ltz", "lb",
"Limburgan", "lim", "li",
"Lingala", "lin", "ln",
"Lithuanian", "lit", "lt",
"Luba-Katanga", "lub", "lu",
"Macedonian", "mac", "mk",
"Malagasy", "mlg", "mg",
"Malay", "may", "ms",
"Malayalam", "mal", "ml",
"Maltese", "mlt", "mt",
"Manx", "glv", "gv",
"Maori", "mao", "mi",
"Marathi", "mar", "mr",
"Marshallese", "mah", "mh",
"Moldavian", "mol", "mo",
"Mongolian", "mon", "mn",
"Nauru", "nau", "na",
"Navaho", "nav", "nv",
"Ndonga", "ndo", "ng",
"Nepali", "nep", "ne",
"Northern Sami", "sme", "se",
"North Ndebele", "nde", "nd",
"Norwegian", "nor", "no",
"Nyanja", "nya", "ny",
"Ojibwa", "oji", "oj",
"Oriya", "ori", "or",
"Oromo", "orm", "om",
"Ossetian", "oss", "os",
"Pali", "pli", "pi",
"Panjabi", "pan", "pa",
"Persian", "per", "fa",
"Polish", "pol", "pl",
"Portuguese", "por", "pt",
"Pushto", "pus", "ps",
"Quechua", "que", "qu",
"Raeto-Romance", "roh", "rm",
"Romanian", "rum", "ro",
"Rundi", "run", "rn",
"Russian", "rus", "ru",
"Samoan", "smo", "sm",
"Sango", "sag", "sg",
"Sanskrit", "san", "sa",
"Sardinian", "srd", "sc",
"Serbian", "scc", "sr",
"Shona", "sna", "sn",
"Sichuan Yi", "iii", "ii",
"Sindhi", "snd", "sd",
"Sinhala", "sin", "si",
"Slovak", "slo", "sk",
"Slovenian", "slv", "sl",
"Somali", "som", "so",
"Spanish", "spa", "es",
"Sundanese", "sun", "su",
"Swahili", "swa", "sw",
"Swedish", "swe", "sv",
"Tagalog", "tgl", "tl",
"Tahitian", "tah", "ty",
"Tajik", "tgk", "tg",
"Tamil", "tam", "ta",
"Tatar", "tat", "tt",
"Telugu", "tel", "te",
"Thai", "tha", "th",
"Tibetan", "tib", "bo",
"Tigrinya", "tir", "ti",
"Tonga", "ton", "to",
"Tsonga", "tso", "ts",
"Tswana", "tsn", "tn",
"Turkish", "tur", "tr",
"Turkmen", "tuk", "tk",
"Twi", "twi", "tw",
"Uighur", "uig", "ug",
"Ukrainian", "ukr", "uk",
"Urdu", "urd", "ur",
"Uzbek", "uzb", "uz",
"Venda", "ven", "ve",
"Vietnamese", "vie", "vi",
"Welsh", "wel", "cy",
"Wolof", "wol", "wo",
"Xhosa", "xho", "xh",
"Yiddish", "yid", "yi",
"Yoruba", "yor", "yo",
"Zulu", "zul", "zu",
};
public static HashMap<String,String> nameToCode6391 = null;
public static HashMap<String,String> nameToCode6392 = null;
public static HashMap<String,String> code6391ToName = null;
public static HashMap<String,String> code6392ToName = null;
public static String getNameFor6391Code(String code) {
if(code == null) return null;
if(code6391ToName == null) initializeHashMaps();
return code6391ToName.get(code.toLowerCase());
}
public static String getNameFor6392Code(String code) {
if(code == null) return null;
if(code6392ToName == null) initializeHashMaps();
return code6392ToName.get(code.toLowerCase());
}
public static String get6391ForName(String name) {
if(name == null) return null;
if(nameToCode6391 == null) initializeHashMaps();
return nameToCode6391.get(name.toLowerCase());
}
public static void initializeHashMaps() {
nameToCode6391 = new HashMap<>();
nameToCode6392 = new HashMap<>();
code6391ToName = new HashMap<>();
code6392ToName = new HashMap<>();
for(int i=0; i<languageNamesAndCodes.length; i=i+3) {
nameToCode6392.put(languageNamesAndCodes[i].toLowerCase(), languageNamesAndCodes[i+1]);
nameToCode6391.put(languageNamesAndCodes[i].toLowerCase(), languageNamesAndCodes[i+2]);
code6391ToName.put(languageNamesAndCodes[i+2], languageNamesAndCodes[i]);
code6392ToName.put(languageNamesAndCodes[i+1], languageNamesAndCodes[i]);
}
}
public static Topic createTopicForLanguageName(String language, TopicMap tm) {
Topic t = null;
if(tm != null) {
try {
t = tm.createTopic();
String code = get6391ForName(language);
if(code == null) code = language.toLowerCase();
t.addSubjectIdentifier(new Locator(XTMPSI.LANG_PREFIX+code));
t.setBaseName(toTitleCase(language) + " language");
t.setDisplayName("en", toTitleCase(language));
t.addType(tm.getTopic(TMBox.LANGUAGE_SI));
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
public static Topic createTopicForLanguageCode(String code, TopicMap tm) {
Topic t = null;
if(tm != null) {
try {
t = tm.createTopic();
String name = getNameFor6391Code(code);
if(name == null) name = code.toLowerCase();
t.addSubjectIdentifier(new Locator(XTMPSI.LANG_PREFIX+code));
t.setBaseName(toTitleCase(name) + " language");
t.setDisplayName("en", toTitleCase(name));
t.addType(tm.getTopic(TMBox.LANGUAGE_SI));
}
catch(Exception e) {
e.printStackTrace();
}
}
return t;
}
public static String getNameForLangTopic(Topic langTopic) {
String langName = null;
if(langTopic != null) {
try {
langName = langTopic.getDisplayName("en");
if(langName != null) {
langName = langName.toLowerCase();
if(nameToCode6391 == null) initializeHashMaps();
if(nameToCode6391.containsKey(langName)) return langName;
}
String langCode = null;
for(Locator l : langTopic.getSubjectIdentifiers()) {
if(l != null) {
if(l.toExternalForm().startsWith(XTMPSI.LANG_PREFIX)) {
langCode = l.toExternalForm().substring(XTMPSI.LANG_PREFIX.length());
langName = code6391ToName.get(langCode);
if(langName != null) break;
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return langName;
}
public static String getCodeForLangTopic(Topic langTopic) {
if(langTopic != null) {
try {
String langName = langTopic.getDisplayName("en");
if(langName != null) {
langName = langName.toLowerCase();
if(nameToCode6391 == null) initializeHashMaps();
if(nameToCode6391.containsKey(langName) ) return nameToCode6391.get(langName);
}
String langCode = null;
for(Locator l : langTopic.getSubjectIdentifiers()) {
if(l != null) {
if(l.toExternalForm().startsWith(XTMPSI.LANG_PREFIX)) {
langCode = l.toExternalForm().substring(XTMPSI.LANG_PREFIX.length());
if(code6391ToName.containsKey(langCode)) return langCode;
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
public static String toTitleCase(String str) {
if(str != null) {
return str.substring(0,1).toUpperCase()+str.substring(1).toLowerCase();
}
return null;
}
}
| 12,304 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
HistoryList.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/sessions/HistoryList.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* HistoryList.java
*
* Created on January 15, 2002, 3:41 PM
*/
package org.wandora.utils.sessions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
*
* @author marko
*/
public class HistoryList {
private int currentIndex = -1;
private List list = new ArrayList();
private int maxSize = 0;
/** Creates new HistoryList */
public HistoryList(int maxS) {
maxSize = maxS;
}
public Boolean add(Object obj, Boolean rmDuplicate) {
if (rmDuplicate == Boolean.TRUE) {
if ((!list.isEmpty()) && (list.lastIndexOf(obj) == list.size()-1)) return (Boolean.FALSE);
}
this.add(obj);
return (Boolean.TRUE);
}
public void add(Object obj) {
List delList;
if (list.size() >= maxSize){
Iterator listItr = list.iterator();
int ind = list.size() - maxSize;
while ((ind > 0) && (listItr.hasNext())) {
listItr.remove();
ind--;
}
}
// if adding in the middle of the list and we are following
// different branch than old then remove old branch
if ((currentIndex < this.lastIndex()) &&
(obj != this.getObjectAt(currentIndex+1))) {
this.removeFrom(currentIndex+1);
}
list.add(obj);
currentIndex++;
if (currentIndex >= list.size()) currentIndex = list.size()-1;
System.out.println("adding object "+currentIndex);
}
public void clear() {
list.clear();
}
public void removeFrom(int index) {
List delList;
if (list.size() > 0) {
while (list.size()-1 >= index) {
list.remove(list.size()-1);
}
if (currentIndex >= list.size()) currentIndex = list.size()-1;
}
}
public int lastIndex() {
return(list.size()-1);
}
public int getCurrentIndex() {
return(currentIndex);
}
public Object getCurrentObject() {
return(list.get(currentIndex));
}
public Object getObjectAt(int index) {
if ((index > 0) && (index < list.size())) return(list.get(index));
return(null);
}
public List getNewest(int size) {
if (size > list.size()) return(list);
if (size > 0) return(list.subList(list.size()-size,list.size()));
return(null);
}
public List getRange(int start, int end) {
if (start < 0) start = 0;
if (end > list.size()) end = list.size();
return(list.subList(start,end));
}
public boolean isEmpty() {
return(list.isEmpty());
}
public void moveBack() {
if (currentIndex > 0) currentIndex--;
System.out.println("Index:"+currentIndex);
}
public void moveForward() {
if (currentIndex < list.size()-1) currentIndex++;
}
public void moveTo(int index) {
if ((index >= 0) && (index < list.size())) currentIndex = index;
}
public void moveToEnd() {
currentIndex = list.size()-1;
}
}
| 4,014 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SessionObject.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/utils/sessions/SessionObject.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*
*
* SessionObject.java
*
* Created on January 21, 2002, 10:56 AM
*/
package org.wandora.utils.sessions;
/**
*
* @author marko
*/
public class SessionObject {
private HistoryList history = null;
private String name = null;
private String id = null;
/** Creates new SessionObject */
public SessionObject(HistoryList sessionHistory, String topicName, String sessionID) {
history = sessionHistory;
name = topicName;
id = sessionID;
}
public HistoryList getHistory() {
return history;
}
public String getID() {
return id;
}
public String getName() {
return name;
}
}
| 1,541 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleListener.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleListener.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
/**
* A listener class that can be attached to a ModuleManager to get
* notifications about changes in module states.
*
* @author olli
*/
public interface ModuleListener {
/**
* Called immediately before a module will be stopped.
* @param module The module to be stopped.
*/
public void moduleStopping(Module module);
/**
* Called after a module has stopped.
* @param module The module that was stopped.
*/
public void moduleStopped(Module module);
/**
* Called when a module is about to be started. The module may or may
* not actually successfully start but it's going to be tried.
* @param module The module that is about to be started.
*/
public void moduleStarting(Module module);
/**
* Called when a module has successfully started.
* @param module The module that was started.
*/
public void moduleStarted(Module module);
}
| 1,762 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
NetAuthenticatorModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/NetAuthenticatorModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.LinkedHashMap;
import java.util.Map;
import org.wandora.utils.MultiNetAuthenticator;
import org.wandora.utils.SimpleNetAuthenticator;
/**
*
* @author olli
*/
public class NetAuthenticatorModule extends AbstractModule {
private static class Login {
public String host;
public String user;
public String password;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Map<String,Login> logins=new LinkedHashMap<String,Login>();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("login.")) {
key=key.substring("login.".length());
int ind=key.indexOf(".");
if(ind<0) continue;
String name=key.substring(0,ind);
key=key.substring(ind+1);
Login l=logins.get(name);
if(l==null){
l=new Login();
logins.put(name,l);
}
String value=e.getValue().toString();
if(key.equalsIgnoreCase("host")) l.host=value;
else if(key.equalsIgnoreCase("user")) l.user=value;
else if(key.equalsIgnoreCase("password")) l.password=value;
}
}
for(Login l : logins.values()){
MultiNetAuthenticator.getInstance().addAuthenticator(new SimpleNetAuthenticator(l.host, l.user, l.password));
}
super.init(manager, settings);
}
}
| 2,537 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
package-info.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/package-info.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* <p>
* This package contains a modular framework for applications and
* services. Most of the core logic of the framework is in the ModuleManager
* class which loads the modules, handles dependencies between them and
* starts and stops them. See its documentation for details on how to start
* using the framework.
* </p>
* <p>
* The application or service built on the framework consists of any number of
* separate modules, which may have dependencies between them. Some of the
* modules typically implement certain interfaces and act as services providers
* for other modules. Then you typically have the modules that interface with
* the outside world and use the services provided by the other modules.
* </p>
* <p>
* A typical use case is a web server where one module hooks into an http web
* server, or even acts as one. The incoming requests can then be forwarded to
* other modules that handle and reply to them. These modules then use other
* service modules, for example a relational database module, to do their work.
* The replies will often be created using a templating language so as to separate
* the logic from the presentation. The templating engine and the templates will
* be modules of their own too.
* <p>
* </p>There are several pre-made modules designed with
* this type of server in mind, but it is by no means the only way to construct
* an application or a service with the framework. The org.wandora.modules.servlet
* package contains several modules which reply to http requests. These are called
* actions and derive from AbstractAction. The same package also contains the
* modules related to templates, currently the only implementation uses
* Apache Velocity but other templating languages could easily be added.
* </p>
* <p>
* Additional documentation is available at http://www.wandora.org/wiki/Wandora_modules_framework
* </p>
*
*/
package org.wandora.modules;
| 2,742 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ScopedModuleManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ScopedModuleManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import javax.script.ScriptException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* <p>
* A module manager that can be placed inside other module managers in
* a hierarchical fashion. Each child module manager can import modules
* from the direct parent manager using import elements. Otherwise, child managers
* are isolated from the parent, or sibling, managers. This makes it practical to
* import module bundles that implement specific features without worry of them
* conflicting with existing modules.
* </p>
* <p>
* The ScopedModuleManager itself is a Module and can be placed in any other
* module manager, scoped or otherwise. Its dependencies will be all the modules
* that are specifically imported into it. All the contained modules that are marked
* for autostart are started when the module manager itself is started and stopped
* when the manager is stopped. The child modules are initialised when the manager
* is initialised.
* </p>
*
*
* @author olli
*/
public class ScopedModuleManager extends ModuleManager implements Module, XMLOptionsHandler {
protected boolean running=false;
protected boolean initialized=false;
protected ModuleManager parentManager;
protected final ArrayList<Import> imports=new ArrayList<Import>();
public ScopedModuleManager() {
}
@Override
public synchronized <A extends Module> A findModule(Module context,String instanceName,Class<A> cls){
A ret=super.findModule(context,instanceName,cls);
if(ret!=null) return ret;
if(parentManager==null) return null;
for(Import im : imports){
if(im.cls.getName().equals(cls.getName())){
return parentManager.findModule(this, instanceName, cls);
}
}
return null;
}
public synchronized <A extends Module> ArrayList<A> findModulesRecursive(Class<A> cls){
ArrayList<A> ret=new ArrayList<A>();
ret.addAll(findModules(cls));
for(ScopedModuleManager smm : findModules(ScopedModuleManager.class)){
ret.addAll(smm.findModulesRecursive(cls));
}
return ret;
}
@Override
public void init(ModuleManager manager, Map<String, Object> parameters) throws ModuleException {
this.parentManager=manager;
initAllModules();
initialized=true;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> ret=new ArrayList<Module>();
for(Import im : imports){
if(im.optional) manager.optionalModule(this, im.cls, ret);
else manager.requireModule(this, im.cls, ret);
}
return ret;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
this.autostartModules();
running=true;
}
@Override
public void stop(ModuleManager manager) {
this.stopAllModules();
running=false;
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public boolean isRunning() {
return running;
}
public void addImport(Import im){
synchronized(imports){
for(Import i : imports){
if(i.cls.getName().equals(im.cls.getName())) {
if(i.optional && !im.optional) i.optional=false;
return;
}
}
imports.add(im);
}
}
public void addImport(Class<? extends Module> cls, boolean optional){
addImport(new Import(cls,optional));
}
protected void parseXMLImport(Element e){
String className=e.getAttribute("class").trim();
String variable=e.getAttribute("variable").trim();
if(parentManager==null) log.warn("Parent manager not set, can't import anything");
if(className.length()==0) {
if(variable.length()==0) {
if(log!=null) log.warn("No class or variable specified in import");
return;
}
else {
setVariable(variable,parentManager.getVariable(variable));
}
}
else {
try{
String optional=e.getAttribute("optional");
Class<?> cls=Class.forName(className);
if(Module.class.isAssignableFrom(cls)){
Import im=new Import((Class<? extends Module>)cls);
if(optional.trim().equalsIgnoreCase("true")) im.optional=true;
addImport(im);
}
else {
if(log!=null) log.warn("Imported class "+className+" is not an instance of Module");
}
}
catch(ClassNotFoundException cnfe){
if(log!=null) log.warn(cnfe);
}
}
}
@Override
public Collection<Module> parseXMLConfigElement(Node doc, String source) {
try{
XPath xpath=XPathFactory.newInstance().newXPath();
NodeList nl=(NodeList)xpath.evaluate("//import",doc,XPathConstants.NODESET);
for(int i=0;i<nl.getLength();i++){
Element e2=(Element)nl.item(i);
parseXMLImport(e2);
}
return super.parseXMLConfigElement(doc, source);
}catch(Exception ex){
if(log!=null) log.error("Error reading options file", ex);
return null;
}
}
@Override
public Map<String, Object> parseXMLOptionsElement(ModuleManager manager, Element e, String source) throws ReflectiveOperationException, ScriptException {
parentManager=manager;
String src=e.getAttribute("src").trim();
if(src.length()>0){
readXMLOptionsFile(src);
}
else {
parseXMLConfigElement(e, source);
}
return super.parseXMLOptionsElement(e);
}
public void setParentManager(ModuleManager manager){
this.parentManager=manager;
}
public static class Import {
public Class<? extends Module> cls;
public boolean optional=false;
public Import(Class<? extends Module> cls,boolean optional){
this.cls=cls;
this.optional=optional;
}
public Import(Class<? extends Module> cls){
this(cls,false);
}
}
}
| 7,648 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractModuleListener.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/AbstractModuleListener.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
/**
* An empty implementation of the ModuleListener interface. You can
* extend this class and then only implement the methods you actually need.
*
* @author olli
*/
public abstract class AbstractModuleListener implements ModuleListener {
public void moduleStarted(Module module) {
}
public void moduleStarting(Module module) {
}
public void moduleStopped(Module module) {
}
public void moduleStopping(Module module) {
}
}
| 1,295 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
MissingDependencyException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/MissingDependencyException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
/**
*
* @author olli
*/
public class MissingDependencyException extends ModuleException {
private static final long serialVersionUID = 1L;
public MissingDependencyException(Class<? extends Module> cls){
this(null,cls,null);
}
public MissingDependencyException(Class<? extends Module> cls,String instanceName){
this(null,cls,instanceName);
}
public MissingDependencyException(String message,Class<? extends Module> cls){
this(message,cls,null);
}
public MissingDependencyException(String message,Class<? extends Module> cls,String instanceName){
super("Missing module dependency class="+cls.getName()+(instanceName==null?"":" instanceName=\""+instanceName+"\""));
}
}
| 1,564 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DefaultReplacementsModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/DefaultReplacementsModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.modules.usercontrol.User;
/**
* A basic implementation of the replacements system. You can add replacements
* in the module parameters using parameter names replacement.key. The every occurrence
* of key is replaced in the text with the value of the parameter. In addition to these
* some default dynamic replacements are available. $DATETIME is replaced with a date
* and time stamp. $USER is replaced with the name of the logged in user, if one is
* available in the context.
*
* @author olli
*/
public class DefaultReplacementsModule extends AbstractModule implements ReplacementsModule {
protected HashMap<String,Replacement> replacements;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
replacements=new HashMap<String,Replacement>();
final SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
replacements.put("$DATETIME",new Replacement(){
@Override
public String replace(String value, String key,HashMap<String,Object> context) {
if(value.indexOf(key)>=0){
String date=dateFormat.format(new Date());
return value.replace(key, date);
}
else return value;
}
});
replacements.put("$USER",new Replacement(){
@Override
public String replace(String value, String key, HashMap<String, Object> context) {
if(value.indexOf(key)>=0){
Object o=context.get("user");
if(o!=null && o instanceof User){
User user=(User)o;
value.replace(key, user.getUserName());
}
}
return value;
}
});
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("replacement.")){
key=key.substring("replacement.".length());
Object o=e.getValue();
if(o==null) {
replacements.remove(key);
}
else {
if(o instanceof Replacement) replacements.put(key,(Replacement)o);
else if(o instanceof String) replacements.put(key,new StringReplacement(o.toString()));
else throw new ModuleException("Invalid replacement value");
}
}
}
super.init(manager, settings);
}
@Override
public String replaceValue(String value,HashMap<String,Object> context) {
if(context==null) context=new HashMap<String,Object>();
for(Map.Entry<String,Replacement> e : replacements.entrySet()){
String key=e.getKey();
Replacement r=e.getValue();
value=r.replace(value, key, context);
}
return value;
}
public static interface Replacement {
public String replace(String value,String key,HashMap<String,Object> context);
}
public static class StringReplacement implements Replacement {
private String repl;
public StringReplacement(String repl){ this.repl=repl; }
public String replace(String value,String key,HashMap<String,Object> context){
return value.replace(key, repl);
}
}
public static class RegexReplacement implements Replacement {
private Pattern pattern;
private String repl;
public RegexReplacement(String pattern,String repl) {
this(Pattern.compile(pattern),repl);
}
public RegexReplacement(Pattern pattern,String repl){
this.pattern=pattern;
this.repl=repl;
}
@Override
public String replace(String value, String key,HashMap<String,Object> context) {
Matcher m=pattern.matcher(value);
return m.replaceAll(repl);
}
}
}
| 5,091 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/AbstractModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.logging.Log;
/**
* A basic implementation of the Module interface. Implements all the methods
* but doesn't do anything useful on its own. The base implementation holds the
* initialisation and running states and does the bare minimum in the init,
* getDependencies, start and stop methods. Typically you will want to override
* at least some of them to add your own logic but still call the base
* implementation too.
*
* @author olli
*/
public abstract class AbstractModule implements Module {
protected boolean isInitialized;
protected boolean isRunning;
protected boolean autoStart;
/**
* A logging module that is set in the requireLogging method. See
* its documentation for more details.
*/
protected LoggingModule loggingModule;
/**
* A Log implementation that is set in the require Logging method. See
* its documentation for more details.
*/
protected Log logging;
/**
* The module manager that handles this module. First set in the init
* method.
*/
protected ModuleManager moduleManager;
public AbstractModule(){
isInitialized=false;
isRunning=false;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
this.moduleManager=manager;
isInitialized=true;
}
/*
@Override
public HashMap<String,Object> saveOptions(){
HashMap<String,Object> ret=new HashMap<String,Object>();
return ret;
}
*/
@Override
public boolean isInitialized() {
return isInitialized;
}
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
return new ArrayList<Module>();
}
/**
* <p>
* A helper method that adds logging into dependencies. Typically you
* will call this in your overridden getDependencies method. After that you
* can use the logging facilities of the logging instance variable.
* AbstractModule does not automatically require logging, but it provides
* some functionality for the typical case where you do need logging.
* </p>
* <p>
* Note that typically modules are not usable before they have been started,
* and the logging module may only have been started just before calling
* start of this module. As such, the module would be unusable before that, in
* particular in init and getDependencies methods. However, logging modules
* should be built in such a way that they are usable immediately
* after having been initialised. In other words, you can assume that you
* can use it as soon as you have a reference to it. You may also call
* requireLogging already in init method to have logging available there.
* You should still also add it to the dependencies later in getDependencies.
* </p>
*
* @param manager
* @param dependencies
* @return
* @throws ModuleException
*/
protected Collection<Module> requireLogging(ModuleManager manager,Collection<Module> dependencies) throws ModuleException {
if(dependencies==null) dependencies=new ArrayList<Module>();
loggingModule=manager.requireModule(this,LoggingModule.class, dependencies);
logging=loggingModule.getLog(this);
return dependencies;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
isRunning=true;
}
@Override
public void stop(ModuleManager manager) {
isRunning=false;
}
/**
* Makes a string representation of this module using ModuleManager.moduleToString.
* @return A string representation of this module.
*/
@Override
public String toString(){
return moduleManager.moduleToString(this);
}
}
| 4,884 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Module.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/Module.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.Collection;
import java.util.Map;
/**
* The interface all modules must implement. Typically you will want to
* extend AbstractModule instead of implementing this directly. It'll contain
* basic implementation for all methods and perform some commonly needed functions.
*
* @author olli
*/
public interface Module {
/**
* <p>
* Initialises the module. After constructor, this is the first method
* called in the life cycle of a module. It should not perform anything
* time consuming or anything with notable outside side effects. It should
* only read the parameters and initialise the module so that it can later
* be started. Note that a module being initialised doesn't mean that it
* necessarily will ever be started.
* </p>
* <p>
* A ModuleException may be thrown if
* something vital is missing from the parameters or they are not sensible.
* In some cases you may not want to throw an exception even if vital
* initialisation information is missing. If, for example, it is possible that
* the module is initialised in some other way between the init and the start
* method calls. A ModuleException may also be thrown at the start method
* if the module is still not initialised.
* </p>
*
* @param manager The module manager handling this module. You may keep a
* reference to it if needed.
* @param parametersThe module parameters parsed from the configuration file.
* @throws ModuleException
*/
public void init(ModuleManager manager,Map<String,Object> parameters) throws ModuleException;
/**
* Returns all the modules this module depends on. This method will be
* called after init and the dependencies are allowed to depend on the
* parameters passed to init. The modules that this module depends on
* must be returned as a collection. In addition, if any required module is
* not present, a MissingDependencyException should be thrown. Typically you
* will use the requireModule and optionalModule methods of the manager to
* make sure that the modules exist and add them to the collection.
* requireModule will automatically throw the exception too if the module is
* not found whereas optionalModule does not.
*
* @param manager The module manager handling this module.
* @return A collection of modules this module depends on.
* @throws ModuleException
*/
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException;
// public HashMap<String,Object> saveOptions();
/**
* Starts the module. This will be called after init and getDependencies
* and signals that the module should now begin to perform whatever it was
* designed to do. This method call however should not block for long, so
* any time consuming tasks should be started in their own threads. You will
* typically get references to the required modules again in start using the
* findModule method of the manager and then store those references to instance
* variables for later use. You may throw a ModuleException if the module
* is not in a state where it can be started or it immediately becomes
* obvious that it cannot be started with the provided settings.
*
* @param manager The module manager handling this module.
* @throws ModuleException
*/
public void start(ModuleManager manager) throws ModuleException;
/**
* Stops the module. Should stop all threads used by the module, free
* any large data structures and perform other cleanup. It is possible that
* the module will be started again later with a start method call (and
* foregoing init and getDependencies calls).
* The module should be left in a state where this is possible.
*
* @param manager The module manager handling this module.
*/
public void stop(ModuleManager manager);
/**
* Checks if the module is initialised. Should return true if init
* has been called and it did not throw an exception.
* @return
*/
public boolean isInitialized();
/**
* Checks if the module is running. Should return true if start has
* been called and it did not throw an exception and stop has not been
* called yet.
* @return
*/
public boolean isRunning();
}
| 5,297 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleGroup.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleGroup.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import javax.script.ScriptException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.wandora.utils.Tuples;
/**
*
* @Deprecated Untested and probably unneeded. ScopedModuleManager can be used
* to group modules.
* @author olli
*/
public class ModuleGroup extends ScriptModule implements XMLOptionsHandler {
protected final ArrayList<Module> childModules=new ArrayList<Module>();
public ModuleGroup(){
}
public void startGroup(boolean withDependencies) throws ModuleException {
synchronized(childModules){
for(Module m : childModules){
if(m instanceof ModuleGroup){
((ModuleGroup)m).startGroup(withDependencies);
}
else {
if(withDependencies) moduleManager.startModuleWithDependencies(m);
else moduleManager.startModule(m);
}
}
}
}
public void stopGroup(boolean cascading) throws ModuleException {
synchronized(childModules){
for(Module m : childModules){
if(m instanceof ModuleGroup){
((ModuleGroup)m).stopGroup(cascading);
}
else {
if(cascading) moduleManager.stopCascading(m);
else moduleManager.stopModule(m);
}
}
}
}
public void addChildModule(Module m){
synchronized(childModules){
childModules.add(m);
}
}
public Collection<Module> getChildModules(){
synchronized(childModules){
return new ArrayList<Module>(childModules);
}
}
public Collection<Module> getChildModulesRecursive(){
synchronized(childModules){
ArrayList<Module> ret=new ArrayList<Module>();
for(Module m : childModules){
ret.add(m);
if(m instanceof ModuleGroup) ret.addAll(getChildModulesRecursive());
}
return ret;
}
}
protected void parseChildModules(ModuleManager manager, Element e, String source) throws ReflectiveOperationException, ScriptException {
XPath xpath=XPathFactory.newInstance().newXPath();
try{
NodeList nl=(NodeList)xpath.evaluate("module",e,XPathConstants.NODESET);
for(int i=0;i<nl.getLength();i++){
Tuples.T3<Module,Map<String,Object>,ModuleManager.ModuleSettings> tuple=manager.parseXMLModuleElement(e,source);
manager.addModule(tuple.e1, tuple.e2, tuple.e3);
addChildModule(tuple.e1);
}
}
catch(XPathExpressionException xpee){
throw new RuntimeException(xpee); // shouldn't happen, hard coded xpath expression
}
}
@Override
public Map<String, Object> parseXMLOptionsElement(ModuleManager manager, Element e, String source) throws ReflectiveOperationException, ScriptException {
parseChildModules(manager, e, source);
return manager.parseXMLOptionsElement(e);
}
}
| 4,244 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
/**
*
* @author olli
*/
public class ModuleException extends Exception {
private static final long serialVersionUID = 1L;
public ModuleException(){
super();
}
public ModuleException(String message){
super(message);
}
public ModuleException(Throwable cause){
super(cause);
}
public ModuleException(String message,Throwable cause){
super(message,cause);
}
}
| 1,254 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
XMLOptionsHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/XMLOptionsHandler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.Map;
import javax.script.ScriptException;
import org.w3c.dom.Element;
/**
* An interface indicating that your module will process the contents of
* the module element instead of relying on the automatic processing of
* ModuleManager. When you implement this interface, ModuleManager will give
* your module a chance to process the contents of the module element on its own
* instead of the module manager parsing the parameters. It's completely up to the
* module then what to do with the contents. However, some common elements, like
* useService elements, should be allowed to still be present and they will still
* be processed by the module manager. Also, any module you derive from may expect
* some parameters, you will have to accommodate these somehow. Note that
* you can still use the parseXMLOptionsElement method in module manager to
* do standard parameters parsing in addition to any custom handling.
*
* @author olli
*/
public interface XMLOptionsHandler {
/**
* Parses the given module element and returns a map containing the
* module parameters. The module parameters will later be passed to your
* module again in init method. You may of course retain parsed information
* outside this map as well and refer to it later in the initialisation.
*
* @param manager The module manager handling this module.
* @param e The module element which is to be parsed.
* @param source The source identifier for the module, could be the file name
* where the module comes from or something else.
* @return The parsed module parameters which will be passed to the init
* method of your module later.
*/
public Map<String,Object> parseXMLOptionsElement(ModuleManager manager,Element e,String source) throws ReflectiveOperationException, ScriptException;
// public void writeXMLOptions(ModuleManager manager,Writer out) throws IOException;
}
| 2,807 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.logging.Log;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.wandora.utils.ListenerList;
import org.wandora.utils.ScriptManager;
import org.wandora.utils.Tuples;
import org.wandora.utils.Tuples.T3;
/**
* <p>
* Main manager for the modules framework. ModuleManager does all the work
* connecting modules with each other, solving dependencies, loading configuration
* and setting up the whole framework.
* </p>
* <p>
* To use this, just make a new instance of ModuleManager and then either load
* a configuration file or add some modules manually, initialise them, and
* finally start the modules. You can also first add some modules manually and
* then load the rest with a configuration file. You typically do this to
* establish some kind of an attachment point for the modules or to add a
* logging module or some such beforehand.
* </p>
* <p>
* You may also add variables before loading the configuration file, these can
* then be used in the configuration file. For example, if you know something
* about the environment, such as the network port the service is running, the
* working directory or something similar, you could add these as variables.
* Then the configuration file can use them instead of having them hardcoded.
* </p>
* <p>
* After adding the modules, you have to initialise them. Initialisation of
* modules needs a map of module properties. If you read the modules from
* a configuration file, the properties will also have been read and are stored
* for later use. When you call initAllModules, all modules that are not yet
* initialised will be initialised with the parameters read from the configuration
* file. Prior to this, you can initialise modules manually if you wish.
* </p>
* <p>
* After initialisation, you need to start the modules. Typically you will call
* autostartModules, which will start all modules that were configured to be
* started automatically. Alternatively, you can also use startAllModules which
* will start every single module that hasn't been started yet. Or you can
* always start modules individually too with startModule or
* startModuleWithDependencies. startModule will throw an exception if the
* dependencies haven't been started yet whereas the other method simply starts
* them too.
* </p>
* http://wandora.orgwiki/Wandora_modules_framework for additional
* documentation about the modules framework.</p>
*
* @author olli
*/
public class ModuleManager {
/**
* A list containing all the modules this manager takes care of.
*/
protected ArrayList<Module> modules;
/**
* Initialisation parameters that will be passed to module init method, read
* from the config file.
*/
protected Map<Module,Map<String,Object>> moduleParams;
/**
* Other settings about modules besides the parameters. Includes things
* like auto restart, priority, name, and explicit services used.
*/
protected Map<Module,ModuleSettings> moduleSettings;
/**
* Logger used by the manager. Can be set with setLog, otherwise it's
* automatically captured by addModule when a logging module is first added.
*/
protected Log log;
protected ListenerList<ModuleListener> moduleListeners;
/**
* Modules that are used by some other running module are put here so that
* they cannot be stopped before the depending module is stopped.
*/
protected Map<Module,ArrayList<Module>> isRequiredBy;
/**
* Variables used in the configuration file.
*/
protected LinkedHashMap<String,String> variables;
public ModuleManager(){
modules=new ArrayList<Module>();
moduleParams=new HashMap<Module,Map<String,Object>>();
moduleListeners=new ListenerList<ModuleListener>(ModuleListener.class);
moduleSettings=new HashMap<Module,ModuleSettings>();
isRequiredBy=new HashMap<Module,ArrayList<Module>>();
variables=new LinkedHashMap<String,String>();
}
/**
* Gets module settings. The settings include everything else about the
* module except the implementation specific parameters. For example,
* module name, autostart status, priority and explicitly specified
* dependencies.
*/
public ModuleSettings getModuleSettings(Module m){
return moduleSettings.get(m);
}
/**
* Checks if module is to be started automatically.
*/
public boolean isModuleAutoStart(Module m){
return moduleSettings.get(m).autoStart;
}
/**
* Gets the module name.
*/
public String getModuleName(Module m){
return moduleSettings.get(m).name;
}
/**
* Add a listener that will be notified about changes in modules in this manager.
*/
public void addModuleListener(ModuleListener l){
moduleListeners.addListener(l);
}
/**
* Removes a previously registered module listener.
*/
public void removeModuleListener(ModuleListener l){
moduleListeners.removeListener(l);
}
/**
* Sets the logging for the module manager itself. Modules will typically
* get a logging module as a dependency instead of using the manager logger
* directly. If no manager logging is set when a logging module is first
* added, that module will automatically be used for manager logging as well.
*/
public void setLogging(Log log){
this.log=log;
}
/**
* Returns the logger used for manager logging. Modules should not use
* this logger, instead they should depend on a logging module and use the
* logging module for logging.
*/
public Log getLogger(){
return this.log;
}
/**
* Returns a list of all modules added to this manager.
*/
public synchronized List<Module> getAllModules(){
ArrayList<Module> ret=new ArrayList<Module>();
ret.addAll(modules);
return ret;
}
/**
* Finds a module that is of the specified class or one extending it.
* Typically you look for modules with an interface and will then get a module
* that implements the interface. In case several such modules exist, the one
* with the highest priority is selected. In case there is a tie, one of them is
* arbitrarily selected.
*
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @return The module found or null if no such module exists.
*/
public synchronized <A extends Module> A findModule(Class<A> cls){
return findModule((String)null,cls);
}
/**
* Finds a module that is of the specified class or one extending it.
* Typically you look for modules with an interface and will then get a module
* that implements the interface. This method takes a module as context, the
* context is the module requesting another module. It may affect what module
* is returned. With the default implementation this will happen if module
* dependencies were explicitly defined in the config file. But in future,
* other selection methods may be added which also depend on the requesting
* module.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @return The module found or null if no such module exists.
*/
public synchronized <A extends Module> A findModule(Module context,Class<A> cls){
ModuleSettings settings=getModuleSettings(context);
return findModule(context,settings.serviceNames.get(cls),cls);
}
/**
* Finds a module that is of the specified class or one extending it.
* Typically you look for modules with an interface and will then get a module
* that implements the interface. This method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @return The module found or null if no such module exists.
* @return
*/
public synchronized <A extends Module> A findModule(Module context,String instanceName,Class<A> cls){
A ret=null;
int best=-1; // do not select automatically anything with a lower priority than 0
if(instanceName!=null) best=Integer.MIN_VALUE; // but with a specified name do
for(Module m : modules){
if(context!=null && m==context) continue;
if(cls.isAssignableFrom(m.getClass())){
String name=getModuleName(m);
if(instanceName==null || (name!=null && instanceName.equals(name)) ){
ModuleSettings settings=getModuleSettings(m);
if(settings.servicePriority>best) {
best=settings.servicePriority;
ret=(A)m;
}
}
}
}
return ret;
}
/**
* Finds a module that is of the specified class or one extending it.
* Typically you look for modules with an interface and will then get a module
* that implements the interface. This method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @return The module found or null if no such module exists.
*/
public synchronized <A extends Module> A findModule(String instanceName,Class<A> cls){
return findModule(null,instanceName,cls);
}
/**
* Finds all modules that are of the specified class or one extending it.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @return The found modules or an empty list if no such modules exist.
*/
public synchronized <A extends Module> ArrayList<A> findModules(Class<A> cls){
ArrayList<A> ret=new ArrayList<A>();
for(Module m : modules){
if(cls.isAssignableFrom(m.getClass())){
ret.add((A) m);
}
}
Collections.sort(ret, new Comparator<A>(){
@Override
public int compare(A o1, A o2) {
ModuleSettings s1=getModuleSettings(o1);
ModuleSettings s2=getModuleSettings(o2);
return s2.servicePriority-s1.servicePriority;
}
});
return ret;
}
/**
* Find a required module and throw a MissingDependencyException if
* one cannot be found. This method is usually used in the getDependencies
* method of modules. If a dependency isn't found, it'll automatically throw
* a suitable exception. If the module i found, it will be added to the
* provided collection which getDependencies needs to return later.
*
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module.
* @throws MissingDependencyException
*/
public synchronized <A extends Module> A requireModule(Class<A> cls,Collection<Module> dependencies) throws MissingDependencyException {
return requireModule((String)null,cls,dependencies);
}
/**
* Find a required module and throw a MissingDependencyException if
* one cannot be found. This method is usually used in the getDependencies
* method of modules. If a dependency isn't found, it'll automatically throw
* a suitable exception. If the module i found, it will be added to the
* provided collection which getDependencies needs to return later. This
* method takes a module as context, the context is the module requesting
* another module. It may affect what module
* is returned. With the default implementation this will happen if module
* dependencies were explicitly defined in the config file. But in future,
* other selection methods may be added which also depend on the requesting
* module.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module.
* @throws MissingDependencyException
*/
public synchronized <A extends Module> A requireModule(Module context,Class<A> cls,Collection<Module> dependencies) throws MissingDependencyException {
ModuleSettings settings=getModuleSettings(context);
return requireModule(context,settings.serviceNames.get(cls),cls,dependencies);
}
/**
* Find a required module and throw a MissingDependencyException if
* one cannot be found. This method is usually used in the getDependencies
* method of modules. If a dependency isn't found, it'll automatically throw
* a suitable exception. If the module i found, it will be added to the
* provided collection which getDependencies needs to return later. This
* method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module.
* @throws MissingDependencyException
*/
public synchronized <A extends Module> A requireModule(Module context,String instanceName, Class<A> cls,Collection<Module> dependencies) throws MissingDependencyException {
Module m=findModule(context,instanceName,cls);
if(m==null) throw new MissingDependencyException(cls,instanceName);
else {
if(!dependencies.contains(m)) dependencies.add(m);
return (A)m;
}
}
/**
* Find a required module and throw a MissingDependencyException if
* one cannot be found. This method is usually used in the getDependencies
* method of modules. If a dependency isn't found, it'll automatically throw
* a suitable exception. If the module i found, it will be added to the
* provided collection which getDependencies needs to return later. This
* method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module.
* @throws MissingDependencyException
*/
public synchronized <A extends Module> A requireModule(String instanceName, Class<A> cls,Collection<Module> dependencies) throws MissingDependencyException {
return requireModule((Module)null,instanceName,cls,dependencies);
}
/**
* Look for a module that will be used if found but is not required.
* Unlike requireModule, no exception is thrown if the module is not found.
* If it is found, then this method behaves like requireModule and the
* module is added in the provided dependencies collection as well as returned
* from the method.
*
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module or null if one cannot be found.
*/
public synchronized <A extends Module> A optionalModule(Class<A> cls,Collection<Module> dependencies) {
return optionalModule((String)null,cls,dependencies);
}
/**
* Look for a module that will be used if found but is not required.
* Unlike requireModule, no exception is thrown if the module is not found.
* If it is found, then this method behaves like requireModule and the
* module is added in the provided dependencies collection as well as returned
* from the method. This method takes a module as context, the context is
* the module requesting another module. It may affect what module
* is returned. With the default implementation this will happen if module
* dependencies were explicitly defined in the config file. But in future,
* other selection methods may be added which also depend on the requesting
* module.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module or null if one cannot be found.
*/
public synchronized <A extends Module> A optionalModule(Module context,Class<A> cls,Collection<Module> dependencies) {
ModuleSettings settings=getModuleSettings(context);
return optionalModule(context,settings.serviceNames.get(cls),cls,dependencies);
}
/**
* Look for a module that will be used if found but is not required.
* Unlike requireModule, no exception is thrown if the module is not found.
* If it is found, then this method behaves like requireModule and the
* module is added in the provided dependencies collection as well as returned
* from the method. This method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param context The module which is requesting the module. This may affect
* what module is returned.
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module or null if one cannot be found.
*/
public synchronized <A extends Module> A optionalModule(Module context,String instanceName,Class<A> cls,Collection<Module> dependencies) {
Module m=findModule(context,instanceName, cls);
if(m==null) return null;
else {
if(!dependencies.contains(m)) dependencies.add(m);
return (A)m;
}
}
/**
* Look for a module that will be used if found but is not required.
* Unlike requireModule, no exception is thrown if the module is not found.
* If it is found, then this method behaves like requireModule and the
* module is added in the provided dependencies collection as well as returned
* from the method. This method takes the name of the module
* requested. No other module will be returned except the module named such.
*
* @param instanceName The instance name of the requested module.
* @param cls The class or interface that the module has to implement or extend or
* be a direct instance of.
* @param dependencies The collection where all dependencies are gathered and
* where the found module is added.
* @return The found module or null if one cannot be found.
*/
public synchronized <A extends Module> A optionalModule(String instanceName,Class<A> cls,Collection<Module> dependencies) {
return optionalModule((Module)null,instanceName,cls,dependencies);
}
public synchronized <A extends Module> ArrayList<A> optionalModules(Class<A> cls,Collection<Module> dependencies) {
ArrayList<A> ms=findModules(cls);
for(A m : ms){
if(!dependencies.contains(m)) dependencies.add(m);
}
return ms;
}
/**
* Adds a module to this manager with default settings and no module
* parameters.
* @param module The module to be added.
*/
public void addModule(Module module){
addModule(module,new HashMap<String,Object>(),new ModuleSettings());
}
/**
* Adds a module to this manager with default settings and no module
* parameters but with the provided name.
* @param module The module to be added.
* @param name The module name;
*/
public void addModule(Module module,String name){
ModuleSettings settings=new ModuleSettings();
settings.name=name;
addModule(module,new HashMap<String,Object>(),settings);
}
/**
* Adds a module to this manager with the given module settings but
* empty module parameters. Settings are general module settings, like
* module name, priority etc. whereas module parameters are module options
* specific to the implementation and used only by the module, not the module
* manager.
*
* @param module The module to be added.
* @param settings The settings for the module.
*/
public void addModule(Module module,ModuleSettings settings){
addModule(module,new LinkedHashMap<String,Object>(),settings);
}
/**
* Adds a module to this manager with the given module parameters and
* default settings. Settings are general module settings, like
* module name, priority etc. whereas module parameters are module options
* specific to the implementation and used only by the module, not the module
* manager.
*
* @param module The module to be added.
* @param params The module parameters.
*/
public synchronized void addModule(Module module,Map<String,Object> params){
addModule(module,params,new ModuleSettings());
}
/**
* Adds a module to this manager with the given module parameters and
* settings. Settings are general module settings, like
* module name, priority etc. whereas module parameters are module options
* specific to the implementation and used only by the module, not the module
* manager.
*
* @param module The module to be added.
* @param params The module parameters.
* @param settings The module settings.
*/
public synchronized void addModule(Module module,Map<String,Object> params,ModuleSettings settings){
if(log==null && module instanceof LoggingModule){
try{
module.init(this, params);
}catch(ModuleException me){
me.printStackTrace();
}
log=((LoggingModule)module).getLog("ModuleManager");
}
modules.add(module);
moduleParams.put(module,params);
moduleSettings.put(module, settings);
if(log!=null) log.info("Adding module "+moduleToString(module));
}
/**
* Removes a module from the manager. Tries to stop the module first if
* it is running. This can potentially lead to different kinds of exceptions,
* notably a ModuleInUseException if some other module is using the module
* being removed.
*
* @param module The module to be removed.
* @throws ModuleInUseException
*/
public synchronized void removeModule(Module module) throws ModuleException {
if(log!=null) log.info("Removing module "+moduleToString(module));
stopModule(module);
modules.remove(module);
moduleParams.remove(module);
moduleSettings.remove(module);
}
/**
* Creates a string representation of a module class. Mostly intended for
* debugging and logging.
*
* @param cls The class of the module.
* @param instanceName The instance name of the module or null.
* @return
*/
public String moduleToString(Class<?> cls,String instanceName){
return cls.getSimpleName()+(instanceName==null?"":"("+instanceName+")");
}
/**
* Creates a string representation of a module. Mostly intended for
* debugging and logging.
*
* @param module The module.
* @return
*/
public String moduleToString(Module module){
String name=getModuleName(module);
return module.getClass().getSimpleName()+(name==null?"":"("+name+")");
}
/**
* Initialises all modules that have not yet been initialised. If the
* module information was read from a configuration file along with module
* parameters, those parameters will be used for the initialisation.
*
* @throws ModuleException
*/
public synchronized void initAllModules() throws ModuleException {
for(Module m : modules){
try{
if(!m.isInitialized()) {
if(log!=null) log.info("Initializing module "+moduleToString(m));
m.init(this, moduleParams.get(m));
}
}
catch(ModuleException me){
if(log!=null) log.warn("Couldn't initialize module "+moduleToString(m),me);
}
}
}
/**
* Starts all modules that have not yet been started and that were set to
* start automatically in module settings. Will also start all the
* dependencies of such modules, even if they themselves were not set to be
* started automatically.
*/
public void autostartModules() throws ModuleException {
autostartModules(modules);
}
/**
* In a given modules collection, starts all modules that have not
* yet been started and that were set to start automatically in module
* settings. Will also start all the
* dependencies of such modules, even if they themselves were not set to be
* started automatically.
*/
public synchronized void autostartModules(Collection<Module> modules) throws ModuleException {
initAllModules();
for(Module m : modules){
try{
if(!m.isRunning()) {
if(isModuleAutoStart(m)){
startModuleWithDependencies(m);
}
}
}
catch(ModuleException me){
if(log!=null) log.warn("Couldn't autostart module "+moduleToString(m),me);
}
}
}
/**
* Starts all modules that have not yet been started.
*/
public synchronized void startAllModules() throws ModuleException {
initAllModules();
for(Module m : modules){
try{
if(!m.isRunning()) {
startModuleWithDependencies(m);
}
}
catch(ModuleException me){
if(log!=null) log.warn("Couldn't start module "+moduleToString(m),me);
}
}
}
/**
* Stops all running modules.
*/
public synchronized void stopAllModules(){
for(Module m : modules){
try{
if(m.isRunning()) {
stopCascading(m);
}
}
catch(ModuleException me){
if(log!=null) log.warn("Couldn't stop module "+moduleToString(m),me);
}
}
}
/**
* Stops a single module along with all modules that depend on it.
* @param module The module to be stopped.
*/
public synchronized void stopCascading(Module module) throws ModuleException {
if(!module.isRunning()) return;
ArrayList<Module> req=isRequiredBy.get(module);
if(req!=null){
while(!req.isEmpty()){ // do this way to avoid concurrent modification
Module r=req.get(req.size()-1);
stopCascading(r);
}
}
stopModule(module);
}
/**
* Stops a single module, but fails if other modules depend on it. A
* ModuleInUseException will be throw if some other running module depends on
* the module to be stopped.
*
* @param module The module to be stopped.
* @throws ModuleException
*/
public synchronized void stopModule(Module module) throws ModuleException {
if(!module.isRunning()) return;
ArrayList<Module> req=isRequiredBy.get(module);
if(req==null || req.isEmpty()) {
if(log!=null) log.info("Stopping module "+moduleToString(module));
moduleListeners.fireEvent("moduleStopping", module);
module.stop(this);
if(!module.isRunning()){
moduleListeners.fireEvent("moduleStopped", module);
Collection<Module> deps=module.getDependencies(this);
for(Module dep : deps){
ArrayList<Module> r=isRequiredBy.get(dep);
r.remove(module);
}
}
else {
if(log!=null) log.warn("Stopped module but isRunning is true "+moduleToString(module));
}
}
else throw new ModuleInUseException(req);
}
/**
* Starts a module as well as all modules it depends on.
*
* @param module The module to be started.
* @throws ModuleException
*/
public synchronized void startModuleWithDependencies(Module module) throws ModuleException {
// TODO: Proper cyclic dependency detection so that we don't get a stack
// overflow in such a case.
if(!module.isInitialized()) module.init(this, moduleParams.get(module));
if(module.isRunning()) return;
Collection<Module> deps=module.getDependencies(this);
for(Module dep : deps){
if(!dep.isRunning()) startModuleWithDependencies(dep);
}
startModule(module);
}
/**
* Starts a module. If any dependencies haven't yet been started, will throw
* a MissingDependencyException. use startModuleWithDependencies to
* automatically start all dependencies as well.
*
* @param module The module to be started.
* @throws ModuleException
*/
public synchronized void startModule(Module module) throws ModuleException {
if(!module.isInitialized()) module.init(this, moduleParams.get(module));
if(module.isRunning()) return;
Collection<Module> deps=module.getDependencies(this);
for(Module dep : deps){
if(!dep.isRunning()) throw new MissingDependencyException(dep.getClass(),getModuleName(dep));
}
if(log!=null) log.info("Starting module "+moduleToString(module));
moduleListeners.fireEvent("moduleStarting", module);
module.start(this);
if(module.isRunning()){
moduleListeners.fireEvent("moduleStarted", module);
for(Module dep : deps){
ArrayList<Module> l=isRequiredBy.get(dep);
if(l==null) {
l=new ArrayList<Module>();
isRequiredBy.put(dep,l);
}
l.add(module);
}
}
else{
if(log!=null) log.warn("Started module but isRunning is false "+moduleToString(module));
}
}
/*
// Note that these two methods have several problems. They don't handle
// parameters that are not simple Strings. They also mess up ordering
// of elements which may in some cases be significant. They are also
// a bit outdated and don't handle variables and some other newer
// things at all.
public static void writeXMLOptions(Writer out,HashMap<String,Object> options) throws IOException {
for(Map.Entry<String,Object> e : options.entrySet()){
Object valueO=e.getValue();
if(valueO==null) continue;
String value=valueO.toString();
value=value.replace("&","&");
value=value.replace("<","<");
out.write("\t\t<param key=\""+e.getKey()+"\">"+value+"</param>\n");
}
}
public void writeXMLOptionsFile(String writeFileName){
try{
OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(writeFileName),"UTF-8");
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
out.write("<options>\n");
ArrayList<Module> modules=getAllModules();
for(Module m : modules){
out.write("\t<module class=\""+m.getClass().getName()+"\" autostart=\""+m.isAutoStart()+"\">\n");
HashMap<String,Object> options=m.saveOptions();
writeXMLOptions(out,options);
out.write("\t</module>\n\n");
}
out.write("</options>");
out.close();
}catch(IOException ioe){
if(log!=null) log.error("Unable to save options file.",ioe);
}
}
*/
/**
* Parses a single param element and returns its value. Handles all the
* different cases of how a param elements value can be determined.
*
* @param e The xml param element.
* @return The value of the parameter.
*/
public Object parseXMLParamElement(Element e) throws ReflectiveOperationException, IllegalArgumentException, ScriptException {
String instance=e.getAttribute("instance");
if(instance!=null && instance.length()>0){
Class cls=Class.forName(instance);
Map<String,Object> params=parseXMLOptionsElement(e);
if(!params.isEmpty()){
Collection<Object> constructorParams=params.values();
Constructor[] cs=cls.getConstructors();
ConstructorLoop: for(int i=0;i<cs.length;i++){
Constructor c=cs[i];
Class[] paramTypes=c.getParameterTypes();
if(paramTypes.length!=constructorParams.size()) continue;
int j=-1;
for(Object o : constructorParams){
j++;
if(o==null) {
if(!paramTypes[j].isPrimitive()) continue;
else continue ConstructorLoop;
}
if(paramTypes[j].isPrimitive()){
if(paramTypes[j]==int.class){ if(o.getClass()!=Integer.class) continue ConstructorLoop; }
else if(paramTypes[j]==long.class){ if(o.getClass()!=Long.class) continue ConstructorLoop; }
else if(paramTypes[j]==double.class){ if(o.getClass()!=Double.class) continue ConstructorLoop; }
else if(paramTypes[j]==float.class){ if(o.getClass()!=Float.class) continue ConstructorLoop; }
else if(paramTypes[j]==byte.class){ if(o.getClass()!=Byte.class) continue ConstructorLoop; }
else continue ConstructorLoop; //did we forget some primitive type?
}
else if(!o.getClass().isAssignableFrom(paramTypes[j])) continue ConstructorLoop;
}
return c.newInstance(constructorParams.toArray());
}
throw new NoSuchMethodException("Couldn't find a constructor that matches parameters parsed from XML.");
}
else {
return cls.getDeclaredConstructor().newInstance();
}
}
String clas=e.getAttribute("class");
if(clas!=null && clas.length()>0){
Class cls=Class.forName(clas);
return cls;
}
if(e.hasAttribute("null")) return null;
if(e.hasAttribute("script")){
String engine=e.getAttribute("script");
if(engine.length()==0 || engine.equalsIgnoreCase("default")) engine=ScriptManager.getDefaultScriptEngine();
ScriptManager scriptManager=new ScriptManager();
ScriptEngine scriptEngine=scriptManager.getScriptEngine(engine);
scriptEngine.put("moduleManager",this);
scriptEngine.put("element",e);
try{
String script=((String)xpath.evaluate("text()",e,XPathConstants.STRING)).trim();
return scriptManager.executeScript(script, scriptEngine);
}catch(XPathExpressionException xpee){ throw new RuntimeException(xpee); }
}
if(e.hasAttribute("module")){
String moduleName=e.getAttribute("module").trim();
return new ModuleDelegate(this,moduleName);
}
try{
String value=((String)xpath.evaluate("text()",e,XPathConstants.STRING)).trim();
return replaceVariables(value, variables);
}catch(XPathExpressionException xpee){ throw new RuntimeException(xpee); }
}
private static XPath xpath=null;
/**
* Reads all the options inside the module element. Currently only
* processing params elements but in the future could handle other elements
* too.
*
* @param e The module element contents of which are to be processed.
* @return The parameters defined in the element.
* @throws ReflectiveOperationException
* @throws ScriptException
*/
public Map<String,Object> parseXMLOptionsElement(Element e) throws ReflectiveOperationException, ScriptException {
if(xpath==null) xpath=XPathFactory.newInstance().newXPath();
LinkedHashMap<String,Object> params=new LinkedHashMap<String,Object>();
try{
NodeList nl2=(NodeList)xpath.evaluate("param",e,XPathConstants.NODESET);
for(int j=0;j<nl2.getLength();j++){
Element e2=(Element)nl2.item(j);
String key=e2.getAttribute("key");
Object value=parseXMLParamElement(e2);
if(key!=null && value!=null) params.put(key.trim(), value);
}
}catch(XPathExpressionException xpee){
throw new RuntimeException(xpee); // hardcoded xpath expressions so this shouldn't really happen
}
return params;
}
/**
* Reads module settings from a module element. The settings include
* autostarting, priority, name read from attributes of the element
* and useService elements defined inside the module element.
*
* @param e The module element.
* @param source The source identifier for the module, could be the file name
* where the module comes from or something else.
* @return Parsed module settings.
* @throws ClassNotFoundException
*/
public static ModuleSettings parseXMLModuleSettings(Element e,String source) throws ClassNotFoundException {
if(xpath==null) xpath=XPathFactory.newInstance().newXPath();
ModuleSettings settings=new ModuleSettings();
String autostartS=e.getAttribute("autostart");
if(autostartS!=null && autostartS.equalsIgnoreCase("false")) settings.autoStart=false;
else settings.autoStart=true;
String priorityS=e.getAttribute("priority");
if(priorityS!=null && priorityS.length()>0) settings.servicePriority=Integer.parseInt(priorityS);
String name=e.getAttribute("name");
if(name!=null && name.length()>0) settings.name=name;
settings.source=source;
try{
NodeList nl=(NodeList)xpath.evaluate("useService",e,XPathConstants.NODESET);
for(int j=0;j<nl.getLength();j++){
Element e2=(Element)nl.item(j);
String service=e2.getAttribute("service");
String value=e2.getAttribute("value");
Class serviceClass=Class.forName(service);
if(!Module.class.isAssignableFrom(serviceClass)){
throw new ClassCastException("The specified service is not a module");
}
settings.serviceNames.put((Class<? extends Module>)serviceClass,value);
}
}catch(XPathExpressionException xpee){
throw new RuntimeException(xpee); // hardcoded xpath expressions so this shouldn't really happen
}
return settings;
}
/**
* Reads a module element and returns the module, its module
* parameters and module settings. Basically handles everything about
* a module element.
*
* @param e The module element.
* @param source The source identifier for the module, could be the file name
* where the module comes from or something else.
* @return A tuple containing the module itself, parsed module parameters
* and parsed module settings.
* @throws ReflectiveOperationException
* @throws ScriptException
*/
public T3<Module,Map<String,Object>,ModuleSettings> parseXMLModuleElement(Element e,String source) throws ReflectiveOperationException, ScriptException {
String moduleClass=e.getAttribute("class");
Module module=(Module)Class.forName(moduleClass).getDeclaredConstructor().newInstance();
Map<String,Object> params;
if(module instanceof XMLOptionsHandler){
params=((XMLOptionsHandler)module).parseXMLOptionsElement(this,e,source);
}
else {
params=parseXMLOptionsElement(e);
}
ModuleSettings settings=parseXMLModuleSettings(e,source);
return Tuples.t3(module,params,settings);
}
/**
* Gets the value of a defined variable. The variable may have been
* defined explicitly with setVariable or parsed from a configuration
* file.
*
* @param key The name of the variable.
* @return The value of the variable or null if it is undefined.
*/
public String getVariable(String key){
return variables.get(key);
}
/**
* Performs variable replacement on a string. All occurrences of
* "${variableName}" where variableName is a defined variable will be
* replaced with the value of the variable.
*
* @param value The string in which variable replacement will be done.
* @param variables A map containing all the defined variables.
* @return
*/
public String replaceVariables(String value,HashMap<String,String> variables){
for(Map.Entry<String,String> e : variables.entrySet()){
value=value.replace("${"+e.getKey()+"}", e.getValue());
}
return value;
}
/**
* Sets a variable. Use null value to remove a variable definition. Will
* overwrite old value if the variable had already been set.
*
* @param key The name of the variable to set.
* @param value The value of the variable or null to remove the definition.
*/
public void setVariable(String key,String value){
if(value==null) variables.remove(key);
else variables.put(key,value);
}
/**
* Parses a variable element and defines that variable for future use.
*
* @param e The variable element.
* @param variables The variable map into which the variable is defined.
*/
public void parseXMLVariable(Element e,HashMap<String,String> variables){
if(xpath==null) xpath=XPathFactory.newInstance().newXPath();
try{
String key=e.getAttribute("key");
String value=((String)xpath.evaluate("text()",e,XPathConstants.STRING)).trim();
value=replaceVariables(value,variables);
setVariable(key,value);
}catch(XPathExpressionException xpee){
throw new RuntimeException(xpee); // hardcoded xpath expressions so this shouldn't really happen
}
}
/**
* Parses an handles include element. This may add a large number of modules
* or do other changes in the module manager.
*
* @param e The include element.
* @return A list of all the modules added.
*/
public Collection<Module> parseXMLInclude(Element e){
ArrayList<Module> ret=new ArrayList<Module>();
String src=e.getAttribute("src").trim();
if(src.length()>0) ret.addAll(readXMLOptionsFile(src));
return ret;
}
/**
* Parses an XML element as if it was the root element of
* a full configuration file. Creates all the modules
* defined in the element. Also sets whatever variables are defined and
* uses those when parsing the rest of the element.
*
* @param doc The element which contains the config definitions.
* @param source The source identifier, e.g. file name, where this element
* came from.
* @return A list of all the modules added.
*/
public Collection<Module> parseXMLConfigElement(Node doc,String source){
try{
ArrayList<Module> ret=new ArrayList<Module>();
xpath=XPathFactory.newInstance().newXPath();
NodeList nl=(NodeList)xpath.evaluate("//variable",doc,XPathConstants.NODESET);
for(int i=0;i<nl.getLength();i++){
Element e=(Element)nl.item(i);
parseXMLVariable(e,variables);
}
nl=(NodeList)xpath.evaluate("//include",doc,XPathConstants.NODESET);
for(int i=0;i<nl.getLength();i++){
Element e=(Element)nl.item(i);
ret.addAll(parseXMLInclude(e));
}
nl=(NodeList)xpath.evaluate("//module",doc,XPathConstants.NODESET);
for(int i=0;i<nl.getLength();i++){
Element e=(Element)nl.item(i);
T3<Module,Map<String,Object>,ModuleSettings> parsed=parseXMLModuleElement(e,source);
addModule(parsed.e1,parsed.e2,parsed.e3);
}
/*
Modules are added to ret here instead of adding parsed.e1 in the previous
loop because a single module element may in some cases result in
multiple modules being added to the manager. This can happen, for
example, if the module implements XMLOptionsHandler and then adds
other modules in there.
*/
for(Module m : modules) {
ModuleSettings settings=getModuleSettings(m);
if(settings!=null && settings.source!=null && settings.source.equals(source))
ret.add(m);
}
return ret;
}catch(Exception ex){
if(log!=null) log.error("Error reading options file", ex);
return null;
}
}
/**
* Reads and parses a whole xml configuration file. Creates all the modules
* defined in the file. Also sets whatever variables are defined in the file and
* uses those when parsing the rest of the file.
*
* @param optionsFileName
* @return A list of all the modules added.
*/
public Collection<Module> readXMLOptionsFile(String optionsFileName){
try{
DocumentBuilderFactory docBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder=docBuilderFactory.newDocumentBuilder();
Node doc=docBuilder.parse(new File(optionsFileName));
return parseXMLConfigElement(doc,optionsFileName);
}catch(Exception e){
if(log!=null) log.error("Error reading options file", e);
return null;
}
}
/**
* A class that contains all the different module settings. Module
* settings are attributes the module manager itself uses. These do not
* include the module parameters which are attributes the module uses to
* initialise itself.
*/
public static class ModuleSettings {
public ModuleSettings() {
}
public ModuleSettings(boolean autoStart) {
this.autoStart=autoStart;
}
public ModuleSettings(String name){
this.name=name;
}
public ModuleSettings(String name,boolean autoStart,int servicePriority, HashMap<Class<? extends Module>,String> serviceNames){
this.name=name;
this.autoStart=autoStart;
this.servicePriority=servicePriority;
if(serviceNames!=null) this.serviceNames=serviceNames;
}
/**
* The explicitly defined dependencies.
*/
public HashMap<Class<? extends Module>,String> serviceNames=new HashMap<Class<? extends Module>,String>();
/**
* Module priority when used as a service.
*/
public int servicePriority=0;
/**
* Whether to autostart the module.
*/
public boolean autoStart=true;
/**
* Module name.
*/
public String name=null;
/**
* The source where this module came from. Could be a file name
* or some other identifier.
*/
public String source=null;
}
}
| 52,187 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ScriptModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ScriptModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.HashMap;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.wandora.utils.ScriptManager;
/**
* <p>
* A base module implementation that adds some scripting functionality
* into the module. Most of the other modules derive from this instead of from
* AbstractModule directly, and it may be a good idea for you to do so as well,
* even if you don't immediately need any of the scripting functions. By deriving
* from ScriptModule, you can later add scripts in the configuration file that
* are executed when your module is initialised, started or stopped.
* </p>
* <p>
* To add scripts in the configuration file, define them in parameters with names
* startScript, stopScript or initScript. The scripts will then be ran at module
* start, stop or init, respectively. You may also specify the script engine to
* use with scriptEngine parameter, otherwise the default engine will be used,
* which is probably Mozilla Rhino ECMA Script.
* </p>
* <p>
* Some variables are added to the script's environment before it's executed.
* moduleManager will contain the module manager, scriptModule contains this
* module object and persistentObjects contains a HashMap where you can
* store any other objects you would like to refer to later. The persistentObjects
* is created at module init and will not be cleared during the lifetime of the
* module. However, the objects stored in there are not saved to disk or any
* other persistent storage, they are persistent only during the lifetime of the
* module object.
* </p>
*
* @author olli
*/
public class ScriptModule extends AbstractModule {
protected String engine;
protected String startScript;
protected String stopScript;
protected String initScript;
protected ScriptManager scriptManager;
protected HashMap<String,Object> persistentObjects;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("scriptEngine");
if(o!=null) engine=o.toString();
o=settings.get("startScript");
if(o!=null) startScript=o.toString();
o=settings.get("stopScript");
if(o!=null) stopScript=o.toString();
o=settings.get("initScript");
if(o!=null) initScript=o.toString();
persistentObjects=new HashMap<String,Object>();
if(initScript!=null){
try{
ScriptEngine scriptEngine=getScriptEngine();
scriptEngine.put("settings",settings);
scriptManager.executeScript(initScript, scriptEngine);
}catch(ScriptException se){
throw new ModuleException(se);
}
}
super.init(manager, settings);
}
protected ScriptEngine getScriptEngine(){
if(scriptManager==null) scriptManager=new ScriptManager();
ScriptEngine scriptEngine=scriptManager.getScriptEngine(engine==null?ScriptManager.getDefaultScriptEngine():engine);
scriptEngine.put("moduleManager", moduleManager);
scriptEngine.put("persistentObjects", persistentObjects);
scriptEngine.put("scriptModule", this);
return scriptEngine;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(startScript!=null){
try{
scriptManager.executeScript(startScript, getScriptEngine());
}catch(ScriptException se){
throw new ModuleException(se);
}
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
if(stopScript!=null){
try{
scriptManager.executeScript(stopScript, getScriptEngine());
}catch(ScriptException se){
logging.warn(se);
}
}
super.stop(manager);
}
}
| 4,844 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleInUseException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleInUseException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.List;
/**
*
* @author olli
*/
public class ModuleInUseException extends ModuleException {
private static final long serialVersionUID = 1L;
public ModuleInUseException(List<Module> modules){
this(null,modules);
}
public ModuleInUseException(String message,List<Module> modules){
super("Module is in use "+modules+". "+(message!=null?message:""));
}
}
| 1,231 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
LoggingModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/LoggingModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.SimpleLog;
/**
* <p>
* A module that provides logging facilities for other modules. Logging
* modules should follow a slightly different life cycle to other modules. This
* is because logging might be needed already in the init or getDependencies
* phase of modules while module functions typically become available only after
* the module has been started. You should initialise the logging into a state
* where it can be fully used already in the init method.
* </p>
* <p>
* This default implementation supports two initialisation parameters. First
* parameter is "log", you can use this to specify the logging mechanism that should
* be used. This should be an instance of org.apache.commons.logging.Log. If
* not specified, the logger of the module manager is used, and if that is not
* specified either, a SimpleLog is created which outputs messages to stderr.
* </p>
* <p>
* You may use the logLevel initialisation parameter to set the lowest level of
* logging messages that are printed. Messages of lower level than this are
* simple ignored. The possible values for this are trace, debug, info, warn,
* error, fatal and none. None is used to suppress logging entirely while providing
* a logging module for other modules that require it. The default log level
* is trace, i.e. all logging messages are printed. However, bear in mind that
* the underlying logger may have its own mechanisms to further filter logging
* messages. Thus even if this LoggingModule is set to print all messages, the
* logging level may be filtered to a higher level elsewhere. This is dependent
* on the logging implementation used.
* </p>
*
* @author olli
*/
public class LoggingModule extends AbstractModule {
protected Log log;
protected int logLevel=SubLog.LOG_TRACE;
public LoggingModule(){
}
public LoggingModule(Log log){
this.log=log;
}
public Log getLog(){
return log;
}
public Log getLog(Module module){
String name=module.toString();
return new SubLog(name+" - ",log);
}
public Log getLog(String moduleName){
return new SubLog(moduleName+" - ",log);
}
public static Log getLog(String moduleName,Log log){
return new SubLog(moduleName+" - ",log);
}
public int getLogLevel(){
return logLevel;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=null;
o=settings.get("log");
if(o!=null && o instanceof Log) log=(Log)o;
if(log==null) log=manager.getLogger();
if(log==null) log=new SimpleLog("log");
o=settings.get("logLevel");
if(o!=null){
String s=o.toString().trim().toLowerCase();
if(s.equals("all") || s.equals("trace")) logLevel=SubLog.LOG_TRACE;
else if(s.equals("debug")) logLevel=SubLog.LOG_DEBUG;
else if(s.equals("info")) logLevel=SubLog.LOG_INFO;
else if(s.equals("warn") || s.equals("warning")) logLevel=SubLog.LOG_WARN;
else if(s.equals("error")) logLevel=SubLog.LOG_ERROR;
else if(s.equals("fatal")) logLevel=SubLog.LOG_FATAL;
else if(s.equals("none")) logLevel=SubLog.LOG_NONE;
if(logLevel>SubLog.LOG_TRACE) log=new SubLog("",log,logLevel);
}
super.init(manager,settings);
}
public static class SubLog implements Log {
protected Log log;
protected String prefix;
public static final int LOG_ALL=0;
public static final int LOG_TRACE=0;
public static final int LOG_DEBUG=1;
public static final int LOG_INFO=2;
public static final int LOG_WARN=3;
public static final int LOG_ERROR=4;
public static final int LOG_FATAL=5;
public static final int LOG_NONE=6;
protected int logLevel=LOG_TRACE;
public SubLog(String prefix,Log log,int logLevel){
this.logLevel=logLevel;
this.prefix=prefix;
this.log=log;
}
public SubLog(String prefix,Log log){
this.prefix=prefix;
this.log=log;
}
public void debug(Object arg0) {
if(logLevel<=LOG_DEBUG) log.debug(prefix+arg0);
}
public void debug(Object arg0, Throwable arg1) {
if(logLevel<=LOG_DEBUG) log.debug(prefix+arg0,arg1);
}
public void error(Object arg0) {
if(logLevel<=LOG_ERROR) log.error(prefix+arg0);
}
public void error(Object arg0, Throwable arg1) {
if(logLevel<=LOG_ERROR) log.error(prefix+arg0,arg1);
}
public void fatal(Object arg0) {
if(logLevel<=LOG_FATAL) log.fatal(prefix+arg0);
}
public void fatal(Object arg0, Throwable arg1) {
if(logLevel<=LOG_FATAL) log.fatal(prefix+arg0,arg1);
}
public void info(Object arg0) {
if(logLevel<=LOG_INFO) log.info(prefix+arg0);
}
public void info(Object arg0, Throwable arg1) {
if(logLevel<=LOG_INFO) log.info(prefix+arg0,arg1);
}
public boolean isDebugEnabled() {
return logLevel<=LOG_DEBUG && log.isDebugEnabled();
}
public boolean isErrorEnabled() {
return logLevel<=LOG_ERROR && log.isErrorEnabled();
}
public boolean isFatalEnabled() {
return logLevel<=LOG_FATAL && log.isFatalEnabled();
}
public boolean isInfoEnabled() {
return logLevel<=LOG_INFO && log.isInfoEnabled();
}
public boolean isTraceEnabled() {
return logLevel<=LOG_TRACE && log.isTraceEnabled();
}
public boolean isWarnEnabled() {
return logLevel<=LOG_WARN && log.isWarnEnabled();
}
public void trace(Object arg0) {
if(logLevel<=LOG_TRACE) log.trace(prefix+arg0);
}
public void trace(Object arg0, Throwable arg1) {
if(logLevel<=LOG_TRACE) log.trace(prefix+arg0,arg1);
}
public void warn(Object arg0) {
if(logLevel<=LOG_WARN) log.warn(prefix+arg0);
}
public void warn(Object arg0, Throwable arg1) {
if(logLevel<=LOG_WARN) log.warn(prefix+arg0,arg1);
}
}
}
| 7,363 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ReplacementsModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ReplacementsModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.HashMap;
/**
* The interface for the replacements system. The replacements system is
* a simpler lighter weight option to proper templates. It can perform simple
* search and replace functions, with possibly dynamic replace values. For
* example, if you only need to add a name, or email address, or some other small
* simple thing, in an otherwise static string, you can use the replacements
* method instead of a full templating language. The only implementation
* at the moment is DefaultReplacementsModule, but other implementations could
* be added.
*
*
* @author olli
*/
public interface ReplacementsModule extends Module {
/**
* Replace the values in the given string using the given context.
* The exact way the context is used depends on the implementation. It is
* not necessarily used so that every occurrence of the key in the context
* is replaced with the value.
*
* @param value The string in which replacements are to be done.
* @param context A context used in the replacements.
* @return
*/
public String replaceValue(String value,HashMap<String,Object> context);
}
| 2,000 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseInterface.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/DatabaseInterface.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
* An interface for a module that provides database services. An implementation
* using JDBC is in GenericDatabaseInterface.
*
* @author olli
*/
public interface DatabaseInterface extends Module {
/**
* Executes a database query and returns the results.
* @param query The query to execute.
* @return The results of the query as a Rows object (essentially an ArrayList).
* @throws SQLException
*/
public Rows query(String query) throws SQLException ;
/**
* Executes an update statement.
* @param query The update statement to execute.
* @return The number of rows affected by the statement.
* @throws SQLException
*/
public int update(String query) throws SQLException ;
/**
* Inserts a row with an auto increment field and returns the
* automatically assigned value.
* @param query The insert statement.
* @return The automatically assigned incremented value.
* @throws SQLException
*/
public Object insertAutoIncrement(String query) throws SQLException;
/**
* Escapes a string so that it can then be safely used as part of a
* query.
* @param str The string to be escaped.
* @return The escaped string.
*/
public String sqlEscape(String str);
/**
* Escapes a string so that it can then be safely used as part of a
* query with a maximum length of the returned string. If the input
* value is longer than the maximum length, it will be truncated to fit the
* length limit.
*
* @param str The string to be escaped.
* @param length The maximum length.
* @return The escaped and possibly truncated string.
*/
public String sqlEscapeLen(String str,int length);
/**
* Makes a time stamp value out of a milliseconds time.
* @param time The time in milliseconds.
* @return The time stamp as a string.
*/
public String formatTimestamp(long time);
/**
* Prepares a statement for later execution.
* @param query The statement to prepare.
* @return A PreparedDatabaseStatement object that can be ran later.
* @throws SQLException
*/
public PreparedDatabaseStatement prepareStatement(String query) throws SQLException ;
/* public PreparedStatement prepareStatement(String query) throws SQLException ;
public Rows queryPrepared(PreparedStatement stmt) throws SQLException ;
public int updatePrepared(PreparedStatement stmt) throws SQLException ;
public void runDatabaseRunnable(DatabaseRunnable run) throws SQLException ;*/
/**
* A simple helper class for returned rows, essentially an ArrayList of Row
* objects.
*/
public static class Rows extends ArrayList<Row> {
public Rows(){
super();
}
}
/**
* A simple helper class for a single returned row, essentially just a HashMap.
*/
public static class Row extends HashMap<String,Object>{
public Row(){
super();
}
}
// public void reconnect();
/**
* Adds a database connection listener that will be notified when
* a database connection is established or closed.
* @param l
*/
public void addDatabaseConnectionListener(DatabaseConnectionListener l);
/**
* Removes a database connection listener.
* @param l
*/
public void removeDatabaseConnectionListener(DatabaseConnectionListener l);
public static interface DatabaseConnectionListener {
public void connectionClosed(DatabaseInterface db);
public void connectionStarted(DatabaseInterface db);
}
/*
public static interface DatabaseRunnable {
public void run() throws SQLException ;
}
*/
/**
* A class that holds information about a stored database statement that
* can be executed later, possibly multiple times.
*/
public static interface PreparedDatabaseStatement {
/**
* Executes this prepared statement as a query and returns the
* query results.
* @return The results of the query.
* @throws SQLException
*/
public Rows executeQuery() throws SQLException;
/**
* Executes this prepared statement as an update statement.
* @return The number of rows affected.
* @throws SQLException
*/
public int executeUpdate() throws SQLException;
/**
* Closes this prepared statement, indicating that it will not be needed
* anymore and any resources related to it can be released.
*/
public void close();
/**
* Sets a parameter of the prepared statement. Parameters are indexed
* starting at 1. You can use any of the other specialised set methods
* for specific types of parameters.
*
* @param paramIndex The index of the parameter to set.
* @param param The value of the parameter.
* @param paramType The type of the parameter, as set in java.sql.Types.
* @throws SQLException
*/
public void setParam(int paramIndex,Object param,int paramType) throws SQLException;
public void setString(int paramIndex,String o) throws SQLException;
public void setBoolean(int paramIndex,boolean o) throws SQLException;
public void setInt(int paramIndex,int o) throws SQLException;
public void setShort(int paramIndex,short o) throws SQLException;
public void setLong(int paramIndex,long o) throws SQLException;
public void setDouble(int paramIndex,double o) throws SQLException;
public void setFloat(int paramIndex,float o) throws SQLException;
public void setNull(int paramIndex,int type) throws SQLException;
}
}
| 6,755 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
EmailModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/EmailModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* A module that provides email sending services for other modules.
* Requires details of the SMTP server in the module parameters passed to the
* init method. These are given in parameters smtpServer, smtpPort smtpUseTLS,
* smtpUseSSLAuth, smtpUser and smtpPass. In addition to these a default
* from field and default subject can be specified in parameters defaultFrom
* and defaultSubject. These will be used if other modules don't specify anything
* else for those fields.
*
* @author olli
*/
public class EmailModule extends AbstractModule {
protected String smtpServer;
protected int smtpPort=-1;
protected String smtpUser;
protected String smtpPass;
protected boolean smtpTLS=false;
protected boolean smtpSSLAuth=false;
protected String defaultFrom=null;
protected String defaultSubject=null;
protected String defaultCharset="UTF-8";
protected String defaultContentType="text/plain";
protected Properties mailProps;
public boolean send(List<String> recipients,String from,String subject,MimeMultipart content) {
if(from==null) from=defaultFrom;
if(subject==null) subject=defaultSubject;
try{
// Properties props=new Properties();
// props.put("mail.smtp.host",smtpServer);
Session session=Session.getDefaultInstance(mailProps,null);
MimeMessage message=new MimeMessage(session);
if(subject!=null) message.setSubject(subject);
if(from!=null) message.setFrom(new InternetAddress(from));
message.setContent(content);
Transport transport = session.getTransport("smtp");
if(smtpPort>0) transport.connect(smtpServer,smtpPort,smtpUser,smtpPass);
else transport.connect(smtpServer,smtpUser,smtpPass);
Address[] recipientAddresses=new Address[recipients.size()];
for(int i=0;i<recipientAddresses.length;i++){
recipientAddresses[i]=new InternetAddress(recipients.get(i));
}
transport.sendMessage(message,recipientAddresses);
return true;
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
public boolean send(List<String> recipients,String from,String subject,List<BodyPart> parts){
MimeMultipart content=new MimeMultipart();
try{
for(BodyPart p : parts){
content.addBodyPart(p);
}
return send(recipients, from, subject, content);
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
/*
public boolean send(List<String> recipients,String from,String subject,byte[] content,String mimeType){
try{
MimeBodyPart mimeBody=new MimeBodyPart();
mimeBody.setContent(content, mimeType);
ArrayList<BodyPart> parts=new ArrayList<BodyPart>();
parts.add(mimeBody);
return send(recipients, from, subject, parts);
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
}
*/
protected static Pattern charsetPattern=Pattern.compile("(?:^|;)\\s*charset\\s*=\\s*([^;\\s]+)\\s*(?:;|$)", Pattern.CASE_INSENSITIVE);
public boolean send(List<String> recipients,String from,String subject,Object message,String mimeType){
String charset;
if(mimeType!=null){
Matcher m=charsetPattern.matcher(mimeType);
if(m.find()){
charset=m.group(1).toUpperCase();
}
else {
charset=defaultCharset;
mimeType+="; charset="+defaultCharset.toLowerCase();
}
}
else {
charset=defaultCharset;
mimeType=defaultContentType+"; charset="+defaultCharset.toLowerCase();
}
try{
MimeBodyPart mimeBody=new MimeBodyPart();
mimeBody.setContent(message, mimeType);
ArrayList<BodyPart> parts=new ArrayList<BodyPart>();
parts.add(mimeBody);
return send(recipients, from, subject, parts);
// byte[] content=message.getBytes(charset);
// return send(recipients, from, subject, content, mimeType);
}
catch(MessagingException me){
logging.warn("Couldn't send email",me);
return false;
}
/* catch(UnsupportedEncodingException uee){
logging.warn("Couldn't send email, unsupported encoding "+charset,uee);
return false;
}*/
}
public boolean send(String recipient,String from,String subject,Object message, String mimeType){
ArrayList<String> recipients=new ArrayList<String>();
recipients.add(recipient);
return send(recipients, from, subject, message, mimeType);
}
public boolean send(String recipient,String from,String subject,Object message){
return send(recipient, from, subject, message, defaultContentType+"; charset="+defaultCharset.toLowerCase());
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
mailProps=new Properties();
o=settings.get("smtpServer");
if(o!=null) {
smtpServer=o.toString();
mailProps.put("mail.smtp.host",smtpServer);
}
o=settings.get("smtpPort");
if(o!=null) {
smtpPort=Integer.parseInt(o.toString());
if(smtpPort>0) mailProps.put("mail.smtp.port",smtpPort);
}
o=settings.get("smtpUseTLS");
if(o!=null) {
smtpTLS=Boolean.parseBoolean(o.toString());
if(smtpTLS) mailProps.put("mail.smtp.starttls.enabled","true");
}
o=settings.get("smtpUseSSLAuth");
if(o!=null){
smtpSSLAuth=Boolean.parseBoolean(o.toString());
if(smtpSSLAuth) mailProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
o=settings.get("smtpUser");
if(o!=null) {
smtpUser=o.toString();
if(smtpUser!=null) mailProps.put("mail.smtp.auth","true");
}
o=settings.get("smtpPass");
if(o!=null) smtpPass=o.toString();
o=settings.get("defaultFrom");
if(o!=null) defaultFrom=o.toString();
o=settings.get("defaultSubject");
if(o!=null) defaultSubject=o.toString();
super.init(manager, settings);
}
}
| 8,381 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DBTesterModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/DBTesterModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.DatabaseInterface.PreparedDatabaseStatement;
import org.wandora.modules.DatabaseInterface.Row;
import org.wandora.modules.DatabaseInterface.Rows;
/**
* This does some stress testing of DatabaseInterface, mainly intended
* for debugging memory leaks.
*
* @author olli
*/
public class DBTesterModule extends AbstractModule {
protected boolean usePrepared=false;
protected PreparedDatabaseStatement prepared=null;
protected DatabaseInterface database;
protected Thread thread;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(this,DatabaseInterface.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("useprepared");
if(o!=null) usePrepared=Boolean.parseBoolean(o.toString());
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
database=manager.findModule(this, DatabaseInterface.class);
if(usePrepared) {
try{
prepared=database.prepareStatement("select * from USERS,USER_PROPS,USER_ROLES where NOW()>?");
}catch(SQLException ignore){}
}
this.isRunning=true;
thread=new Thread(new Runnable(){
@Override
public void run() {
threadRun();
}
});
thread.start();
super.start(manager);
}
protected void threadRun(){
int queriesRan=0;
int connections=0;
while(this.isRunning){
for(int i=0;i<100;i++){
try{ Thread.sleep((int)(Math.random()*10)); } catch(InterruptedException ie){}
try{
Rows rows;
if(prepared!=null){
prepared.setInt(1, (int)(Math.random()*100));
rows=prepared.executeQuery();
}
else rows=database.query("select * from USERS,USER_PROPS,USER_ROLES where NOW()>0");
queriesRan++;
for(Row row : rows){
if(row.isEmpty()) break; // doesn't really do anything but makes sure that we do something with the rows
}
}catch(SQLException sqle){
logging.warn(sqle);
}
}
// database.reconnect();
connections++;
logging.info("Queries ran "+queriesRan);
logging.info("Connections "+connections);
try{ Thread.sleep((int)(Math.random()*5000)); } catch(InterruptedException ie){}
}
}
@Override
public void stop(ModuleManager manager) {
this.isRunning=false;
if(thread!=null){
try{ thread.join(2000); } catch(InterruptedException ie){}
}
thread=null;
if(prepared!=null) prepared.close();
database=null;
super.stop(manager);
}
}
| 4,284 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GenericDatabaseInterface.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/GenericDatabaseInterface.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.dbcp2.BasicDataSource;
import org.wandora.utils.ListenerList;
import org.wandora.utils.Tuples;
import org.wandora.utils.Tuples.T2;
/**
* A general purpose implementation of the DatabaseInterface using JDBC
* and thus being able to operate with many different relational
* databases. The connection details of the JDBC connection are given as
* module parameters in init with parameter names driver, connectionstring,
* username and password. These contain, respectively, the full class name of the
* JDBC driver to use, the connection string used by the driver, the user name
* and the password.
*
*
* @author olli
*/
public class GenericDatabaseInterface extends AbstractModule implements DatabaseInterface {
protected ListenerList<DatabaseConnectionListener> listeners=new ListenerList<DatabaseConnectionListener>(DatabaseConnectionListener.class);
protected String driver;
protected String connectionString;
protected String userName;
protected String password;
// protected String initScript;
protected BasicDataSource connectionPool;
// protected Connection connection;
// protected int connectionRetries=5;
// protected SimpleDateFormat timestampFormat=new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss.SSS''");
@Override
public String sqlEscape(String str){
str=str.replace("'", "''");
return str;
}
@Override
public String sqlEscapeLen(String str,int length){
if(str.length()>length) str=str.substring(0,length);
str=sqlEscape(str);
return str;
}
@Override
public String formatTimestamp(long time){
// Date d=new Date();
// d.setTime(time);
// return timestampFormat.format(d);
// mysql doesn't support milliseconds in timestamps so it's better to store them with just milliseconds
return ""+time;
}
public Rows makeRows(ResultSet rs) throws SQLException {
Rows ret=new Rows();
ResultSetMetaData md=rs.getMetaData();
int columnCount=md.getColumnCount();
String[] columns=new String[columnCount];
for(int i=0;i<columnCount;i++){columns[i]=md.getColumnLabel(i+1).toLowerCase();}
while(rs.next()){
Row row=new Row();
for(int i=0;i<columnCount;i++){
Object o=rs.getObject(i+1);
row.put(columns[i], o);
}
ret.add(row);
}
return ret;
}
/*
@Override
public void runDatabaseRunnable(DatabaseRunnable run) throws SQLException {
int retries=connectionRetries;
while(true){
try{
run.run();
break;
}catch(SQLException sqle){
retries--;
if(retries<0) throw sqle;
else {
if(retries<connectionRetries-1) try{Thread.sleep(10000);}catch(InterruptedException ie){}
reconnect();
}
}
}
}
*/
@Override
public Rows query(String query) throws SQLException {
Connection connection=connectionPool.getConnection();
if(connection==null) throw new SQLException("Couldn't get connection from the connection pool");
Statement stmt=null;
ResultSet rs=null;
try{
stmt=connection.createStatement();
rs=stmt.executeQuery(query);
return makeRows(rs);
} finally{
if(rs!=null) try{ rs.close(); } catch(SQLException ignore){}
if(stmt!=null) try{ stmt.close(); } catch(SQLException ignore){}
if(connection!=null) try{ connection.close(); } catch(SQLException ignore){}
}
/*
int retries=connectionRetries;
while(true){
try{
Statement stmt=connection.createStatement();
try{
ResultSet rs=stmt.executeQuery(query);
return makeRows(rs);
}
finally{ stmt.close(); }
} catch(SQLException sqle){
retries--;
if(retries<0) throw sqle;
else {
if(retries<connectionRetries-1) try{Thread.sleep(10000);}catch(InterruptedException ie){}
reconnect();
}
}
}
*/
}
@Override
public int update(String query) throws SQLException {
return update(query,null);
}
// generatedKeys is a container for another return value
public int update(String query,Rows[] generatedKeys) throws SQLException {
Connection connection=connectionPool.getConnection();
if(connection==null) throw new SQLException("Couldn't get connection from the connection pool");
Statement stmt=null;
ResultSet rs=null;
try{
stmt=connection.createStatement();
if(generatedKeys!=null && generatedKeys.length>0){
int ret=stmt.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
rs=stmt.getGeneratedKeys();
generatedKeys[0]=makeRows(rs);
return ret;
}
else {
return stmt.executeUpdate(query);
}
} finally{
if(rs!=null) try{ rs.close(); } catch(SQLException ignore){}
if(stmt!=null) try{ stmt.close(); } catch(SQLException ignore){}
if(connection!=null) try{ connection.close(); } catch(SQLException ignore){}
}
/*
int retries=connectionRetries;
while(true){
try{
Statement stmt=connection.createStatement();
try{
if(generatedKeys!=null && generatedKeys.length>0){
int ret=stmt.executeUpdate(query,Statement.RETURN_GENERATED_KEYS);
ResultSet rs=stmt.getGeneratedKeys();
generatedKeys[0]=makeRows(rs);
return ret;
}
else {
return stmt.executeUpdate(query);
}
}
finally{ stmt.close(); }
}catch(SQLException sqle){
retries--;
if(retries<0) throw sqle;
else {
if(retries<connectionRetries-1) try{Thread.sleep(10000);}catch(InterruptedException ie){}
reconnect();
}
}
}
*/
}
// private final Object autoIncrementLock=new Object();
@Override
public Object insertAutoIncrement(String query) throws SQLException {
// this synchronisation is no longer needed with the connection pool
// since connections are not shared
// synchronized(autoIncrementLock){
Rows[] generatedKeys=new Rows[1];
update(query,generatedKeys);
return generatedKeys[0].get(0).entrySet().iterator().next().getValue();
// }
}
/*
@Override
public Rows queryPrepared(PreparedStatement stmt) throws SQLException {
return makeRows(stmt.executeQuery());
}
@Override
public int updatePrepared(PreparedStatement stmt) throws SQLException {
return stmt.executeUpdate();
}
*/
/*
@Override
public PreparedStatement prepareStatement(String query) throws SQLException {
return null;
Connection connection=connectionPool.getConnection();
if(connection!=null) try {
return connection.prepareStatement(query);
} finally{ connection.close(); }
else throw new SQLException("Couldn't get connection from the connection pool");
}
*/
/*
public void connect() throws ClassNotFoundException,SQLException {
// it seems hsqldb (or jdbc?) messes up logging, store handlers and then reset them after connecting
Logger l=null;
Level lev=null;
Handler[] hs=null;
if(connectionString.startsWith("jdbc:hsqldb:")){
l=Logger.getLogger("");
lev=l.getLevel();
hs=l.getHandlers();
}
logging.info("Connecting to database");
if(connection!=null) connection.close();
Class.forName(driver);
connection=DriverManager.getConnection(connectionString,userName,password);
if(connectionString.startsWith("jdbc:hsqldb:")){
Handler[] hs2=l.getHandlers();
for(int i=0;i<hs2.length;i++){
l.removeHandler(hs2[i]);
}
for(int i=0;i<hs.length;i++){
l.addHandler(hs[i]);
}
l.setLevel(lev);
}
if(connection==null){
logging.error("Couldn't connect to database. getConnection returned null.");
return;
}
logging.info("Connected to database");
if(initScript!=null){
logging.info("Running database init script.");
try{
StringBuffer sb=new StringBuffer();
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(initScript),"UTF-8"));
String line=null;
while( (line=in.readLine())!=null ) {
sb.append(line);
sb.append("\n");
}
String[] lines=sb.toString().split(";");
Statement stmt=connection.createStatement();
for(int i=0;i<lines.length;i++){
lines[i]=lines[i].trim();
if(lines[i].length()>0) stmt.addBatch(lines[i]);
}
stmt.executeBatch();
stmt.close();
}
catch(IOException ioe){
logging.error("Couldn't run init script.",ioe);
}
catch(SQLException sqle2){
logging.error("Couldn't run init script.",sqle2);
}
}
fireDatabaseStarted();
}
protected final Object reconnectLock=new Object();
@Override
public void reconnect(){
synchronized(reconnectLock){
try{
// this tests if the connection is working
Statement stmt=connection.createStatement();
stmt.executeQuery("select NOW();");
stmt.close();
// if we get here then the connection is working and nothing needs to be done
return;
}catch(SQLException e){}
fireDatabaseClosed();
try{
connect();
isRunning=true;
}
catch(ClassNotFoundException cnfe){
logging.error("Couldn't reconnect to database.",cnfe);
}
catch(SQLException sqle){
logging.error("Couldn't reconnect to database.",sqle);
}
}
}
*/
/*
@Override
public void reconnect() {
}
*/
protected void initConnectionPool(){
connectionPool=new BasicDataSource();
connectionPool.setDriverClassName(driver);
connectionPool.setUrl(connectionString);
connectionPool.setUsername(userName);
connectionPool.setPassword(password);
connectionPool.setValidationQuery("select 1");
connectionPool.setTestOnBorrow(true);
// connectionPool.setValidationQueryTimeout(1);
fireDatabaseStarted();
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
driver=(String)settings.get("driver");
connectionString=(String)settings.get("connectionstring");
userName=(String)settings.get("username");
password=(String)settings.get("password");
// initScript=(String)settings.get("initscript");
// Object o=settings.get("retries");
// if(o!=null) connectionRetries=Integer.parseInt(o.toString());
super.init(manager,settings);
}
/*
@Override
public HashMap<String, Object> saveOptions() {
HashMap<String,Object> ret=super.saveOptions();
ret.put("driver",driver);
ret.put("connectionstring",connectionString);
ret.put("username",userName);
ret.put("password", password);
// ret.put("initscript",initScript);
return ret;
}
*/
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
/* try{
connect();
isRunning=true;
}
catch(ClassNotFoundException cnfe){
throw new ModuleException("Couldn't connect to database",cnfe);
}
catch(SQLException sqle){
throw new ModuleException("Couldn't connect to database",sqle);
}
// no call to super.start, isRunning is set after connect or in reconnect
*/
initConnectionPool();
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
/* if(connection!=null) {
try{
connection.close();
}catch(SQLException sqle){
}
connection=null;
}*/
try{
connectionPool.close();
}
catch(SQLException sqle){
logging.warn("Exception closing connection pool",sqle);
}
fireDatabaseClosed();
super.stop(manager);
}
@Override
public PreparedDatabaseStatement prepareStatement(String query) throws SQLException {
return new GenericPreparedDatabaseStatement(query);
}
public void addDatabaseConnectionListener(DatabaseConnectionListener l){
listeners.addListener(l);
}
public void removeDatabaseConnectionListener(DatabaseConnectionListener l){
listeners.removeListener(l);
}
protected void fireDatabaseStarted(){
listeners.fireEvent("connectionStarted", this);
}
protected void fireDatabaseClosed(){
listeners.fireEvent("connectionStarted", this);
}
protected class GenericPreparedDatabaseStatement implements PreparedDatabaseStatement {
private String query;
private ArrayList<T2<Integer,Object>> params;
private Connection connection;
private PreparedStatement statement;
private int numRetries=1;
public GenericPreparedDatabaseStatement(String query){
this.query=query;
params=new ArrayList<T2<Integer, Object>>();
}
private void openConnection() throws SQLException {
close();
logging.info("Opening connection");
connection=connectionPool.getConnection();
if(connection==null) throw new SQLException("Couldn't get connection from the connection pool for prepared statement");
statement=connection.prepareStatement(query);
for(int i=0;i<params.size();i++){
T2<Integer,Object> param=params.get(i);
if(param!=null) statement.setObject(i, param.e2, param.e1);
}
}
@Override
public void close() {
try{
if(statement!=null) statement.close();
if(connection!=null) connection.close();
}catch(SQLException ignore){}
statement=null;
connection=null;
}
@Override
public Rows executeQuery() throws SQLException {
if(statement==null) openConnection();
int attempt=0;
while(true){
try{
ResultSet rs=statement.executeQuery();
try{
return makeRows(rs);
}
finally{
if(rs!=null) try{ rs.close(); } catch(SQLException ignore){}
}
}catch(SQLException sqle){
logging.info("Connection closed, retrying");
attempt++;
if(attempt>numRetries) throw sqle;
else {
if(attempt>1) try{ Thread.sleep(1000); } catch(InterruptedException ignore){}
openConnection();
}
}
}
}
@Override
public int executeUpdate() throws SQLException {
if(statement==null) openConnection();
int attempt=0;
while(true){
try{
return statement.executeUpdate();
}catch(SQLException sqle){
attempt++;
if(attempt>numRetries) throw sqle;
else {
if(attempt>1) try{ Thread.sleep(1000); } catch(InterruptedException ignore){}
openConnection();
}
}
}
}
@Override
public void setParam(int paramIndex, Object param, int paramType) throws SQLException {
while(this.params.size()<=paramIndex) this.params.add(null);
this.params.set(paramIndex, Tuples.t2(paramType, param));
if(statement!=null){
statement.setObject(paramIndex, param, paramType);
}
}
@Override
public void setBoolean(int paramIndex, boolean o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.BOOLEAN);
}
@Override
public void setDouble(int paramIndex, double o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.DOUBLE);
}
@Override
public void setFloat(int paramIndex, float o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.FLOAT);
}
@Override
public void setInt(int paramIndex, int o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.INTEGER);
}
@Override
public void setLong(int paramIndex, long o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.BIGINT);
}
@Override
public void setNull(int paramIndex, int type) throws SQLException {
setParam(paramIndex,null,type);
}
@Override
public void setShort(int paramIndex, short o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.SMALLINT);
}
@Override
public void setString(int paramIndex, String o) throws SQLException {
setParam(paramIndex,o,java.sql.Types.VARCHAR);
}
}
}
| 20,228 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModuleDelegate.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/ModuleDelegate.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules;
/**
*
* A container class for other modules. The purpose of this is to keep
* a reference to a module that will be created later. This can be used to
* refer to other modules in a module configuration file where the reference
* might occur before the module is created. A ModuleDelegate is then created
* and the actual module can be retrieved later with getModule.
*
* @author olli
*/
public class ModuleDelegate {
protected ModuleManager manager;
protected String moduleName;
public ModuleDelegate(ModuleManager manager, String name){
this.manager=manager;
this.moduleName=name;
}
public Module getModule(){
return manager.findModule(moduleName, Module.class);
}
}
| 1,565 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ViewTopicAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/topicmap/ViewTopicAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.topicmap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.CachedAction;
import org.wandora.modules.servlet.GenericTemplateAction;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.servlet.Template;
import org.wandora.topicmap.TMBox;
import org.wandora.topicmap.Topic;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An action for displaying something about a single topic using
* a template. This extends GenericTemplateAction and adds some features
* related to topics. For the most part, however, it works exactly like
* GenericTemplateAction.
* </p>
* <p>
* The topic this action uses can be specified in the HTTP request. The request
* parameter used for this is topic, but it can be changed using the initialisation
* parameter topicRequestKey. The request parameter value can be a number of things.
* It can be prefixed with one of "si:", "sl:" or "bn:" standing for subject
* identifier, subject locator and base name, respectively. The prefix is then
* followed by the value of the chosen identifying field. If you do not use any
* prefix, a topic is looked for trying all the identifying fields in that order
* until a topic is found. That is, the value is first assumed to be a subject
* identifier, then a subject locator and finally a base name. If no suitable
* topic is found, whether a prefix is used or not, the action will fail.
* </p>
* <p>
* You may set the initialisation parameter noTopic to true to disable automatic
* topic resolution. In this case you should resolve the topic in your template.
* You will also need to forward the relevant request parameter to the template,
* which is best done using GenericTemplateAction's forwardRequestParameters.
* </p>
* <p>
* Unless noTopic is set to true, the topic will be automatically added to the
* template context. By default this is done using template parameter name
* "topic", but this can be changed using the initialisation parameter topicContextKey.
* Similarly the topic map is added to the context using parameter name "topicmap"
* and this can be changed with the initialisation parameter topicMapContextKey.
* The exact value of the HTTP request parameter is also added in the context with
* parameter name "topicRequest". This will include the possible prefix of the
* value, as described above.
* </p>
* <p>
* You can set the default topic and default language using initialisation
* parameters defaultTopic and defaultLang, respectively. If either is left
* undefined in the HTTP request, the defaults will be used instead.
* </p>
* <p>
* Note that the getTopic and getTopics methods are static and can, and should,
* be used in other actions which need to resolve topics based on request
* parameters.
* </p>
*
* @author olli
*/
public class ViewTopicAction extends GenericTemplateAction {
protected String topicRequestKey="topic";
protected String topicMapContextKey="topicmap";
protected String topicContextKey="topic";
protected boolean noTopic=false;
protected String defaultLang="en";
protected String defaultTopic="http://wandora.org/si/core/wandora-class";
protected TopicMapManager tmManager;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(this,TopicMapManager.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
Object o;
o=settings.get("defaultLang");
if(o!=null) defaultLang=o.toString().trim();
o=settings.get("defaultTopic");
if(o!=null) defaultTopic=o.toString().trim();
o=settings.get("noTopic");
if(o!=null) noTopic=Boolean.parseBoolean(o.toString());
o=settings.get("topicMapContextKey");
if(o!=null) topicMapContextKey=o.toString().trim();
o=settings.get("topicContextKey");
if(o!=null) topicContextKey=o.toString().trim();
o=settings.get("topicRequestKey");
if(o!=null) topicRequestKey=o.toString().trim();
}
@Override
public void start(ModuleManager manager) throws ModuleException {
tmManager=manager.findModule(this,TopicMapManager.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
tmManager=null;
super.stop(manager);
}
@Override
protected Map<String,String> getCacheKeyParams(HttpServletRequest req, HttpMethod method, String action) {
Map<String,String> params=super.getCacheKeyParams(req, method, action);
String lang=req.getParameter("lang");
if(lang==null || lang.length()==0) lang=defaultLang;
params.put("lang",lang);
if(!noTopic){
String topic=req.getParameter(topicRequestKey);
if(topic==null || topic.length()==0) topic=defaultTopic;
params.put("topicRequest",topic);
}
return params;
}
@Override
protected String getCacheKey(HttpServletRequest req, HttpMethod method, String action) {
return CachedAction.buildCacheKey(getCacheKeyParams(req, method, action));
}
/**
* <p>
* Returns topics based on a simple query. Currently this will only ever
* return a single topic at most, in the future more supported query types
* might be added which could return more topics.
* </p>
* <p>
* At the moment, the query can be prefixed with one of "si:", "sl:" or "bn:"
* which stand for subject identifier, subject locator and base name,
* respectively. After the prefix, add the value of the chosen identifying
* field. That topic will then be returned, or an empty collection if it doesn't
* exist. If you don't use any prefix, the value is first assumed to be a
* subject identifier, if that doesn't correspond to an existing topic, then
* subject locator is tried, and finally base name. If none work, then an
* empty collection is returned. Otherwise the first match is returned.
* </p>
* @param query The topic query.
* @param tm The topic map where to execute the query.
* @param max Maximum number of results to return.
* @return The topics matching the query.
* @throws TopicMapException
*/
public static List<Topic> getTopics(String query,TopicMap tm,int max) throws TopicMapException {
List<Topic> ret=new ArrayList<Topic>();
if(query.startsWith("si:")){
Topic t=tm.getTopic(query.substring(3));
if(t!=null) ret.add(t);
}
else if(query.startsWith("bn:")){
Topic t=tm.getTopicWithBaseName(query.substring(3));
if(t!=null) ret.add(t);
}
else if(query.startsWith("sl:")){
Topic t=tm.getTopicBySubjectLocator(query.substring(3));
if(t!=null) ret.add(t);
}
else {
Topic t=tm.getTopic(query);
if(t!=null) ret.add(t);
else {
t=tm.getTopicBySubjectLocator(query);
if(t!=null) ret.add(t);
else {
t=tm.getTopicWithBaseName(query);
if(t!=null) ret.add(t);
}
}
}
return ret;
}
/**
* Same as getTopics, but returns only the first result of what
* getTopics would return. As noted in getTopics documentation,
* at the moment it will only ever return at most a single topic anyway
* so there isn't much difference between these two methods yet. This
* method will return null if no topic is found.
*
* @param query The topic query.
* @param tm The topic map where to execute the query.
* @return The first result of the query or null if no topics were found.
* @throws TopicMapException
*/
public static Topic getTopic(String query,TopicMap tm) throws TopicMapException {
List<Topic> ts=getTopics(query,tm,1);
if(ts.isEmpty()) return null;
else return ts.get(0);
}
@Override
protected Map<String, Object> getStaticTemplateContext() {
Map<String,Object> context=super.getStaticTemplateContext();
context.put("tmbox",new TMBox());
return context;
}
@Override
protected Map<String, Object> getTemplateContext(Template template, HttpServletRequest req, HttpMethod method, String action, org.wandora.modules.usercontrol.User user) throws ActionException {
Map<String, Object> context=super.getTemplateContext(template, req, method, action, user);
context.putAll(getCacheKeyParams(req, method, action));
TopicMap tm=tmManager.getTopicMap();
if(!noTopic){
try{
Topic t=getTopic((String)context.get("topicRequest"),tm);
if(t==null) return null; // returning null causes this action to abort, probably results in a 404 in the end or something
context.put(topicContextKey,t);
}
catch(TopicMapException tme){
logging.warn(tme);
return null;
}
}
context.put(topicMapContextKey,tm);
return context;
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, org.wandora.modules.usercontrol.User user) throws ServletException, IOException, ActionException {
if(tmManager.lockRead()){
try{
return super.handleAction(req, resp, method, action, user);
}
finally{
tmManager.unlockRead();
}
}
else return false;
}
}
| 11,386 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleTopicMapManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/topicmap/SimpleTopicMapManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.topicmap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.topicmap.SimpleTopicMapLogger;
import org.wandora.topicmap.TopicMap;
import org.wandora.topicmap.TopicMapException;
import org.wandora.topicmap.TopicMapType;
import org.wandora.topicmap.TopicMapTypeManager;
import org.wandora.topicmap.layered.LayerStack;
import org.wandora.topicmap.memory.TopicMapImpl;
import org.wandora.topicmap.packageio.PackageOutput;
import org.wandora.topicmap.packageio.ZipPackageOutput;
import org.wandora.utils.ListenerList;
/**
* <p>
* Basic implementation of the topic map manager. Simply loads the topic
* map from a file and gives direct access to that. The file can either be an
* xtm file or a Wandora project file. Optionally, can be set to save the
* topic map at regular intervals, or alternatively to reload the topic map file
* at regular intervals.
* </p>
* <p>
* The topic map file is set with the initialisation parameter topicMapFile.
* Alternatively you can also set the topic map directly by giving a topic map
* object in the parameter topicMap. In this case the auto save and reload features
* cannot be used.
* </p>
* <p>
* Auto saving is set with the autoSave initialisation parameter. The value is
* the saving interval in minutes. Use 0 to disable auto saving, which is the
* default. Setting this parameter to "true" enables auto saving every 10 minutes.
* Note that the topic map will be written to disk whether or not actual changes
* in it have occurred.
* </p>
* <p>
* Automatic file reloading can be set with autoRefresh parameter, set it to true
* to enable automatic reloading. The topic map is reloaded whenever its
* timestamp changes, this is checked roughly once every minute.
* </p>
* <p>
* You should not use both auto saving and reloading at the same time. Or in general,
* you should not use auto saving at all if you intend to modify the file while
* this module is running. This can very easily lead to a situation where this module
* overwrites your changes.
* </p>
*
* @author olli
*/
public class SimpleTopicMapManager extends AbstractModule implements TopicMapManager {
protected final ListenerList<TopicMapManagerListener> managerListeners=new ListenerList<TopicMapManagerListener>(TopicMapManagerListener.class);
protected ReadWriteLock tmLock=new ReentrantReadWriteLock(false);
protected TopicMap tm;
protected String topicMapFile=null;
protected String autoSaveFile=null;
protected boolean autoRefresh=false;
protected int autoSave=0;
protected long lastSave=0;
protected long lastLoad=0;
protected boolean autoThreadRunning=false;
protected Thread autoThread=null;
protected final Object autoThreadWait=new Object();
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
Object o;
o=settings.get("topicMap");
if(o!=null){
if(o instanceof TopicMap) tm=(TopicMap)o;
else topicMapFile=o.toString();
}
o=settings.get("topicMapFile");
if(o!=null) topicMapFile=o.toString();
o=settings.get("autoRefresh");
if(o!=null) {
if(o.toString().equalsIgnoreCase("true")) autoRefresh=true;
else autoRefresh=false;
}
o=settings.get("autoSave");
if(o!=null) {
try{
int i=Integer.parseInt(o.toString());
autoSave=i;
}
catch(NumberFormatException nfe){
if(o.toString().equalsIgnoreCase("true")) autoSave=10;
else autoSave=0;
}
}
o=settings.get("autoSaveFile");
if(o!=null) autoSaveFile=o.toString();
else if(autoSave>0) throw new ModuleException("autoSaveFile parameter is required with auto save.");
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if((tm==null || autoRefresh) && topicMapFile!=null){
reloadTopicMap();
}
if(autoRefresh || autoSave>0){
startAutoThread();
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
this.lockWrite();
try {
this.autoThreadRunning=false;
if(autoThread!=null){
synchronized(autoThreadWait){
autoThreadWait.notify();
}
try{
autoThread.join();
}catch(InterruptedException e){}
}
autoThread=null;
if(autoSave>0){
this.saveTopicMap();
}
}finally{ this.unlockWrite(); }
super.stop(manager);
}
protected void startAutoThread(){
assert autoThread==null;
lastSave=System.currentTimeMillis();
autoThreadRunning=true;
autoThread=new Thread(new Runnable(){
@Override
public void run() {
autoThreadRun();
}
});
autoThread.start();
}
protected void autoThreadRun() {
while(autoThreadRunning){
synchronized(autoThreadWait){
try{
autoThreadWait.wait(60000);
}catch(InterruptedException e){}
}
if(!autoThreadRunning) return;
if(autoSave>0 && System.currentTimeMillis()>lastSave+60000l*(long)autoSave){
this.saveTopicMap();
}
else if(autoRefresh){
File f=new File(topicMapFile);
if(f.exists() && f.lastModified()>lastLoad) {
this.reloadTopicMap();
}
}
}
}
public void saveTopicMap(){
lastSave=System.currentTimeMillis();
lockRead();
try{
if(tm instanceof LayerStack && autoSaveFile.toLowerCase().endsWith(".wpr")){
TopicMapType tmtype=TopicMapTypeManager.getType(tm);
PackageOutput out=new ZipPackageOutput(new FileOutputStream(autoSaveFile));
tmtype.packageTopicMap(tm,out,"",new SimpleTopicMapLogger(new PrintStream(new OutputStream(){
@Override public void write(byte[] b) throws IOException {}
@Override public void write(byte[] b, int off, int len) throws IOException {}
@Override public void write(int b) throws IOException {}
})));
out.close();
}
else {
tm.exportXTM(autoSaveFile);
}
}
catch(TopicMapException tme){
logging.error("Unable to autosave topic map",tme);
}
catch(IOException ioe){
logging.error("Unable to autosave topic map",ioe);
}
finally{ unlockRead(); }
}
public void reloadTopicMap(){
TopicMap oldTm=tm;
lastLoad=System.currentTimeMillis();
lockWrite();
try{
if(topicMapFile.toLowerCase().endsWith(".wpr")){
LayerStack ls=new LayerStack(topicMapFile);
tm=ls;
}
else {
TopicMap tmNew=new TopicMapImpl(topicMapFile);
tm=tmNew;
}
}
finally{ unlockWrite(); }
fireTopicMapChanged(oldTm, tm);
}
@Override
public boolean lockRead() {
tmLock.readLock().lock();
return true;
}
@Override
public void unlockRead() {
tmLock.readLock().unlock();
}
@Override
public boolean lockWrite() {
tmLock.writeLock().lock();
return true;
}
@Override
public void unlockWrite() {
tmLock.writeLock().unlock();
}
@Override
public TopicMap getTopicMap() {
return tm;
}
protected void fireTopicMapChanged(TopicMap old,TopicMap neu){
managerListeners.fireEvent("topicMapChanged",old,neu);
}
@Override
public void addTopicMapManagerListener(TopicMapManagerListener listener) {
managerListeners.addListener(listener);
}
@Override
public void removeTopicMapManagerListener(TopicMapManagerListener listener) {
managerListeners.removeListener(listener);
}
}
| 10,013 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
WandoraTopicMapManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/topicmap/WandoraTopicMapManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.topicmap;
import java.util.Collection;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.wandora.application.Wandora;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.topicmap.TopicMap;
import org.wandora.utils.ListenerList;
/**
* <p>
* A TopicMapManager implementation that uses a running Wandora
* application for the topic map. This will only work if the Wandora
* application is running in the same virtual machine. Wandora is not a module
* in the framework, instead it is accessed using the static Wandora.getWandora
* method.
* </p>
* <p>
* This module does not use any initialisation parameters beyond those of
* AbstractModule.
* </p>
*
* @author olli
*/
public class WandoraTopicMapManager extends AbstractModule implements TopicMapManager {
protected final ListenerList<TopicMapManagerListener> managerListeners=new ListenerList<TopicMapManagerListener>(TopicMapManagerListener.class);
protected ReadWriteLock tmLock=new ReentrantReadWriteLock(false);
protected Wandora wandora;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
wandora=Wandora.getWandora();
if(wandora==null) throw new ModuleException("Wandora not found");
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
wandora=null;
super.stop(manager);
}
@Override
public boolean lockRead() {
tmLock.readLock().lock();
return true;
}
@Override
public void unlockRead() {
tmLock.readLock().unlock();
}
@Override
public boolean lockWrite() {
tmLock.writeLock().lock();
return true;
}
@Override
public void unlockWrite() {
tmLock.writeLock().unlock();
}
@Override
public TopicMap getTopicMap() {
return wandora.getTopicMap();
}
protected void fireTopicMapChanged(TopicMap old,TopicMap neu){
managerListeners.fireEvent("topicMapChanged",old,neu);
}
@Override
public void addTopicMapManagerListener(TopicMapManagerListener listener) {
managerListeners.addListener(listener);
}
@Override
public void removeTopicMapManagerListener(TopicMapManagerListener listener) {
managerListeners.removeListener(listener);
}
}
| 3,615 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TopicMapManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/topicmap/TopicMapManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.topicmap;
import org.wandora.modules.Module;
import org.wandora.topicmap.TopicMap;
/**
* <p>
* The interface for a module that provides a topic map, and related
* services, for other modules. Just providing access to the topic map
* is the main function of this. In addition to that, there are some locking
* mechanisms, but depending on the implementation, they may or may not actually
* do anything. Implementation details may also vary but the idea is that any
* number of read locks can be acquired at the same time but write locks are
* exclusive, no readers or other writers are allowed at the same time.
* </p>
* <p>
* You can also add listeners that will be notified if the whole topic map
* is changed. Note that this is different to just changes in the topic map, the
* topic map itself has listener mechanisms for that. The listener you register
* with the manager is notified when the entire topic map is replaced with another
* topic map.
* </p>
*
* @author olli
*/
public interface TopicMapManager extends Module {
/**
* Locks the topic map for reading. You must eventually release
* the lock with unlockRead if this method succeeds and returns true.
* @return True if the locking succeeded, false otherwise.
*/
public boolean lockRead();
/**
* Releases a previously acquired read lock.
*/
public void unlockRead();
/**
* Locks the topic map for writing. You must eventually release
* the lock with unlockWrite if this method succeeds and returns true.
* @return True if the locking succeeded, false otherwise.
*/
public boolean lockWrite();
/**
* Releases a previously acquired write lock.
*/
public void unlockWrite();
/**
* Returns the topic map managed by this topic map manager.
* @return The topic map of this manager.
*/
public TopicMap getTopicMap();
/**
* Adds a topic map listener that will be notified when the managed
* topic map is replaced with another topic map.
* @param listener The topic map listener.
*/
public void addTopicMapManagerListener(TopicMapManagerListener listener);
/**
* Removes a topic map listener.
* @param listener The listener.
*/
public void removeTopicMapManagerListener(TopicMapManagerListener listener);
/**
* An interface for objects that want to be notified when the managed topic
* map is replaced with another topic map. This listener is not notified
* of changes in the topic map itself, the topic map class has mechanisms for
* that.
*/
public interface TopicMapManagerListener {
/**
* The managed topic map has been replaced with another topic map.
* @param old The old topic map.
* @param neu The new topic map.
*/
public void topicMapChanged(TopicMap old,TopicMap neu);
}
}
| 3,764 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RoleRestrictedContext.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/RoleRestrictedContext.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.Map;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.UserAuthenticator.AuthenticationResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class RoleRestrictedContext extends AbstractControlledContext {
protected String requiredRole;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("requiredRole");
if(o!=null) this.requiredRole=o.toString();
super.init(manager, settings);
}
@Override
protected ForwardResult doForwardRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method) throws ServletException, IOException, ActionException {
try{
AuthenticationResult res=authenticate(requiredRole, req, resp, method);
if(res.authenticated) return new ForwardResult(true, false, res.user);
else return new ForwardResult(false, res.responded, res.user);
}catch(AuthenticationException ae){
throw new ActionException(ae);
}
}
}
| 2,259 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModifyableUserStore.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/ModifyableUserStore.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
/**
* An interface that adds to the basic UserBase interface methods which
* allow users to be modified.
*
* @author olli
*/
public interface ModifyableUserStore extends UserStore {
/**
* Creates a new user in the user store. More information about the user
* can then be added using the returned user object. Will throw an exception
* if a user with that name already exists, or if the user cannot be created
* for any other reason.
*
* @param user The user name of the new user.
* @return A user object representing the new user.
* @throws UserStoreException
*/
public User newUser(String user) throws UserStoreException;
/**
* Saves a user which originates from this database. Note that you
* cannot give just any user object, the parameter must be a user object
* you originally got from this user store. Use getUser to get an existing
* user or newUser to create a new one.
* @param user The user object to save.
* @return True if the operation succeeded.
* @throws UserStoreException
*/
public boolean saveUser(User user) throws UserStoreException;
/**
* Deletes a user from this user store.
* @param user The user name of the user to delete.
* @return True if the operation succeeded.
* @throws UserStoreException
*/
public boolean deleteUser(String user) throws UserStoreException;
}
| 2,280 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GetUserLogAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/GetUserLogAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.AbstractAction;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class GetUserLogAction extends AbstractAction {
protected UserLoggerAction userLogger;
protected UserStore userStore;
protected String userParamKey;
protected boolean useLoggedInUser=false;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(this,UserLoggerAction.class, deps);
manager.requireModule(this,UserStore.class, deps);
return deps;
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user) throws ServletException, IOException, ActionException {
User u=null;
if(useLoggedInUser) u=user;
else {
if(userParamKey==null) return false;
String userName=req.getParameter(userParamKey);
if(userName==null || userName.length()==0) return false;
try{
u=userStore.getUser(userName);
}catch(UserStoreException use){
return false;
}
}
if(u==null) return false;
String logFileS=userLogger.getLogFile(u);
if(logFileS==null) return false;
File f=new File(logFileS);
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
OutputStream out=resp.getOutputStream();
if(!f.exists()) {
out.write("Log file doesn't exist.".getBytes());
out.close();
}
else {
try{
byte[] buf=new byte[4096];
int read;
InputStream in=new FileInputStream(f);
while( (read=in.read(buf))!=-1 ){
out.write(buf,0,read);
}
in.close();
out.close();
}
catch(IOException ioe){
out.write("\nError reading log file.".getBytes());
out.close();
logging.warn("Exception sending user log file",ioe);
}
}
return true;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("userParamKey");
if(o!=null){
userParamKey=o.toString();
useLoggedInUser=false;
}
o=settings.get("useLoggedInUser");
if(o!=null) useLoggedInUser=Boolean.parseBoolean(o.toString());
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
userLogger=manager.findModule(this,UserLoggerAction.class);
userStore=manager.findModule(this,UserStore.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
userLogger=null;
userStore=null;
super.stop(manager);
}
}
| 4,574 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserStore.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserStore.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.Collection;
import org.wandora.modules.Module;
/**
* The base interface for a UserStore. Has basic methods to retrieve users
* and nothing else. ModifyableUserStore extends this interface with methods
* that allow users to be also modified. Any user store which is not modifyable
* is assumed to be set up and modified by editing some files while the user store
* is not running.
*
* @author olli
*/
public interface UserStore extends Module {
/**
* Finds a user with a user name.
* @param user The user name.
* @return A user object which contains more details about the user, or null
* if the user is not found.
* @throws UserStoreException
*/
public User getUser(String user) throws UserStoreException;
/**
* Returns a collection of all users. Note that in some cases the collection
* could be very big, or some implementations may simply not implement this
* method at all.
* @return A collection containing all users.
* @throws UserStoreException
*/
public Collection<User> getAllUsers() throws UserStoreException;
/**
* Finds users based on a property value. Since there are no uniqueness
* constraints with any of the properties in general, may return multiple
* users.
* @param key The property key used for the search.
* @param value The value of the property.
* @return A collection of users matching the property, or an empty collection
* if none matched.
* @throws UserStoreException
*/
public Collection<User> findUsers(String key,String value) throws UserStoreException;
}
| 2,518 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserStoreException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserStoreException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
/**
*
* @author olli
*/
public class UserStoreException extends Exception {
private static final long serialVersionUID = 1L;
public UserStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UserStoreException(Throwable cause) {
super(cause);
}
public UserStoreException(String message, Throwable cause) {
super(message, cause);
}
public UserStoreException(String message) {
super(message);
}
public UserStoreException() {
}
}
| 1,477 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GetUserAuthenticator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/GetUserAuthenticator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* A simple user authenticator that takes the user name and password from
* the HTTP request parameters. Note that this is a bad solution for general
* authentication and should only be used in very specific circumstances. The
* passwords are not encrypted in the request and they are stored in plain text
* on the server side as well.
* </p>
* <p>
* One use case where using this would be acceptable is when all passwords are
* empty and only the user name is needed. For example, the user name might be
* a server assigned API key for accessing some service.
* </p>
* <p>
* You can set the request parameters where user name and password are read from
* using initialisation parameters userParam and passwordParam, respectively.
* </p>
*
* @author olli
*/
public class GetUserAuthenticator extends AbstractModule implements UserAuthenticator {
public static final String PASSWORD_KEY="password";
protected String userParam="user";
protected String passwordParam="password";
protected String realm="";
protected UserStore userStore;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(UserStore.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("userParam");
if(o!=null) userParam=o.toString();
o=settings.get("passwordParam");
if(o!=null) passwordParam=o.toString();
if(passwordParam.length()==0) passwordParam=null;
o=settings.get("realm");
if(o!=null) realm=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
userStore=manager.findModule(UserStore.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
userStore=null;
super.stop(manager);
}
protected AuthenticationResult replyNotAuthorized(String realm, HttpServletResponse resp) throws IOException {
return replyNotAuthorized(realm, resp, null);
}
protected AuthenticationResult replyNotAuthorized(String realm, HttpServletResponse resp, User user) throws IOException {
return new AuthenticationResult(false, user, false);
}
@Override
public AuthenticationResult authenticate(String requiredRole, HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method) throws IOException, AuthenticationException {
String userName=req.getParameter(userParam);
if(userName==null || userName.length()==0) return replyNotAuthorized(realm, resp);
String password=null;
if(passwordParam!=null) password=req.getParameter(passwordParam);
try{
User user=userStore.getUser(userName);
if(user!=null) {
String storedPassword=user.getOption(PASSWORD_KEY);
if(storedPassword!=null && !storedPassword.equals(password)) return replyNotAuthorized(realm, resp);
if(requiredRole!=null && !user.isOfRole(requiredRole)) return replyNotAuthorized(realm,resp,user);
else return new AuthenticationResult(true, user, false);
}
else return replyNotAuthorized(realm,resp);
}catch(UserStoreException use){
throw new AuthenticationException(use);
}
}
}
| 4,975 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AuthenticationException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/AuthenticationException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
/**
*
* @author olli
*/
public class AuthenticationException extends Exception {
private static final long serialVersionUID = 1L;
public AuthenticationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public AuthenticationException(Throwable cause) {
super(cause);
}
public AuthenticationException(String message, Throwable cause) {
super(message, cause);
}
public AuthenticationException(String message) {
super(message);
}
public AuthenticationException() {
}
}
| 1,502 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FrequencyRestrictedContext.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/FrequencyRestrictedContext.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Map;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionAuthenticationException;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class FrequencyRestrictedContext extends AbstractControlledContext {
private String keyPrefix="";
private static String postfixCurrentTime="_time";
private static String postfixCurrentValue="_value";
private String requiredRole=null;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("keyPrefix");
if(o!=null) keyPrefix=o.toString();
o=settings.get("requiredRole");
if(o!=null) requiredRole=o.toString();
super.init(manager, settings);
}
@Override
protected AbstractControlledContext.ForwardResult doForwardRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method) throws ServletException, IOException, ActionException {
try{
UserAuthenticator.AuthenticationResult res=authenticate(requiredRole, req, resp, method);
if(res.authenticated) {
User user=res.user;
try{
boolean allowed=access(user,keyPrefix);
if(!allowed && exceptionOnAuthentication) throw new ActionAuthenticationException("Access frequency exceeded for user.",this);
return new AbstractControlledContext.ForwardResult(allowed, false, user);
} catch(UserStoreException use){
throw new ActionException(use);
}
}
else return new AbstractControlledContext.ForwardResult(false, res.responded, res.user);
}catch(AuthenticationException ae){
throw new ActionException(ae);
}
}
private static long[] getCurrent(User user,Keys key,long time,String prefix){
String currentTimeS=user.getOption(prefix+key.toString()+postfixCurrentTime);
String currentValueS=user.getOption(prefix+key.toString()+postfixCurrentValue);
if(currentTimeS==null || currentValueS==null || currentTimeS.length()==0 || currentValueS.length()==0) {
long next=key.getEndTime(time).getTimeInMillis();
return new long[]{next,0};
}
long currentTime=Long.parseLong(currentTimeS);
int currentValue=Integer.parseInt(currentValueS);
if(currentTime<time) {
long next=key.getEndTime(time).getTimeInMillis();
return new long[]{next,0};
}
else return new long[]{currentTime,currentValue};
}
private static boolean _access(User user,long time,boolean update,String prefix) throws UserStoreException {
for(Keys key : Keys.values()){
String limitS=user.getOption(prefix+key.toString());
if(limitS==null || limitS.length()==0) continue;
int limit=Integer.parseInt(limitS);
if(limit<0) continue;
long[] current=getCurrent(user,key,time,prefix);
if(current[1]>=limit) return false;
else {
if(update){
user.setOption(prefix+key+postfixCurrentTime,""+current[0]);
user.setOption(prefix+key+postfixCurrentValue,""+(current[1]+1));
if(!user.saveUser()) return false;
}
}
}
return true;
}
/*
* These methods don't update the counters, merely check whether access is allowed.
*/
public static boolean isAccessAllowed(User user,String prefix) throws UserStoreException {
return isAccessAllowed(user,System.currentTimeMillis(),prefix);
}
public static boolean isAccessAllowed(User user,long time,String prefix) throws UserStoreException {
return _access(user,time,false,prefix);
}
/*
* These methods check that access is allowed and also update the counters.
*/
public static boolean access(User user,String prefix) throws UserStoreException {
return access(user,System.currentTimeMillis(),prefix);
}
public static boolean access(User user,long time,String prefix) throws UserStoreException {
return _access(user,time,true,prefix);
}
public static enum Keys {
per1sec(1),
per10sec(10),
per1min(60),
per10min(600),
per1hour(3600),
per1day(3600*24),
per1month(3600*24*30),
per1year(3600*34*365);
private int seconds;
Keys(int seconds){
this.seconds=seconds;
}
public GregorianCalendar getStartTime(long time){
if(this==per1month){
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis(time);
ret.set(GregorianCalendar.MILLISECOND, 0);
ret.set(GregorianCalendar.SECOND, 0);
ret.set(GregorianCalendar.MINUTE, 0);
ret.set(GregorianCalendar.HOUR, 0);
ret.set(GregorianCalendar.DAY_OF_MONTH, 1);
return ret;
}
else if(this==per1year){
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis(time);
ret.set(GregorianCalendar.MILLISECOND, 0);
ret.set(GregorianCalendar.SECOND, 0);
ret.set(GregorianCalendar.MINUTE, 0);
ret.set(GregorianCalendar.HOUR, 0);
ret.set(GregorianCalendar.DAY_OF_MONTH, 1);
ret.set(GregorianCalendar.MONTH, 0);
return ret;
}
else{
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis((time/(this.seconds*1000))*this.seconds*1000);
return ret;
}
}
public GregorianCalendar getEndTime(long time){
if(this==per1month){
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis(time);
ret.set(GregorianCalendar.MILLISECOND, 0);
ret.set(GregorianCalendar.SECOND, 0);
ret.set(GregorianCalendar.MINUTE, 0);
ret.set(GregorianCalendar.HOUR, 0);
ret.set(GregorianCalendar.DAY_OF_MONTH, 1);
ret.add(GregorianCalendar.MONTH, 1);
return ret;
}
else if(this==per1year){
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis(time);
ret.set(GregorianCalendar.MILLISECOND, 0);
ret.set(GregorianCalendar.SECOND, 0);
ret.set(GregorianCalendar.MINUTE, 0);
ret.set(GregorianCalendar.HOUR, 0);
ret.set(GregorianCalendar.DAY_OF_MONTH, 1);
ret.set(GregorianCalendar.MONTH, 0);
ret.add(GregorianCalendar.YEAR, 1);
return ret;
}
else{
GregorianCalendar ret=new GregorianCalendar();
ret.setTimeInMillis(((time+this.seconds*1000)/(this.seconds*1000))*this.seconds*1000);
return ret;
}
}
}
}
| 8,693 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserManagerAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserManagerAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.GenericTemplateAction;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.servlet.Template;
import jakarta.servlet.http.HttpServletRequest;
/**
*
* @author olli
*/
public class UserManagerAction extends GenericTemplateAction {
protected ModifyableUserStore userStore;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(ModifyableUserStore.class, deps);
return deps;
}
@Override
protected String getCacheKey(HttpServletRequest req, HttpMethod method, String action) {
// caching is possible only for userlist and viewuser
String editAction=req.getParameter("editAction");
if(editAction==null) editAction="userlist";
if(!editAction.equals("viewuser") && !editAction.equals("userlist")) return null;
else return super.getCacheKey(req, method, action);
}
@Override
protected Map<String, Object> getTemplateContext(Template template, HttpServletRequest req, HttpMethod method, String action, User user) throws ActionException {
String editAction=req.getParameter("editaction");
if(editAction==null || editAction.length()==0) editAction="userlist";
Map<String,Object> params=super.getTemplateContext(template, req, method, action, user);
String userName=req.getParameter("user");
if(userName!=null) userName=userName.trim();
if(userName!=null && userName.length()==0) userName=null;
User userObject=null;
String view="userlist";
String error=null;
try{
if(editAction.equals("userlist")){
// no side effects, do nothing
}
else if(editAction.equals("viewuser")){
view="user";
// just check that the user is valid
if(userName!=null) userObject=userStore.getUser(userName);
}
else if(editAction.equals("edituser") || editAction.equals("edituserlist")){
view="user";
if(editAction.equals("edituserlist")) view="userlist";
if(userName!=null) {
userObject=userStore.getUser(userName);
if(userObject!=null){
Enumeration<String> paramNames=req.getParameterNames();
while(paramNames.hasMoreElements()){
String key=paramNames.nextElement();
String[] values=req.getParameterValues(key);
for(String value : values){
value=value.trim();
if(key.equals("setoption")){
int ind=value.indexOf("=");
if(ind<0) userObject.setOption(value, "");
else {
String k=value.substring(0,ind);
String v=value.substring(ind+1);
userObject.setOption(k,v);
}
}
else if(key.equals("removeoption")){
userObject.removeOption(value);
}
else if(key.equals("addrole")){
userObject.addRole(value);
}
else if(key.equals("removerole")){
userObject.removeRole(value);
}
}
}
if(!userObject.saveUser()) error="NOEDIT";
}
}
}
else if(editAction.equals("deleteuser")){
if(userName!=null) {
if(!userStore.deleteUser(userName)) error="NODELETE";
}
}
else if(editAction.equals("newuser")){
view="user";
if(userName!=null) {
userObject=userStore.newUser(userName);
if(userObject==null) error="NONEW";
}
}
else return null;
if(view.equals("user") && userObject==null) {
if(error==null) error="INVALIDUSER";
view="userlist";
}
if(view.equals("userlist")){
params.put("allUsers",userStore.getAllUsers());
}
else {
params.put("user",userObject);
}
}catch(UserStoreException use){
if(error==null) error="USERSTORE";
}
params.put("editView",view);
params.put("error",error);
return params;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
forwardRequestParameters.add("editAction");
forwardRequestParameters.add("user");
}
@Override
public void start(ModuleManager manager) throws ModuleException {
userStore=manager.findModule(ModifyableUserStore.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
userStore=null;
super.stop(manager);
}
}
| 6,868 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
User.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/User.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.Collection;
/**
* <p>
* A basis for users. This sets some very basic features all users objects
* should have. The three main things are: a user name, a set of roles and a
* set of other options and properties. The user name identifies the user and
* should be unique. The set of roles are used to specify what types of actions
* the user is allowed to perform. Everything else is stored in the generic
* options map, which is a collection of key value pairs.
* </p>
* <p>
* Note that a password would be stored in the options map. This class does not
* specify how or with what key it would be stored. That's up to whatever
* performs user authentication. Some might store it in plain text (usually not
* a good idea) while some others could use different hashing methods to store it
* and authenticate a user.
* </p>
* <p>
* You typically get users from a UserStore. Any changes to the user object can
* also be saved to the store where the user originally came from with the
* saveUser method.
* </p>
*
* @author olli
*/
public abstract class User {
/**
* Gets the user name.
* @return The user name.
*/
public abstract String getUserName();
/**
* Gets one of the stored options.
* @param optionKey The key of the property.
* @return The value of the property, or null if it doesn't exist.
*/
public abstract String getOption(String optionKey);
/**
* Gets all stored option keys.
* @return A collection containing all stored option keys.
*/
public abstract Collection<String> getOptionKeys();
/**
* Sets a stored option.
* @param optionKey The option key.
* @param value The value of the option.
*/
public abstract void setOption(String optionKey,String value);
/**
* Removes a stored option from the options map.
* @param optionKey The key of the stored option to remove.
*/
public abstract void removeOption(String optionKey);
/**
* Gets all the roles this user belongs to.
* @return A collection of role identifiers.
*/
public abstract Collection<String> getRoles();
/**
* Removes a role from this user. The user will not be part of that
* role anymore.
* @param role The role to remove.
*/
public abstract void removeRole(String role);
/**
* Adds a role to this user.
* @param role The role to add.
*/
public abstract void addRole(String role);
/**
* Saves any changes made to the user into the persistent user
* store where this user object originally came from.
* @return True if the saving succeeded, false otherwise.
* @throws UserStoreException
*/
public abstract boolean saveUser() throws UserStoreException;
/**
* Checks if this user is of a specified role.
* @param role The role identifier to check against.
* @return True if the user is of the specified role.
*/
public boolean isOfRole(String role){
return getRoles().contains(role);
}
} | 3,915 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SimpleUser.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/SimpleUser.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* A basic user implementation. Implements all the methods of the abstract
* base class. Roles and options are stored in memory in a simple ArrayList and
* a HashMap, respectively.
*
* @author olli
*/
public class SimpleUser extends User {
protected String userName;
protected Map<String,String> options;
protected List<String> roles;
@JsonIgnore
protected boolean changed=false;
@JsonIgnore
protected UserStore userStore=null;
public SimpleUser(){
}
public SimpleUser(String userName){
this(userName,new LinkedHashMap<String,String>(),new ArrayList<String>());
}
public SimpleUser(String userName, Map<String,String> options, List<String> roles) {
this(userName, options, roles, null);
}
public SimpleUser(String userName, Map<String,String> options, List<String> roles, UserStore userStore) {
this.userName = userName;
this.options = options;
this.roles = roles;
this.userStore = userStore;
}
public void setUserName(String s) {
this.userName=s;
}
@Override
public String getUserName() {
return userName;
}
public Map<String, String> getOptions() {
return options;
}
@JsonIgnore
@Override
public Collection<String> getOptionKeys() {
return options.keySet();
}
public void setOptions(Map<String, String> options) {
this.options = options;
}
@JsonIgnore
@Override
public void removeOption(String optionKey) {
options.remove(optionKey);
changed=true;
}
@JsonIgnore
@Override
public String getOption(String optionKey) {
return options.get(optionKey);
}
public void setRoles(Collection<String> roles){
this.roles=new ArrayList<String>(roles);
}
@Override
public Collection<String> getRoles() {
return roles;
}
@JsonIgnore
@Override
public void addRole(String role) {
if(!roles.contains(role)) roles.add(role);
}
@JsonIgnore
@Override
public void removeRole(String role) {
roles.remove(role);
}
@JsonIgnore
@Override
public void setOption(String optionKey, String value) {
this.options.put(optionKey, value);
changed=true;
}
@JsonIgnore
public void resetChanged(){
changed=false;
}
@JsonIgnore
public boolean isChanged(){
return changed;
}
@JsonIgnore
@Override
public boolean saveUser() throws UserStoreException {
if(userStore!=null && userStore instanceof ModifyableUserStore){
return ((ModifyableUserStore)userStore).saveUser(this);
}
else return false;
}
@JsonIgnore
public UserStore getUserStore() {
return userStore;
}
@JsonIgnore
public void setUserStore(UserStore userStore) {
this.userStore = userStore;
}
@JsonIgnore
public SimpleUser duplicate(){
return new SimpleUser(userName, new LinkedHashMap<String,String>(options), new ArrayList<String>(roles),userStore);
}
}
| 4,223 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SourceRestrictedContext.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/SourceRestrictedContext.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.Map;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.GenericContext;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A context which restricts access to the source IP address. The allowed
* addresses are specified in the initialisation parameters using parameter names
* address and mask. The address specifies an IP address and mask a mask to use
* with the address. Any incoming request which matches the IP address where the
* mask bits are 1, are allowed access, all others are denied access. The default
* value for mask is 255.255.255.255, so if you only specify the IP address, only
* that single IP address will be allowed access. The default value for address
* is 127.0.0.1 for local access only.
*
*
* @author olli
*/
public class SourceRestrictedContext extends GenericContext {
protected int address=0x7f000001; // 127.0.0.1
protected int mask=0xffffffff;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("address");
if(o!=null){
String s=o.toString();
int ind=s.indexOf("/");
if(ind>0){
address=makeAddress(s.substring(0,ind));
mask=makeMask(s.substring(ind+1));
}
else address=makeAddress(s);
}
o=settings.get("mask");
if(o!=null) mask=makeMask(o.toString());
super.init(manager, settings);
}
public static int makeAddress(String address){
String[] s=address.split("\\.");
int ret=0;
try{
for(int i=0;i<4;i++){
int n=0;
if(i<s.length) n=Math.min(Math.max(Integer.parseInt(s[i]),0),255);
ret=((ret<<8)|n);
}
}catch(NumberFormatException nfe) {return 0;}
return ret;
}
public static int makeMask(String mask){
if(mask.indexOf(".")>=0) return makeAddress(mask);
int bits=Math.min(Math.max(Integer.parseInt(mask),0),32);
int ret=0;
for(int i=0;i<bits;i++) ret=((ret<<1)|1);
if(bits<32) ret=(ret<<(32-bits));
return ret;
}
@Override
protected ForwardResult doForwardRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method) throws ServletException, IOException {
String remoteAddress=req.getRemoteAddr();
int addr=makeAddress(remoteAddress);
if(addr==0) return new ForwardResult(false,false);
if((addr&mask)==address) return new ForwardResult(true, false);
else return new ForwardResult(false,false);
}
}
| 3,772 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StaticUserStore.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/StaticUserStore.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* A very simple user store which reads user names and passwords and roles
* straight from the initialisation parameters. Does not support editing users or
* any other options than password and roles. As such, it's really only useful for
* rudimentary access control and even then, the passwords are stored in plain.
* Nevertheless, this can make an easy to set up user store for development which
* can then later be replaced with something more suitable.
* </p>
* <p>
* The user data is read from the initialisation variable users. The contents of
* this is a list of users, each user on its own line. Each user line is of the
* following format:
* </p>
* <pre>
* username;0;password;role1,role2,role3
* </pre>
* <p>
* The digit 0 is meant to indicate the format of the rest of the line, with the
* idea that in the future, this class could support more options on each user
* line. At the moment, this is the only supported format however. The last part
* may contain any number of roles, separated by commas.
* </p>
* <p>
* The password is stored in the user object using BasicUserAuthenticator.PASSWORD_KEY
* as the key.
* </p>
*
* @author olli
*/
public class StaticUserStore extends AbstractModule implements UserStore{
protected Map<String,User> users;
protected String userData;
private Pattern userPattern1=Pattern.compile("^((?:[^;]|\\\\;|\\\\\\\\)*);(\\d+);(.*)$");
private Pattern userPattern2=Pattern.compile("^((?:[^;]|\\\\;|\\\\\\\\)*);(.*$)");
protected void parseUsers(String userData){
users=new LinkedHashMap<String,User>();
String[] lines=userData.split("\n");
for(int i=0;i<lines.length;i++){
String line=lines[i].trim();
if(line.length()==0) continue;
Matcher m=userPattern1.matcher(line);
if(m.matches()) {
String user=m.group(1).replaceAll("\\\\([\\\\;])", "$1");
String dataType=m.group(2);
String rest=m.group(3);
if(Integer.parseInt(dataType)==0){
m=userPattern2.matcher(rest);
if(m.matches()){
String password=m.group(1).replaceAll("\\\\([\\\\;])", "$1");
String rolesS=m.group(2).replaceAll("\\\\([\\\\;])", "$1");
String[] rolesA=rolesS.split(",");
ArrayList<String> roles=new ArrayList<String>();
for(int j=0;j<rolesA.length;j++) roles.add(rolesA[j].trim());
User u=new SimpleUser(user, new HashMap<String,String>(), roles);
u.setOption(BasicUserAuthenticator.PASSWORD_KEY, password);
users.put(user,u);
continue;
}
}
}
// Successful parsing will use continue so if we get here then there was an error
logging.warn("Unable to parse line "+(i+1)+" of user data");
}
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
userData=(String)settings.get("users");
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
parseUsers(userData);
super.start(manager);
}
@Override
public Collection<User> getAllUsers() {
return users.values();
}
@Override
public User getUser(String user) {
return users.get(user);
}
@Override
public Collection<User> findUsers(String key, String value) {
if(!key.equals(BasicUserAuthenticator.PASSWORD_KEY)) return new ArrayList<User>();
ArrayList<User> ret=new ArrayList<User>();
for(User u : users.values()){
String option=u.getOption(key);
if(option!=null && option.equals(value)) ret.add(u);
}
return ret;
}
}
| 5,651 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserLoggerAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserLoggerAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.AbstractAction;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class UserLoggerAction extends AbstractAction {
// these are static so that same log files can be shared by multiple actions
protected static final Object fileWait=new Object();
protected static final Set<String> openFiles=new HashSet<>();
protected String entryHeader;
protected HashMap<String,String> logParams;
protected String logDir;
public String getLogFile(User user){
try{
String userName=URLEncoder.encode(user.getUserName(), "UTF-8");
if(userName.equals(".") || userName.equals("..")) return null;
return logDir+userName;
}catch(UnsupportedEncodingException uee){
throw new RuntimeException(uee); // shouldn't happen, UTF-8 is required in all java implementations
}
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps= super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("logDir");
if(o!=null) logDir=o.toString();
o=settings.get("entryHeader");
if(o!=null) entryHeader=o.toString();
logParams=new HashMap<String,String>();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("logParam.")){
key=key.substring("logParam.".length());
String value=e.getValue().toString().trim();
if(value.length()==0) value=key;
logParams.put(key,value);
}
}
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
super.stop(manager);
}
protected Writer openFile(String fileName){
long t=System.currentTimeMillis();
synchronized(fileWait){
while(openFiles.contains(fileName) && System.currentTimeMillis()-t<2000) {
try{
fileWait.wait(2000);
}catch(InterruptedException ie){
return null;
}
}
if(openFiles.contains(fileName)) return null;
try{
OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(fileName,true),"UTF-8");
openFiles.add(fileName);
return out;
}catch(FileNotFoundException fnfe){
logging.warn("Couldn't open user log file for writing",fnfe);
return null;
}catch(UnsupportedEncodingException uee){
throw new RuntimeException(uee); // shouldn't happen, UTF-8 is required in all java implementations
}
}
}
protected void closeFile(String fileName,Writer out){
synchronized(fileWait){
try{
out.close();
}catch(IOException ioe){ logging.warn("Couldn't close user log file",ioe); }
openFiles.remove(fileName);
fileWait.notifyAll();
}
}
protected String getEntryParams(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user){
StringBuilder sb=new StringBuilder();
for(Map.Entry<String,String> e : logParams.entrySet()){
String key=e.getKey();
String value=e.getValue();
String paramValue;
String replacedValue=doReplacements(value, req, method, action, user);
if(replacedValue.equals(value)) paramValue=req.getParameter(value);
else paramValue=replacedValue;
if(paramValue==null) paramValue="";
paramValue=paramValue.replace("\\", "\\\\").replace("\"","\\\"");
if(sb.length()>0) sb.append("; ");
sb.append(key).append("=\"").append(paramValue).append("\"");
}
return sb.toString();
}
protected SimpleDateFormat logDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
protected boolean writeEntry(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user,Writer out) {
StringBuilder entry=new StringBuilder();
entry.append(logDateFormat.format(new Date()));
if(entryHeader!=null) entry.append(" ").append(entryHeader);
String params=getEntryParams(req, resp, method, action, user);
if(params!=null && params.length()>0) {
entry.append(": ").append(params);
}
entry.append("\n");
try{
out.write(entry.toString());
}catch(IOException ioe){
logging.warn("Couldn't write log entry",ioe);
return false;
}
return true;
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user) throws ServletException, IOException {
String logFileName=getLogFile(user);
if(logFileName==null) return false;
Writer out=openFile(logFileName);
if(out!=null){
try{
return writeEntry(req, resp, method, action, user, out);
}
finally{
closeFile(logFileName, out);
}
}
else return false;
}
}
| 7,377 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserAuthenticator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserAuthenticator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import org.wandora.modules.Module;
import org.wandora.modules.servlet.ModulesServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* The base interface for authenticators. Authenticators authenticate a
* user based on the received HTTP request. They may also hijack the request and
* even reply to it, for example to send back a login form. By completing the
* login form, the user will send the required login details to the authenticator
* and then it lets the user access other features.
* </p>
* <p>
* The result of the authentication is returned as an AuthenticationResult object.
* This has three fields. The authenticated indicates tells whether authentication
* succeeded. The responded field indicates whether a response was sent in case
* the authentication didn't succeed. The response could be an error message or
* a login form or something similar. Finally the user field contains the
* authenticated user. The user field may be set even if authentication fails.
* This would be the case if the user provided a correct user name and password
* but the user doesn't have the required privileges. Also, the user is not
* necessarily set even if authentication succeeds. This would be the case if
* anonymous was allowed.
* </p>
*
* @author olli
*/
public interface UserAuthenticator extends Module {
/**
* <p>
* Authenticates a user. If requiredRole is non-null, the logged in user
* must be of that role for the authentication to succeed. Otherwise there
* are two possible options in how to implement the authentication. It may
* be required that the user provides valid login details for authentication
* to succeed. Or it could be that anonymous logins are also authorised and
* the authentication succeeds without the user field set in the result.
* What exactly happens is implementation specific, possibly even dependent
* on the authenticator initialisation parameters.
* </p>
*
* @param requiredRole The role the user should have or null if no role is required.
* @param req The HTTP request.
* @param resp The HTTP response.
* @param method The method of the HTTP request.
* @return An AuthenticationResult what happened with the authentication.
* @throws IOException
* @throws AuthenticationException
*/
public AuthenticationResult authenticate(String requiredRole, HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method) throws IOException, AuthenticationException ;
/**
* A class containing information about the authentication. See
* UserAuthenticator documentation for details.
*/
public static class AuthenticationResult {
public AuthenticationResult(boolean authenticated, User user, boolean responded) {
this.authenticated=authenticated;
this.user=user;
this.responded=responded;
}
public boolean authenticated=false;
public User user=null;
public boolean responded=false;
}
}
| 4,017 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
UserStoreCopyTool.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/UserStoreCopyTool.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.MissingDependencyException;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* This is a module you might include in the modules config to move users
* from one user store to another. It's intended to be a one time move. Add
* it to the config file once, set it to autostart, start the server and it'll do
* its job. Then turn off the server and remove the module from the config.
*
* The user stores between which users are copied are specified with init params.
* Each store must be specified by name.
*
* @author olli
*/
public class UserStoreCopyTool extends AbstractModule {
protected UserStore fromStore;
protected ModifyableUserStore toStore;
protected String fromStoreName;
protected String toStoreName;
@Override
public Collection<org.wandora.modules.Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<org.wandora.modules.Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
if(fromStoreName!=null){
fromStore=manager.findModule(this, fromStoreName, UserStore.class);
if(fromStore==null) throw new MissingDependencyException(UserStore.class,fromStoreName);
}
if(toStoreName!=null){
toStore=manager.findModule(this, toStoreName, ModifyableUserStore.class);
if(toStore==null) throw new MissingDependencyException(ModifyableUserStore.class,toStoreName);
}
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("fromStore");
if(o!=null) fromStoreName=o.toString();
o=settings.get("toStore");
if(o!=null) toStoreName=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(fromStore==null || toStore==null){
if(fromStoreName==null) logging.error("fromStore not specified in init parameters");
if(toStoreName==null) logging.error("toStore not specified in init parameters");
throw new ModuleException("User stores not found");
}
else {
try{
performCopy();
}catch(UserStoreException use){
logging.error(use);
}
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
super.stop(manager);
}
public void performCopy() throws UserStoreException{
logging.info("Coping user store");
Collection<User> users=fromStore.getAllUsers();
for(User user : users){
User newUser=toStore.getUser(user.getUserName());
if(newUser==null) newUser=toStore.newUser(user.getUserName());
for(String role : user.getRoles()){
newUser.addRole(role);
}
for(String key : user.getOptionKeys()){
String value=user.getOption(key);
newUser.setOption(key, value);
}
newUser.saveUser();
}
logging.info("User copying done");
}
}
| 4,325 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DatabaseUserStore.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/DatabaseUserStore.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.DatabaseInterface;
import org.wandora.modules.DatabaseInterface.Row;
import org.wandora.modules.DatabaseInterface.Rows;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* A user store which stores users in a relational database. Needs a
* module implementing the DatabaseInterface to work. The user data is stored
* in three tables, which need to be created beforehand. Following sql script
* will generate the tables on MySQL, you may need to adjust it slightly for
* other database systems.
* </p>
*
<pre>
create table USERS(
ID bigint AUTO_INCREMENT primary key,
USERNAME varchar(256) not null collate utf8_bin
);
create table USER_ROLES(
USERID bigint not null references USERS(ID),
ROLE varchar(256) not null collate utf8_bin
);
create table USER_PROPS(
USERID bigint not null references USERS(ID),
PROPKEY varchar(256) not null collate utf8_bin,
PROPVALUE varchar(2048) collate utf8_bin
);
</pre>
*
* <p>
* You may prefix each table with a prefix of your choosing. Specify it in the
* initialisation parameters with tablePrefix.
* </p>
* <p>
* Any changes to the user store are immediately stored in the database when
* saveUser is called.
* </p>
*
* @author olli
*/
public class DatabaseUserStore extends AbstractModule implements ModifyableUserStore {
protected String tablePrefix="";
protected DatabaseInterface database;
protected final HashMap<String,DBUser> users=new HashMap<String,DBUser>();
protected void handleSQLException(SQLException sqle) throws UserStoreException {
logging.warn(sqle);
throw new UserStoreException("Error accessing user database",sqle);
}
@Override
public Collection<org.wandora.modules.Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<org.wandora.modules.Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(this, DatabaseInterface.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("tablePrefix");
if(o!=null) tablePrefix=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
database=manager.findModule(this,DatabaseInterface.class);
try{
fetchUsers();
}
catch(UserStoreException e){
throw new ModuleException(e);
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
database=null;
super.stop(manager);
}
@Override
public boolean deleteUser(String user) throws UserStoreException{
if(!commitDeleteUser(user)) return false;
synchronized(users){
users.remove(user);
return true;
}
}
@Override
public User newUser(String user) throws UserStoreException{
synchronized(users){
if(users.containsKey(user)) return null;
DBUser u=commitNewUser(user);
if(u==null) return null;
u.setUserStore(this);
users.put(user, u);
return u;
}
}
@Override
public boolean saveUser(User user) throws UserStoreException{
if(!commitUser((DBUser)user)) return false;
synchronized(users){
users.put(user.getUserName(),((DBUser)user).duplicate());
return true;
}
}
@Override
public Collection<User> findUsers(String key, String value) throws UserStoreException{
synchronized(users){
ArrayList<User> ret=new ArrayList<User>();
for(DBUser u : users.values()){
String option=u.getOption(key);
if(option!=null && option.equals(value)) ret.add(u.duplicate());
}
return ret;
}
}
protected void fetchUsers() throws UserStoreException {
Map<String,DBUser> newUsers=new LinkedHashMap<String,DBUser>();
try{
List<User> ret=new ArrayList<User>();
Rows userRows=database.query("select * from "+tablePrefix+"USERS order by ID");
Rows roleRows=database.query("select * from "+tablePrefix+"USER_ROLES order by USERID");
Rows propRows=database.query("select * from "+tablePrefix+"USER_PROPS order by USERID");
int rolePointer=0;
int propPointer=0;
for(Row userRow : userRows){
String userName=(String)userRow.get("username");
long id=(Long)userRow.get("id");
DBUser user=new DBUser(id,userName);
user.setUserStore(this);
while(rolePointer<roleRows.size()){
Row roleRow=roleRows.get(rolePointer);
if((Long)roleRow.get("userid")!=id) break;
rolePointer++;
String role=(String)roleRow.get("role");
user.addRole(role);
}
while(propPointer<propRows.size()){
Row propRow=propRows.get(propPointer);
if((Long)propRow.get("userid")!=id) break;
propPointer++;
String key=(String)propRow.get("propkey");
String value=(String)propRow.get("propvalue");
user.setOption(key, value);
}
newUsers.put(userName,user);
}
}catch(SQLException sqle){
handleSQLException(sqle);
return; // handleSQLException throws a UserException so nothing actually gets returned
}
synchronized(users){
users.clear();
users.putAll(newUsers);
}
}
private final Object modifyLock=new Object();
protected boolean commitUser(DBUser user) throws UserStoreException{
try{
long id=user.getId();
synchronized(modifyLock){
database.update("delete from "+tablePrefix+"USER_ROLES where USERID="+id);
database.update("delete from "+tablePrefix+"USER_PROPS where USERID="+id);
if(!user.getRoles().isEmpty()){
StringBuilder sb=new StringBuilder(
"insert into "+tablePrefix+"USER_ROLES (USERID,ROLE) values ");
boolean first=true;
for(String role : user.getRoles()){
if(!first) sb.append(", ");
else first=false;
sb.append("(").append(id).append(",'").append(database.sqlEscapeLen(role,256)).append("')");
}
database.update(sb.toString());
}
if(!user.getOptions().isEmpty()) {
StringBuilder sb=new StringBuilder(
"insert into "+tablePrefix+"USER_PROPS (USERID,PROPKEY,PROPVALUE) values ");
boolean first=true;
for(Map.Entry<String,String> e : user.getOptions().entrySet()){
String key=e.getKey();
String value=e.getValue();
if(!first) sb.append(", ");
else first=false;
sb.append("(").append(id).append(",'").append(database.sqlEscapeLen(key,256)).append("','").append(database.sqlEscapeLen(value,256)).append("')");
}
database.update(sb.toString());
}
// USER table itself doesn't have any modifyable information so no need to update that
return true;
}
}catch(SQLException sqle){
handleSQLException(sqle);
return false; // handleSQLException throws a UserException so nothing actually gets returned
}
}
protected boolean commitDeleteUser(String userName) throws UserStoreException{
try{
synchronized(modifyLock) {
Rows rows=database.query("select * from "+tablePrefix+"USERS where USERNAME='"+database.sqlEscape(userName)+"'");
if(rows.isEmpty()) return false;
long id=(Long)rows.get(0).get("id");
database.update("delete from "+tablePrefix+"USER_ROLES where USERID="+id);
database.update("delete from "+tablePrefix+"USER_PROPS where USERID="+id);
database.update("delete from "+tablePrefix+"USERS where ID="+id);
return true;
}
}catch(SQLException sqle){
handleSQLException(sqle);
return false; // handleSQLException throws a UserException so nothing actually gets returned
}
}
protected DBUser commitNewUser(String userName) throws UserStoreException{
try{
synchronized(modifyLock){
long id=(Long)database.insertAutoIncrement("insert into "+tablePrefix+"USERS (USERNAME) values ("+
"'"+database.sqlEscapeLen(userName, 256) +"')");
DBUser u=new DBUser(id,userName);
return u;
}
}
catch(SQLException sqle){
handleSQLException(sqle);
return null; // handleSQLException throws a UserException so nothing actually gets returned
}
}
@Override
public Collection<User> getAllUsers() throws UserStoreException {
synchronized(users){
ArrayList<User> ret=new ArrayList<User>();
for(DBUser user : users.values()){
ret.add(user.duplicate());
}
return ret;
}
}
@Override
public User getUser(String user) throws UserStoreException {
synchronized(users){
return users.get(user);
}
}
protected static class DBUser extends SimpleUser {
public DBUser(long id,String userName, HashMap<String, String> options, ArrayList<String> roles, UserStore userStore) {
super(userName, options, roles, userStore);
this.id=id;
}
public DBUser(long id,String userName, HashMap<String, String> options, ArrayList<String> roles) {
super(userName, options, roles);
this.id=id;
}
public DBUser(long id,String userName) {
super(userName);
this.id=id;
}
public DBUser(long id) {
this.id=id;
}
private long id;
public long getId(){return id;}
@Override
public DBUser duplicate() {
return new DBUser(id,userName, new HashMap<String,String>(options), new ArrayList<String>(roles),userStore);
}
}
}
| 12,219 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractControlledContext.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/AbstractControlledContext.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.Collection;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.GenericContext;
import org.wandora.modules.servlet.ModulesServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public abstract class AbstractControlledContext extends GenericContext {
protected UserAuthenticator authenticator;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(this, UserAuthenticator.class, deps);
return deps;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
authenticator=manager.findModule(this, UserAuthenticator.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
authenticator=null;
super.stop(manager);
}
protected UserAuthenticator.AuthenticationResult authenticate(String requiredRole, final HttpServletRequest req, final HttpServletResponse resp, final ModulesServlet.HttpMethod method) throws IOException, AuthenticationException{
return authenticator.authenticate(requiredRole, req, resp, method);
}
}
| 2,320 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
PasswordResendAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/PasswordResendAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.servlet.SendEmailAction;
import org.wandora.modules.servlet.Template;
import jakarta.servlet.http.HttpServletRequest;
/**
*
* @author olli
*/
public class PasswordResendAction extends SendEmailAction {
protected UserStore userStore;
protected String emailKey="email"; // the key used in the user object to store email
protected String emailParam="email"; // the key used in http request to supply email
@Override
protected Map<String, Object> getTemplateContext(Template template, HttpServletRequest req, HttpMethod method, String action, User user) throws ActionException {
Map<String,Object> context=super.getTemplateContext(template, req, method, action, user);
String userEmail=req.getParameter(emailParam);
if(userEmail==null || userEmail.length()==0) return null;
Collection<User> us=null;
try{
us=userStore.findUsers(emailKey, userEmail);
} catch(UserStoreException use){
return null;
}
if(us.isEmpty()) return null;
if(us.size()>1) logging.info("More than one user has email "+userEmail+", using only first");
User u=us.iterator().next();
context.put("user",u);
context.put("email",userEmail);
return context;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(UserStore.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("emailKey");
if(o!=null) emailKey=o.toString();
o=settings.get("emailParam");
if(o!=null) emailParam=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
userStore=manager.findModule(UserStore.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
userStore=null;
super.stop(manager);
}
}
| 3,430 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
BasicUserAuthenticator.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/BasicUserAuthenticator.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.utils.Base64;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* A simple user authenticator that performs standard HTTP authentication
* using the BASIC scheme. Even if you use this over a secure connection, this
* might still not be suitable for a production environment, except in specific
* circumstances. The reason is that all user password are stored as plain text
* in the user objects. Thus collecting user supplied password would be a very
* bad idea and go against good security practices. However, if the user passwords
* are assigned by the system, or there is only a limited number of users who
* are aware of the risks, this may still be a usable solution. In any case,
* this can be used in a development environment and later replaced with a more
* suitable solution.
* </p>
* <p>
* You can set the realm for the authentication using the realm initialisation
* parameter.
* </p>
*
* @author olli
*/
public class BasicUserAuthenticator extends AbstractModule implements UserAuthenticator {
public static final String PASSWORD_KEY="password";
protected String realm;
protected UserStore userStore;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(UserStore.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("realm");
if(o!=null) realm=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
userStore=manager.findModule(UserStore.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
userStore=null;
super.stop(manager);
}
protected AuthenticationResult replyNotAuthorized(String realm, HttpServletResponse resp) throws IOException {
resp.setHeader("WWW-Authenticate","BASIC realm=\""+realm+"\"");
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return new AuthenticationResult(false, null, true);
}
@Override
public AuthenticationResult authenticate(String requiredRole, HttpServletRequest req, HttpServletResponse resp, HttpMethod method) throws IOException, AuthenticationException {
String auth=req.getHeader("Authorization");
if(auth==null) return replyNotAuthorized(realm,resp);
if(!auth.toUpperCase().startsWith("BASIC ")) return replyNotAuthorized(realm,resp);
String encoded=auth.substring(6);
String credentials=new String(Base64.decode(encoded));
int ind=credentials.indexOf(":");
String userName;
String password="";
if(ind<0) userName=credentials;
else {
userName=credentials.substring(0,ind);
password=credentials.substring(ind+1);
}
try{
User user=userStore.getUser(userName);
if(user!=null) {
String storedPassword=user.getOption(PASSWORD_KEY);
if(storedPassword!=null && !storedPassword.equals(password)) return replyNotAuthorized(realm, resp);
if(requiredRole!=null && !user.isOfRole(requiredRole)) return replyNotAuthorized(realm,resp);
else return new AuthenticationResult(true, user, false);
}
else return replyNotAuthorized(realm,resp);
}catch(UserStoreException use){
throw new AuthenticationException(use);
}
}
}
| 5,004 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChangeUserAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/ChangeUserAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ActionException;
import org.wandora.modules.servlet.GenericTemplateAction;
import org.wandora.modules.servlet.ModulesServlet;
import org.wandora.modules.servlet.Template;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An action that changes something about a user. Can either be used
* on its own as a GenericTemplateAction, or as part of a ChainedAction
* where this action just does the user modification and some other action in
* the chain sends the response. If you intend to use this in chain mode, set
* the initialisation parameter chainMode to true, that will suppress all output
* from this action.
* </p>
* <p>
* What changes are done to the user are specified in the initialisation
* parameters. Thus this action is not suitable for situations where the change
* to be made to the user is specified in the HTTP request. You can use this for
* static changes to a user, for example to promote a user to the administrator
* role. The change is always the same, adding the administrator role.
* </p>
* <p>
* Small dynamic behaviour however can be added using the replacements system.
* This is only applied to the property values to be set, not the property keys
* or any role changes. You can use this, for example, to set a time stamp
* in the user properties for every request and thus have the last user access
* time.
* </p>
* <p>
* The changes to be made are specified using three initialisation parameters.
* These are addRoles, removeRoles and setProperties. addRoles and removeRoles
* specify roles which are to be added or removed, respectively. Each is a
* semicolon or line feed separated list of roles. The setProperties is list
* of key value pairs, separated by semicolons or line feeds. In each pair, the
* key and value are separated by an equals sign.
* </p>
*
* @author olli
*/
public class ChangeUserAction extends GenericTemplateAction {
protected Map<String,String> setProperties;
protected List<String> removeRoles;
protected List<String> addRoles;
/*
* If this action is set to chainMode then all output is suppressed and
* the action can be used as the first action in a ChainedAction. Otherwise
* the action generates normal GenericTemplaceAction output.
*/
protected boolean chainMode=false;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
protected Map<String, Object> getTemplateContext(Template template, HttpServletRequest req, ModulesServlet.HttpMethod method, String action, User user) throws ActionException {
if(user!=null){
for(String r : removeRoles){
user.removeRole(r);
}
for(String r : addRoles){
user.addRole(r);
}
for(Map.Entry<String,String> e : setProperties.entrySet()){
String key=e.getKey();
String value=e.getValue();
value=doReplacements(value, req, method, action, user);
if(value==null || value.length()==0) user.removeOption(key);
else user.setOption(key, value);
}
boolean isActivated=true;
try{
if(!user.saveUser()) isActivated=false;
}catch(UserStoreException use){
throw new ActionException(use);
}
if(chainMode){
return new HashMap<String, Object>(); // just return non-null to indicate success
}
else {
Map<String, Object> context=super.getTemplateContext(template, req, method, action, user);
context.put("isActivated",isActivated);
return context;
}
}
else return null;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
setProperties=new HashMap<String,String>();
removeRoles=new ArrayList<String>();
addRoles=new ArrayList<String>();
Object o=settings.get("removeRoles");
if(o!=null){
String[] split=o.toString().split("[;\\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
if(s.length()>0) removeRoles.add(s);
}
}
o=settings.get("addRoles");
if(o!=null){
String[] split=o.toString().split("[;\\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
if(s.length()>0) addRoles.add(s);
}
}
o=settings.get("setProperties");
if(o!=null){
String[] split=o.toString().split("[;\\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
int ind=s.indexOf("=");
String key=s.substring(0,ind).trim();
String value=s.substring(ind+1).trim();
setProperties.put(key,value);
}
}
o=settings.get("chainMode");
if(o!=null) chainMode=Boolean.parseBoolean(o.toString());
super.init(manager, settings);
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException {
if(chainMode){
Object o=getTemplateContext(null, req, method, action, user);
if(o==null) return false;
else return true;
}
else return super.handleAction(req, resp, method, action, user);
}
}
| 7,189 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChangeUserRolesAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/ChangeUserRolesAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
/**
* Use ChangeUserAction instead which does everything
* this action used to do but can also optionally change properties.
* This class is kept as an alias only for backwards compatibility.
*
* @deprecated
* @author olli
*/
public class ChangeUserRolesAction extends ChangeUserAction {
}
| 1,141 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
FileUserStore.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/usercontrol/FileUserStore.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.usercontrol;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.utils.JsonMapper;
/**
* <p>
* A user store that reads users from a json file. Also supports modifying
* the users and automatically saving the modified user store.
* </p>
* <p>
* Auto saving is turned on by default. It can be turned off with the
* initialisation parameter autoSave and setting it to false. The file name
* must be specified with the initialisation parameter userFile.
* </p>
*
* @author olli
*/
public class FileUserStore extends AbstractModule implements ModifyableUserStore {
protected final Map<String,User> users=new LinkedHashMap<String,User>();
protected String userFile;
protected long saveTime=10000;
protected boolean autoSaveRunning=false;
protected boolean autoSave=true;
protected final Object saveMonitor=new Object();
protected Thread saveThread;
protected boolean changed=false;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("autoSave");
if(o!=null) autoSave=Boolean.parseBoolean(o.toString());
o=settings.get("userFile");
if(o!=null) userFile=o.toString();
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(userFile==null) throw new ModuleException("userFile not specified");
if(!readJsonUsers(userFile)) throw new ModuleException("Couldn't read userFile");
changed=false;
if(autoSave){
autoSaveRunning=true;
saveThread=new Thread(new Runnable(){
@Override
public void run() {
saveThreadRun();
}
});
saveThread.start();
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
if(autoSaveRunning){
autoSaveRunning=false;
synchronized(saveMonitor){
saveMonitor.notifyAll();
}
try{
saveThread.join();
}catch(InterruptedException ie){}
saveThread=null;
}
super.stop(manager);
}
protected boolean readJsonUsers(String userFile){
try{
SimpleUser[] readUsers=new JsonMapper().readValue(new File(userFile), SimpleUser[].class);
synchronized(users){
users.clear();
for(int i=0;i<readUsers.length;i++){
readUsers[i].setUserStore(this);
users.put(readUsers[i].getUserName(),readUsers[i]);
}
return true;
}
}catch(IOException ioe){
logging.warn("Couldn't read Json user file",ioe);
return false;
}
}
protected void writeJsonUsers(String userFile){
try{
synchronized(users){
logging.info("Saving users");
new JsonMapper().writeValue(new File(userFile), users.values());
changed=false;
}
}catch(IOException ioe){
logging.warn("Couldn't write Json user file",ioe);
}
}
@Override
public Collection<User> getAllUsers() {
synchronized(users){
ArrayList<User> ret=new ArrayList<User>();
for(User u : users.values()){
ret.add(((SimpleUser)u).duplicate());
}
return ret;
}
}
@Override
public User getUser(String user) {
synchronized(users){
User u=users.get(user);
if(u==null) return null;
return ((SimpleUser)u).duplicate();
}
}
@Override
public User newUser(String user) {
synchronized(users){
if(users.containsKey(user)) return null;
User u=new SimpleUser(user);
((SimpleUser)u).setUserStore(this);
users.put(user,u);
changed=true;
return u;
}
}
@Override
public boolean saveUser(User user) {
synchronized(users){
User u=users.get(user.getUserName());
if(u==null) return false;
((SimpleUser)u).setOptions(new HashMap<String,String>(((SimpleUser)user).getOptions()));
((SimpleUser)u).setRoles(new ArrayList<String>(((SimpleUser)user).getRoles()));
changed=true;
}
return true;
}
@Override
public boolean deleteUser(String user) {
synchronized(users){
if(users.containsKey(user)){
users.remove(user);
changed=true;
return true;
}
else return false;
}
}
@Override
public Collection<User> findUsers(String key, String value) {
ArrayList<User> ret=new ArrayList<User>();
for(User u : users.values()){
String option=u.getOption(key);
if(option!=null && option.equals(value)) ret.add(u);
}
return ret;
}
protected void saveThreadRun(){
while(autoSaveRunning){
synchronized(saveMonitor){
try{
saveMonitor.wait(saveTime);
}catch(InterruptedException ie){}
}
if(changed){
writeJsonUsers(userFile);
}
}
}
}
| 6,950 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RedirectAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/RedirectAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class RedirectAction extends AbstractAction {
protected String redirectUrl;
/*
* There are small differences between the redirect codes. 302 is the original
* redirect, but its behavior is somewhat unspecified when it comes to the method
* (GET or POST). 303 is a http/1.1 code that dictates that GET should be used
* for the redirected request. 307 redirect should use the original method. 303
* and 307 being http/1.1 might not work in VERY old browsers.
*
* Furthermore, 301 means moved permanently as opposed to the temporary
* nature of the previous codes.
*/
protected int redirectCode=303;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o;
o=settings.get("redirectUrl");
if(o!=null) redirectUrl=o.toString();
o=settings.get("redirectCode");
if(o!=null) redirectCode=Integer.parseInt(o.toString());
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(redirectUrl==null) logging.warn("redirectUrl not specified");
super.start(manager);
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user) throws ServletException, IOException, ActionException {
resp.setStatus(redirectCode);
resp.setHeader("Location", redirectUrl);
return true;
}
}
| 3,156 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
SendEmailAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/SendEmailAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.EmailModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Sends an email composed using a template. This action extends GenericTemplateAction
* but behaves a bit differently than most of them. The template is used to compose
* the email, not to send a response to the actual action. In fact, no response is
* ever sent to the http request, instead you have to use this action through a
* ChainedAction and respond in the next action in the chain.
*
* Also note that this action extends CachedAction via GenericTemplateAction but does
* not in fact support caching. If you try to turn on caching, a warning is
* written to the log and caching is turned off. In fact, handleAction is overridden
* in such a way that no caching will take place regardless of whether it's turned on or not.
*
* @author olli
*/
public class SendEmailAction extends GenericTemplateAction {
protected EmailModule email;
protected String from=null;
protected String subject=null;
protected String recipients=null;
protected boolean parseSubject=false;
protected boolean parseRecipients=false;
protected boolean parseFrom=false;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
manager.requireModule(EmailModule.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("subject");
if(o!=null) subject=o.toString();
o=settings.get("recipient");
if(o!=null) recipients=o.toString();
o=settings.get("recipients");
if(o!=null) recipients=o.toString();
o=settings.get("from");
if(o!=null) from=o.toString();
o=settings.get("parseSubject");
if(o!=null) parseSubject=Boolean.parseBoolean(o.toString());
o=settings.get("parseRecipient");
if(o!=null) parseRecipients=Boolean.parseBoolean(o.toString());
o=settings.get("parseRecipients");
if(o!=null) parseRecipients=Boolean.parseBoolean(o.toString());
o=settings.get("parseFrom");
if(o!=null) parseFrom=Boolean.parseBoolean(o.toString());
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(caching) {
logging.warn("this action does not support caching, caching turned off");
caching=false;
}
email=manager.findModule(EmailModule.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
email=null;
super.stop(manager);
}
public static class EmailContent {
public String subject;
public String recipients;
public String from;
public String message;
}
public static EmailContent parseEmail(byte[] bytes, String encoding,boolean parseRecipients, boolean parseSubject, boolean parseFrom) throws IOException {
String content=new String(bytes,encoding);
EmailContent ret=new EmailContent();
for(int i=0;i<(parseRecipients?1:0)+(parseSubject?1:0)+(parseFrom?1:0);i++){
int ind=content.indexOf("\n");
if(ind<0) return null;
String line=content.substring(0, ind).trim();
if(line.length()==0) continue;
content=content.substring(ind+1);
int ind2=line.indexOf(":");
if(ind2<0) return null;
String key=line.substring(0,ind2).trim().toLowerCase();
String value=line.substring(ind2+1).trim();
if(key.equals("subject")){
ret.subject=value;
}
else if(key.equals("recipient") || key.equals("recipients")){
ret.recipients=value;
}
else if(key.equals("from")){
ret.from=value;
}
}
ret.message=content;
return ret;
}
protected boolean parseOutputAndSend(byte[] bytes,String contentType,String encoding) throws IOException{
String content=new String(bytes,encoding);
String sendSubject=subject;
String sendRecipients=recipients;
String sendFrom=from;
String mimeType=contentType+"; charset="+encoding.toLowerCase();
EmailContent ec=parseEmail(bytes, encoding, parseRecipients, parseSubject, parseFrom);
if(ec==null) {
logging.warn("unable to parse email headers");
return false;
}
content=ec.message;
if(parseSubject && ec.subject!=null) sendSubject=ec.subject;
else if(!parseSubject && ec.subject!=null) logging.warn("Found subject at the start of email but parseSubject is false");
if(parseRecipients && ec.recipients!=null) sendRecipients=ec.recipients;
else if(!parseRecipients && ec.recipients!=null) logging.warn("Found recipients at the start of email but parseRecipients is false");
if(parseFrom && ec.from!=null) sendFrom=ec.from;
else if(!parseFrom && ec.from!=null) logging.warn("Found from at the start of email but parseFrom is false");
String[] split=sendRecipients.split("\\s*,\\s*");
return email.send(Arrays.asList(split), sendFrom, sendSubject, content, mimeType);
}
@Override
public boolean handleAction(final HttpServletRequest req, final HttpServletResponse resp, final HttpMethod method, final String action, final User user) throws ServletException, IOException, ActionException {
Template template=getTemplate(req, method, action);
if(template==null) return false;
Map<String,Object> context=getTemplateContext(template, req, method, action, user);
if(context==null) return false;
ByteArrayOutputStream baos=new ByteArrayOutputStream();
template.process(context, baos);
return parseOutputAndSend(baos.toByteArray(), template.getMimeType(), template.getEncoding());
}
@Override
protected void returnOutput(InputStream cacheIn, HttpServletResponse resp) throws IOException {
// should never be called as handleAction is overridden bypassing all caching
throw new RuntimeException("returnOutput called in SendEmailAction");
}
@Override
protected boolean doOutput(HttpServletRequest req, HttpMethod method, String action, OutputProvider out, User user) throws ServletException, IOException {
// should never be called as handleAction is overridden bypassing all caching
throw new RuntimeException("doOutput called in SendEmailAction");
}
}
| 8,350 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ActionExceptionHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ActionExceptionHandler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import org.wandora.modules.Module;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An interface for handlers that can take care of ActionExceptions
* thrown when handling an HTTP request. By including a module that implements
* this interface, GenericContext will automatically use it whenever an ActionException
* inside it occurs. Note that the root servlet does not (necessarily) perform
* similarly. If you want to include custom ActionException handling, you should
* use a context for all your actions. GenericContext can be used as is for this
* purpose.
* </p>
* <p>
* See TemplateActionExceptionHandler for a generic implementation of this
* using templates.
* </p>
* <p>
* Implementations of this should not extends AbstractAction, or if they do,
* they need to take special care about dependency handling. The reason is that
* this will easily cause a circular dependency. AbstractAction will require a
* ServletModule. ServletModules, which GenericContext implements, may then
* optionally require an ActionExceptionHandler. If that is an AbstractAction,
* it will again look for a ServletModule and so on. So if you do extend
* AbstractAction, you will need to override getDependencies to break the
* circular dependency problem.
* </p>
*
* @author olli
*/
public interface ActionExceptionHandler extends Module {
/**
* Handles an exception that occurred when handling an HTTP request.
* The ActionException itself should contain the action where it occurred.
* The return value will act as if the original action return it. In other
* words, true indicates that the request was handled while false means that
* the context, or root servlet, should continue giving other actions a chance
* to handle it. Note that even returning false indicates that you have handled
* the exception in some way. If you decide not to handle the exception at all,
* rethrow it in the handler instead of returning either true or false. That,
* or any other exception thrown, will not be caught by this same handler,
* but may be caught by another handler higher up in the context tree.
*
* @param req The HTTP request.
* @param resp The HTTP request where the response can be written.
* @param method The HTTP method used with the request.
* @param user The authenticated user, or null if not applicable.
* @param ae The ActionException that caused this to be called.
* @return True if the action has been handled, false if other actions should
* still try to handle it.
* @throws ServletException
* @throws IOException
* @throws ActionException
*/
public boolean handleActionException(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, User user, ActionException ae) throws ServletException, IOException, ActionException ;
}
| 3,928 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ModulesServlet.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ModulesServlet.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Jdk14Logger;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.ModuleManager.ModuleSettings;
import org.wandora.modules.servlet.ServletModule.RequestListener;
import org.wandora.utils.ListenerList;
import org.wandora.utils.ParallelListenerList;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A HttpServlet that sets up the modules framework. This is the actual
* servlet implementation that the servlet container interfaces with. It sets up
* the modules framework at servlet initialisation and adds some basic modules
* into it before loading the configuration file and initialising all other
* modules. It sets a root ServletModule, with the module name rootServlet, so
* that actions can then interface with the actual servlet container. It also
* sets the variable servletHome to what should be the WEB-INF directory of
* the webapp. After this, it loads the modules framework configuration file from
* a file specified in the servlet configuration init parameter modulesconfig.
* If not specified, it tries modulesconfig.xml as the default value.
*
* @author olli
*/
public class ModulesServlet extends HttpServlet{
protected final ParallelListenerList<RequestListener> requestListeners=new ParallelListenerList<RequestListener>(RequestListener.class);
protected ModuleManager moduleManager;
protected ServletModule servletModule=new _ServletModule();
public static final String DEFAULT_BIND_ADDRESS="http://localhost:8080";
protected String bindAddress=null;
protected String servletHome;
public void addRequestListener(RequestListener listener){
requestListeners.addListener(listener);
}
public void removeRequestListener(RequestListener listener){
requestListeners.removeListener(listener);
}
@Override
public void destroy() {
moduleManager.stopAllModules();
super.destroy();
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
moduleManager=new ModuleManager();
servletHome=config.getServletContext().getRealPath("/")+"WEB-INF";
moduleManager.setVariable("servletHome", servletHome);
// SimpleLog log=new SimpleLog("ModulesServlet");
// log.setLevel(SimpleLog.LOG_LEVEL_DEBUG);
Log log=new Jdk14Logger("ModulesServlet");
moduleManager.setLogging(log);
String configFile=config.getInitParameter("modulesconfig");
if(configFile==null) {
configFile=config.getInitParameter("modulesConfig");
if(configFile==null) configFile="modulesconfig.xml";
}
bindAddress=config.getInitParameter("bindaddress");
if(bindAddress==null){
bindAddress=config.getInitParameter("bindAddress");
}
moduleManager.addModule(servletModule,new ModuleSettings("rootServlet"));
moduleManager.readXMLOptionsFile(configFile);
if(bindAddress==null){
bindAddress=moduleManager.getVariable("bindAddress");
if(bindAddress==null) bindAddress=DEFAULT_BIND_ADDRESS;
}
try{
moduleManager.autostartModules();
}catch(ModuleException me){
throw new ServletException("Unable to start modules.",me);
}
}
protected void returnNotHandled(HttpServletRequest req, HttpServletResponse resp,HttpMethod method) throws ServletException, IOException {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
protected void doMethod(final HttpServletRequest req, final HttpServletResponse resp,final HttpMethod method) throws ServletException, IOException {
final ServletException[] se=new ServletException[1];
final IOException[] ioe=new IOException[1];
final ActionException[] ae=new ActionException[1];
final boolean[] handledA=new boolean[]{false};
requestListeners.forEach(new ListenerList.EachDelegate<RequestListener>(){
private boolean handled=false;
@Override
public void run(RequestListener listener, Object... params) {
if(handled) return;
try{
handled=listener.handleRequest(req, resp, method, null);
if(handled) handledA[0]=true;
}
catch(ServletException ex){
handled=true;
se[0]=ex;
}
catch(IOException ex){
handled=true;
ioe[0]=ex;
}
catch(ActionException ex){
handled=true;
ae[0]=ex;
}
}
});
if(se[0]!=null) throw se[0];
else if(ioe[0]!=null) throw ioe[0];
else if(ae[0]!=null) {
throw new ServletException(ae[0]);
}
if(!handledA[0]) returnNotHandled(req,resp,method);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doMethod(req, resp, HttpMethod.GET);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doMethod(req, resp, HttpMethod.POST);
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doMethod(req, resp, HttpMethod.DELETE);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doMethod(req, resp, HttpMethod.PUT);
}
public static enum HttpMethod {
GET,POST,DELETE,HEAD,OPTIONS,PUT,TRACE
}
public class _ServletModule extends AbstractModule implements ServletModule {
@Override
public void addRequestListener(RequestListener listener){ ModulesServlet.this.addRequestListener(listener); }
@Override
public void removeRequestListener(RequestListener listener){ ModulesServlet.this.removeRequestListener(listener); }
@Override
public String getServletURL() {
String path=ModulesServlet.this.getServletContext().getContextPath();
return bindAddress+path;
}
@Override
public String getContextPath() {
return servletHome+"/";
}
}
}
| 7,780 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ActionException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ActionException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
/**
* <p>
* The primary exception type for Actions, or any RequestListener, to
* throw when handling an action. GenericContext provides some mechanisms to
* add exception handlers for this type of exception.
* </p>
*
* @author olli
*/
public class ActionException extends Exception {
protected ActionHandler action;
public ActionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ActionException(Throwable cause) {
super(cause);
}
public ActionException(String message, Throwable cause) {
super(message, cause);
}
public ActionException(String message) {
super(message);
}
public ActionException() {
}
public ActionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,ActionHandler action) {
super(message, cause, enableSuppression, writableStackTrace);
setAction(action);
}
public ActionException(Throwable cause,ActionHandler action) {
super(cause);
setAction(action);
}
public ActionException(String message, Throwable cause,ActionHandler action) {
super(message, cause);
setAction(action);
}
public ActionException(String message,ActionHandler action) {
super(message);
setAction(action);
}
public ActionException(ActionHandler action) {
setAction(action);
}
/**
* Gets the action where the exception occurred.
* @return The action.
*/
public ActionHandler getAction() {
return action;
}
/**
* Sets the action where this exception occurred.
* @param action The action.
*/
public void setAction(ActionHandler action) {
this.action = action;
}
}
| 2,740 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/AbstractAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.ReplacementsModule;
import org.wandora.modules.ScriptModule;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* The base class for action modules, that is modules that respond to
* an HTTP request and return some content. It implements
* ServletModule.RequestListener which makes it possible to register itself
* to ServletModules. In addition, it also implements ActionHandler which is
* needed if the action is used inside one of the context classes.
* </p>
* <p>
* If you extend this class directly, your main point of extension is the only
* abstract method, handleAction, and the basic Module initialisation methods.
* If you wish to be notified of every HTTP request without any filtering,
* override the handleRequest instead.
* </p>
* <p>
* This action reads parameters with following names from the initialisation
* parameters. actionParamKey can be used to specify the HTTP request parameter
* which contains the action id, this defaults to "action". action parameter
* contains the id of this action, alternatively, you can use parameter actions
* and provide a comma separated list of multiple ids, the default is to have no
* id associated with this action. defaultAction parameter can be set
* to "true" to make this a default action. If the action id is not specified
* in the request and this is a default action, it'll try to handle the action.
* Any parameter with its name prefixed with "httpheader." will be used to add
* custom HTTP headers in the response. The part following this prefix in the
* parameter name is not
* important, it only needs to be unique in the module. The actual header
* name and value are parsed from the contents of the element. It should
* contain the header name followed by a colon character (:) followed by
* the value.
* </p>
* <p>
* Note that custom HTTP headers can be added in the initialisation parameters
* but they don't get automatically in the response. Instead, you will need
* to call setHttpHeaders in your handleAction code to have them added.
* </p>
*
* @author olli
*/
public abstract class AbstractAction extends ScriptModule implements ServletModule.RequestListener, ActionHandler {
protected boolean isDefaultAction=false;
protected ServletModule servletModule;
protected String actionParamKey="action";
protected final Collection<String> handledActions=new HashSet<String>();
protected final HashMap<String,String> httpHeaders=new HashMap<String,String>();
protected void addHandledAction(String action){
this.handledActions.add(action);
}
protected void setActionParamKey(String key){
this.actionParamKey=key;
}
@Override
public Collection<org.wandora.modules.Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<org.wandora.modules.Module> deps=super.getDependencies(manager);
manager.requireModule(this,ServletModule.class, deps);
return deps;
}
protected boolean replacementsInitialized=false;
protected ReplacementsModule replacements=null;
/**
* Performs basic string replacement using a ReplacementsModule if
* one is available. Otherwise returns the value as is. See
* ReplacementsModule for more information. Adds certain things from the
* request in the context that will be passed to the replacements module.
* Context variable user contains the user, req contains the request and
* action contains the action name.
*
* @param value The value in which replacement is to be done.
* @param req The HTTP request where this call originated.
* @param method The method of the HTTP request.
* @param action The parsed action.
* @param user The logged in user, or null if not applicable.
* @return The value after replacements have been done.
*/
public String doReplacements(String value,HttpServletRequest req, ModulesServlet.HttpMethod method, String action, User user){
if(!replacementsInitialized){
// Could add some kind of locking but as it is, it doesn't really
// matter if two threads do this initialization.
replacements=moduleManager.findModule(this, ReplacementsModule.class);
replacementsInitialized=true;
}
// if replacements module is not used, then just return the string as is
if(replacements==null) return value;
HashMap<String,Object> context=new HashMap<String,Object>();
context.put("user", user);
context.put("request", req);
context.put("action", action);
return replacements.replaceValue(value, context);
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object actionParamKeyO=settings.get("actionParamKey");
if(actionParamKeyO!=null) this.actionParamKey=actionParamKeyO.toString();
Object actionsO=settings.get("actions");
if(actionsO!=null){
String[] actions=actionsO.toString().split(",");
for(String a : actions){
a=a.trim();
if(a.length()>0) this.addHandledAction(a);
}
}
Object actionO=settings.get("action");
if(actionO!=null){
String action=actionO.toString();
if(action.length()>0) this.addHandledAction(action);
}
Object defaultO=settings.get("defaultAction");
if(defaultO!=null) isDefaultAction=Boolean.parseBoolean(defaultO.toString());
// Http header parsing is done here in AbstractAction but they don't
// get automatically added to every request. Actions have to
// call setHttpHeaders to do that. This must be done prior to writing
// anything else to the response but after the action is sure that it's
// going to handle the action. CachedAction automatically does it as it
// has a mechanism to detect this point in action. For all other cases,
// the action implementation needs to do it.
for(Map.Entry<String,Object> e : settings.entrySet()){
if(e.getKey().startsWith("httpheader")){
String value=e.getValue().toString();
int ind=value.indexOf(":");
if(ind>0){
String key=value.substring(0,ind).trim();
value=value.substring(ind+1).trim();
httpHeaders.put(key,value);
}
}
}
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
servletModule=manager.findModule(this,ServletModule.class);
servletModule.addRequestListener(this);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
if(servletModule!=null) servletModule.removeRequestListener(this);
servletModule=null;
super.stop(manager);
}
/**
* Sets HTTP headers from a Map of key value pairs. You typically pass
* the field httpHeaders to this method if you wish to add them in the
* response.
*
* @param resp The HTTP response object.
* @param headers A Map containing the headers to be added.
*/
protected void setHttpHeaders(HttpServletResponse resp,Map<String,String> headers) {
for(Map.Entry<String,String> e : headers.entrySet()){
resp.setHeader(e.getKey(), e.getValue());
}
}
/**
* Handles this action. Prior to calling this action, it's already been
* determined that this action should try to handle the action by either
* matching the action request parameter with the action id of this action,
* or this being the default action. Perform any operations needed here and
* then write the response into the response object. You will typically want
* to call setHttpHeaders to set the HTTP headers in the response after you
* know that you definitely will handle the request but before you write
* anything else into the response stream. If for whatever reason this
* method shouldn't handle the request after all, return false. Otherwise
* return true.
*
* @param req The HTTP Request.
* @param resp The HTTP response.
* @param method The HTTP method of the request.
* @param action The parsed action id.
* @param user The logged in user, or null if not applicable.
* @return True if the action was handled and a response sent. False otherwise
* in which case other actions may try to handle this action.
* @throws ServletException
* @throws IOException
* @throws ActionException
*/
public abstract boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, User user) throws ServletException, IOException, ActionException ;
@Override
public boolean isHandleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method) {
String action=null;
if(this.actionParamKey!=null) action=req.getParameter(this.actionParamKey);
if(isDefaultAction && (action==null || action.length()==0) ) return true;
if(this.actionParamKey==null || this.handledActions.isEmpty() ) return false;
if(action==null) return false;
return this.handledActions.contains(action);
}
@Override
public boolean handleRequest(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, User user) throws ServletException, IOException, ActionException {
if(isHandleAction(req, resp, method)) {
String action=null;
if(actionParamKey!=null) action=req.getParameter(actionParamKey);
if(action==null && isDefaultAction && !handledActions.isEmpty()) action=handledActions.iterator().next();
return handleAction(req, resp, method, action, user);
}
else return false;
}
}
| 11,451 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ChainedAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ChainedAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An action that makes it possible to chain together two, or more,
* actions into one. This is useful if you have an action that already
* fits the situation but needs one little thing added to it. For example, you
* could just use GenericTemplateAction, but you also want to send an email.
* You can chain together a SendEmailAction and the GenericTemplateAction with
* a ChainedAction. The ChainedAction is the action that receives the actual
* HTTP request, it then passes it on to the first action in the chain, if the
* action succeeded, it passes it on to the next action and so on. Note that
* in most cases only one of the actions in the chain should write anything
* in the response object.
* </p>
* <p>
* You have other options as well to resolve the above use case. You could just
* extend GenericTemplateAction to make the action you need. Or, without
* extending the action, you could just pass in its template context a helper
* object that can do the other things you need to be done and then do them in
* the template.
* </p>
* <p>
* To use this action, give the chained actions in an initialisation parameter
* named chain as a semicolon separated list. Each action in the chain must be
* named (using the name attribute in the module, like naming modules normally)
* and then the names used in the chain parameter. Usually you don't specify
* any action keys (the action or actions parameter) for the chained actions to
* prevent them from being used directly outside the chain. Although in some
* cases this could be desirable too.
* </p>
*
* @author olli
*/
public class ChainedAction extends AbstractAction {
protected ArrayList<AbstractAction> chain;
protected ArrayList<String> chainNames;
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, String action, org.wandora.modules.usercontrol.User user) throws ServletException, IOException, ActionException {
for(AbstractAction a : chain){
boolean b=a.handleAction(req, resp, method, action, user);
if(!b) return false;
}
return true;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
for(String s : chainNames){
manager.requireModule(s, AbstractAction.class, deps);
}
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
chainNames=new ArrayList<String>();
Object o=settings.get("chain");
if(o!=null){
String[] s=o.toString().split(";");
for(int i=0;i<s.length;i++){
String n=s[i].trim();
if(n.length()>0) chainNames.add(n);
}
}
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
chain=new ArrayList<AbstractAction>();
for(String s : chainNames){
chain.add(manager.findModule(s, AbstractAction.class));
}
if(chain.isEmpty()) logging.warn("Chain is empty");
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
chain=new ArrayList<AbstractAction>();
super.stop(manager);
}
}
| 4,839 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GenericContext.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/GenericContext.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.usercontrol.User;
import org.wandora.utils.ListenerList;
import org.wandora.utils.ParallelListenerList;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* A base for context modules. Context modules split a ServletModule into
* several different contexts. The context modules themselves are also
* ServletModules, they just take some of the root servlet module requests and
* forward them to actions registered to the specific context module. Actions see
* the context as any other ServletModule.
* </p>
* <p>
* Context modules may do something to the request before forwarding it, for
* example to restrict the use of the other modules registered to it. This could,
* for example, be user authentication with a username and a password, or checking
* that the request originates from localhost or something similar. You could also
* just add more specific logging for each request and the unconditionally pass
* on the request.
* </p>
* <p>
* The GenericContext contains some common features, and can serve as a base class
* for other contexts, although it's not required to extend it. You can also just
* directly implement ServletModule and appear as a servlet to other modules.
* Naturally you will also need to implement ServletModule.RequestListener to
* register your context to the root servlet module. It is also recommended that
* you implement ActionHandler, which adds some features to the RequestListener
* and aids in forwarding requests.
* </p>
* <p>
* GenericContext is not abstract and can be used on its own for some purposes.
* It can be used to add custom exception handling for actions inside the context,
* or to group actions by request path or local server directory.
* </p>
* <p>
* Grouping actions by request path works with the initialisation parameter
* urlPrefix. This sets a prefix that the request path must use for the request
* to be passed in this context. The prefix is also removed from the request so
* that you can nest more urlPrefix restricted contexts inside.
* </p>
* <p>
* The local context path can be changed with the contextPath initialisation
* parameter. By default the context path is the server path. Actions may use
* this as a basis for accessing their files, but are not required to. The
* contextPath resets this path. You can also use contextDir initialisation
* parameter to set both urlPrefix and contextPath at the same time. For example,
* if your server directory has a subdirectory "webapp", then setting contextPath
* to "webapp" would set that directory as the default path for actions in this
* context, and would pass the request to them only when the request has the path
* prefix "webapp".
* </p>
* <p>
* Another thing that GenericContext does without any extending is provide a hook
* for exception handling in actions. This is done by including any module that
* implements ActionExceptionHandler. GenericContext uses it as an optional
* dependency, so one will be found automatically if you define it in your config.
* To have different exception handlers for different contexts, use the priority
* or useService mechanics to specify which one to use with which context.
* Whenever an ActionException occurs within an action inside this context,
* it'll be given to the exception handler if one is available. Other exceptions
* than ActionExceptions won't be caught by the handler. See ActionExceptionHandler
* for more details.
* </p>
* <p>
* Overriding classes should override at least doForwardRequest, which checks if the
* request should be forwarded on. You can implement access restrictions by
* just overriding this. You may also want to override isHandleAction, it is
* one of the first checks after receiving a request. Basically it checks if any
* of the registered actions is going to be interested in the request, if not,
* the context will drop the request immediately. Naturally you may also
* override handleRequest to do your own processing and then possibly call the
* super implementation.
* </p>
* <p>
* In the initialisation parameters, you may set checkActions to false to disable
* the initial check of whether any registered actions are interested in the request.
* The initial check is possibly only for actions implementing ActionHandler,
* if any of your actions does not implement ActionHandler, you must disable the
* initial check or they will never receive the requests.
* </p>
* <p>
* You can set the parameter exceptionOnAuthentication to false to disable throwing
* of exceptions when user fails to authenticate, or generally just when
* doForwardRequest returns a value that the request should not be forwarded. The
* default behaviour is to throw an exception which will then be handled by the
* previous context, or the root servlet, in some way, most likely as presenting
* an error of some kind to the user. If this behaviour is disabled, then
* handleRequest will just simply return false and the previous context will try
* other possible handlers. Thus you can have behaviour where this context handles
* requests if the user is logged in, but if they aren't, it's not strictly an
* error condition.
* </p>
*
* @author olli
*/
public class GenericContext extends AbstractModule implements ServletModule, ServletModule.RequestListener, ActionHandler {
protected ServletModule servlet;
protected boolean checkActions=true;
protected ActionExceptionHandler exceptionHandler=null;
protected boolean exceptionOnAuthentication=true;
protected String authenticationErrorMessage="Authentication error";
protected String urlPrefix;
protected String contextPath;
protected final ParallelListenerList<RequestListener> requestListeners=new ParallelListenerList<RequestListener>(RequestListener.class);
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
ServletModule m=manager.requireModule(this, ServletModule.class, deps);
if(m==this) throw new ModuleException("Got itself as the servlet module. Modules are misconfigured.");
manager.optionalModule(this, ActionExceptionHandler.class, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("checkActions");
if(o!=null && o.toString().equalsIgnoreCase("false")) checkActions=false;
o=settings.get("exceptionOnAuthentication");
if(o!=null) exceptionOnAuthentication=Boolean.parseBoolean(o.toString());
o=settings.get("authenticationErrorMessage");
if(o!=null) authenticationErrorMessage=o.toString();
o=settings.get("contextDir");
if(o!=null) {
urlPrefix=o.toString().trim();
if(!urlPrefix.endsWith(File.separator)) urlPrefix+=File.separator;
contextPath=urlPrefix;
if(!File.separator.equals("/")) urlPrefix=urlPrefix.replace(File.separator, "/");
}
o=settings.get("urlPrefix");
if(o!=null) urlPrefix=o.toString().trim();
o=settings.get("contextPath");
if(o!=null) {
contextPath=o.toString().trim();
if(!contextPath.endsWith("/")) contextPath+="/";
}
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
servlet=manager.findModule(this, ServletModule.class);
if(servlet==this) throw new ModuleException("Got itself as the servlet module. Modules are misconfigured.");
servlet.addRequestListener(this);
exceptionHandler=manager.findModule(this, ActionExceptionHandler.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
servlet.removeRequestListener(this);
servlet=null;
super.stop(manager);
}
@Override
public void addRequestListener(RequestListener listener) {
requestListeners.addListener(listener);
}
@Override
public void removeRequestListener(RequestListener listener) {
requestListeners.removeListener(listener);
}
@Override
public String getServletURL() {
if(servlet==null) return null;
else return servlet.getServletURL()+urlPrefix;
}
@Override
public String getContextPath() {
if(contextPath!=null) {
if(contextPath.startsWith("/")) return contextPath;
else return servlet.getContextPath()+contextPath;
}
else return servlet.getContextPath();
}
private HttpServletRequest wrapRequest(final HttpServletRequest req){
if(urlPrefix==null) return req;
String prefix=urlPrefix;
String request=req.getRequestURI();
if(!prefix.startsWith("/") && request.startsWith("/")) prefix="/"+prefix;
if(!request.endsWith("/") && prefix.endsWith("/") && (request+"/").equals(prefix))
prefix=prefix.substring(0, prefix.length()-1);
if(!request.startsWith(prefix)) return null;
final String fPrefix=prefix;
return new HttpServletRequestWrapper(req){
@Override
public String getContextPath() {
return fPrefix;
}
};
}
/**
* <p>
* Checks if a request should be forwarded to the registered listeners.
* The return value is in the form of a ForwardResult object. This combines
* multiple things about how the request can be handled. See its documentation
* for more detail.
* </p>
* <p>
* The default implementation simply returns
* new ForwardResult(true, false, null), thus forwarding all requests without
* any additional handling.
* </p>
*
* @param req The HTTP request.
* @param resp The HTTP response.
* @param method The HTTP method.
* @return A ForwardResult object indicating what to do, or what has been done,
* with the request.
* @throws ServletException
* @throws IOException
* @throws ActionException
*/
protected ForwardResult doForwardRequest(final HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method) throws ServletException, IOException, ActionException {
if(urlPrefix!=null){
ForwardResult ret=new ForwardResult(true, false, null);
ret.request=wrapRequest(req);
if(ret.request==null) return null;
return ret;
}
else return new ForwardResult(true, false, null);
}
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, ModulesServlet.HttpMethod method, final User user) throws ServletException, IOException, ActionException {
try{
if(checkActions){
if(!isHandleAction(request, response, method)) return false;
}
ForwardResult fres=doForwardRequest(request, response, method);
if(!fres.forward){
if(exceptionOnAuthentication && !fres.responded) {
// For more specific messages, throw this exception in doForwardRequest
// of your subclass.
throw new ActionAuthenticationException(authenticationErrorMessage,this,fres.user);
}
return fres.responded;
}
final User authenticatedUser=(fres.user!=null?fres.user:user);
final ServletException[] se=new ServletException[1];
final ActionException[] ae=new ActionException[1];
final IOException[] ioe=new IOException[1];
final boolean[] handledA=new boolean[]{false};
final HttpServletRequest req=(fres.request!=null?fres.request:request);
final HttpServletResponse resp=(fres.response!=null?fres.response:response);
final ModulesServlet.HttpMethod meth=(fres.method!=null?fres.method:method);
requestListeners.forEach(new ListenerList.EachDelegate<RequestListener>(){
private boolean handled=false;
@Override
public void run(RequestListener listener, Object... params) {
if(handled) return;
try{
handled=listener.handleRequest(req, resp, meth, authenticatedUser);
if(handled) handledA[0]=true;
}
catch(ServletException ex){
handled=true;
se[0]=ex;
}
catch(IOException ex){
handled=true;
ioe[0]=ex;
}
catch(ActionException ex){
handled=true;
ae[0]=ex;
}
}
});
if(se[0]!=null) throw se[0];
else if(ioe[0]!=null) throw ioe[0];
else if(ae[0]!=null) throw ae[0];
return handledA[0];
}
catch(ActionException ae){
if(exceptionHandler!=null) {
return exceptionHandler.handleActionException(request, response, method, user, ae);
}
else throw ae;
}
}
/**
* <p>
* Gets the Action that will probably handle the given request.
* Note that this only returns the first action that gets the opportunity to handle the request
* that claims that it can handle it. The action might later decide not to handle the request
* in which case the request is passed to the next action that claims it can handle the request.
* So this method is really only a guess at what action will probably handle the request.
* </p>
* <p>
* Furthermore, this check depends on actions implementing the ActionHandler
* interface. Actions in general are not required to do this, although it is
* recommended that they do. If they don't, this method will just skip over
* them and never return any such action. However, when the request is actually
* handled by this context, even actions not implementing ActionHandler will
* be offered a chance to handle it. Thus it could end up handling the request,
* even before the action returned by this method.
* </p>
*
* @param req The HTTP request.
* @param resp The HTTP response.
* @param method The method of the HTTP request.
* @return The action that will first get the opportunity to handle the request
* and that claims that it will try to handle it.
*/
public ActionHandler getHandlingAction(final HttpServletRequest req, final HttpServletResponse resp, final ModulesServlet.HttpMethod method) {
final ActionHandler[] ret=new ActionHandler[]{null};
requestListeners.forEach(new ListenerList.EachDelegate<RequestListener>(){
@Override
public void run(RequestListener listener, Object... params) {
if(ret[0]!=null) return;
if(listener instanceof ActionHandler){
if(((ActionHandler)listener).isHandleAction(req, resp, method)){
ret[0]=(ActionHandler)listener;
}
}
}
});
return ret[0];
}
@Override
public boolean isHandleAction(final HttpServletRequest req, final HttpServletResponse resp, final ModulesServlet.HttpMethod method) {
if(!checkActions) return true;
HttpServletRequest wrappedReq=wrapRequest(req);
if(wrappedReq==null) return false;
return getHandlingAction(wrappedReq, resp, method)!=null;
}
/**
* <p>
* A helper class to contain information about forwarding a request
* to actions. It has three fields. The forward field simply indicates
* whether the request should be forwarded on. The responded field
* indicates whether a response has already been sent to the user. This
* could be the case, for example, if a login page is sent as a reply and
* the request should not be forwarded until the user has logged in. Finally,
* the user field contains the logged in user, or null if not relevant or not
* logged in.
* </p>
* <p>
* All three parameters can be passed straight to the constructor in the order
* forward, responded, user. There is also a two-parameter constructor without
* the user, which will then be set to null. A normal forward with no other
* handling would be new ForwardResult(true,false,null) and normal blocking
* new ForwardResult(false,false,null). If you resolved a user, add it as
* the last parameter in case the login attempt succeeded.
* </p>
*/
public static class ForwardResult {
public ForwardResult(){}
public ForwardResult(boolean forward,boolean responded){
this(forward, responded, null);
}
public ForwardResult(boolean forward,boolean responded,User user){
this.forward=forward;
this.responded=responded;
this.user=user;
}
/**
* Indicates if the request should be forwarded on to other actions.
*/
public boolean forward;
/**
* Indicates if a reply has already been sent to the request. For
* example, you could decide not to forward the request, and set
* forwarded=false, and then send a login page to give the user a chance
* to login. Thus you would set responded=true because you already sen
* a response. This will prevent an error message from being sent.
*/
public boolean responded;
/**
* The user that's logged in. You should somehow resolve this from
* the authentication details in the request and then set the field.
* If authentication is not relevant, or the user failed to login, set
* to null.
*/
public User user;
/**
* Overwritten request object. If non-null, should use this as the
* request object when forwarding the request.
*/
public HttpServletRequest request;
/**
* Overwritten response object. If non-null, should use this as the
* response object when forwarding the request.
*/
public HttpServletResponse response;
/**
* Overwritten method. If non-null, should use this as the
* method when forwarding the request.
*/
public ModulesServlet.HttpMethod method;
}
}
| 20,401 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StaticTemplateContextProvider.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/StaticTemplateContextProvider.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.modules.servlet;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* This class can be used to define a default context for template
* managers. See TemplateManager for more details.
* </p>
* <p>
* The context for this module is defined in the initialisation parameters the
* same way as in TemplateManager or templates. Parameters with the prefix
* "context." are added to the context with the prefix removed from the parameter
* name.
* </p>
*
* @author olli
*/
public class StaticTemplateContextProvider extends AbstractModule implements TemplateContextProvider {
protected Map<String,Object> context;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
context=new HashMap<String, Object>();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("context.")){
context.put(key.substring("context.".length()),e.getValue());
}
}
context=Collections.unmodifiableMap(context);
super.init(manager, settings);
}
@Override
public Map<String, Object> getTemplateBaseContext() {
return context;
}
}
| 2,270 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
VelocityEngineModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/VelocityEngineModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.util.Map;
import java.util.Properties;
import org.apache.velocity.app.VelocityEngine;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* A module that makes an Apache Velocity engine available for
* any VelocityTemplates. You must include this in the modules framework
* to be able to use VelocityTemplates. All the initialisation parameters
* are given as is to the engine as initialisation properties. See Velocity
* documentation for property names. Normal AbstractModule parameter handling
* still applies as well.
*
*
* @author olli
*/
public class VelocityEngineModule extends AbstractModule {
protected VelocityEngine engine;
protected Properties engineProperties;
public VelocityEngine getEngine(){
return engine;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
engineProperties=new Properties();
for(Map.Entry<String,Object> e : settings.entrySet()){
Object value=e.getValue();
if(!(value instanceof String)) continue;
String key=e.getKey();
engineProperties.setProperty(key, value.toString());
}
}
@Override
public void start(ModuleManager manager) throws ModuleException {
engine=new VelocityEngine();
engine.init(engineProperties);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
engine=null;
super.stop(manager);
}
}
| 2,510 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
RequestForwarder.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/RequestForwarder.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class RequestForwarder extends CachedAction {
protected Map<String,String> additionalParams;
protected List<String> forwardParams;
protected boolean forwardAllParams=false;
protected String destinationProtocol;
protected String destinationHost;
protected int destinationPort;
protected String destinationPath;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
additionalParams=new LinkedHashMap<String,String>();
forwardParams=new ArrayList<String>();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("additionalParam.")){
key=key.substring("additionalParam.".length());
Object o=e.getValue();
if(o==null) additionalParams.put(key,null);
else additionalParams.put(key,o.toString());
}
}
Object o;
o=settings.get("forwardParams");
if(o!=null){
String[] split=o.toString().split("[;\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
if(s.length()>0) forwardParams.add(s);
}
}
o=settings.get("forwardAllParams");
if(o!=null) forwardAllParams=Boolean.parseBoolean(o.toString());
Pattern destinationParser=Pattern.compile("^(?:(http(?:s)?)://)?([^/:]+)(?::(\\d+))?(?:(/.*))?$");
o=settings.get("destination");
if(o!=null) {
Matcher m=destinationParser.matcher(o.toString());
if(m.matches()){
destinationProtocol=m.group(1);
if(destinationProtocol==null || destinationProtocol.length()==0) destinationProtocol="http";
destinationHost=m.group(2);
String destinationPortS=m.group(3);
destinationPath=m.group(4);
if(destinationPath==null || destinationPath.length()==0) destinationPath="/";
if(destinationPortS!=null && destinationPortS.length()>0) destinationPort=Integer.parseInt(destinationPortS);
else destinationPort=-1; // this gets translated to protocol default later
}
}
super.init(manager, settings);
}
protected Map<String,String> getSendParams(HttpServletRequest req){
Map<String,String> params=new LinkedHashMap<String,String>();
if(forwardAllParams){
for(String s : forwardParams){
String v=req.getParameter(s);
params.put(s,v);
}
}
else {
for(String s : forwardParams){
String v=req.getParameter(s);
if(v!=null) params.put(s,v);
}
}
params.putAll(additionalParams);
return params;
}
protected String makeSendParamString(HttpServletRequest req){
Map<String,String> params=getSendParams(req);
StringBuilder paramString=new StringBuilder();
for(Map.Entry<String,String> e : params.entrySet()){
try{
String value=e.getValue();
if(paramString.length()>0) paramString.append("&");
paramString.append(URLEncoder.encode(e.getKey(), "UTF-8"));
paramString.append("=");
paramString.append(URLEncoder.encode(value, "UTF-8"));
}catch(UnsupportedEncodingException uee){
throw new RuntimeException(uee); // shouldn't happen, hardcoded UTF-8
}
}
return paramString.toString();
}
@Override
protected void returnOutput(InputStream cacheIn, HttpServletResponse resp) throws IOException {
try{
Map<String,String> metadata=readMetadata(cacheIn);
String contentType=metadata.get("contentType");
if(contentType.length()>0) resp.setContentType(contentType);
String encoding=metadata.get("encoding");
if(encoding.length()>0) resp.setCharacterEncoding(encoding);
super.returnOutput(cacheIn, resp);
}
finally{
cacheIn.close();
}
}
@Override
protected boolean doOutput(HttpServletRequest req, HttpMethod method, String action, OutputProvider out, org.wandora.modules.usercontrol.User user) throws ServletException, IOException {
logging.debug("Start forwarding request");
HttpURLConnection connection;
String path=destinationPath;
String paramString=makeSendParamString(req);
if(path.indexOf("?")>0) path+="&"+paramString;
else path+="?"+paramString;
connection=(HttpURLConnection)new URL(destinationProtocol,destinationHost,destinationPort,path).openConnection();
int response=connection.getResponseCode();
if(response!=HttpURLConnection.HTTP_OK) {
logging.info("Got response code "+response);
return false;
}
InputStream in;
try{
in=connection.getInputStream();
}catch(IOException ioe){
logging.warn(ioe);
return false;
}
logging.debug("Starting response");
Map<String,String> metadata=new LinkedHashMap<String,String>();
String contentType=connection.getContentType();
if(contentType==null) contentType="";
String encoding=connection.getContentEncoding();
if(encoding==null) encoding="";
metadata.put("contentType",contentType);
metadata.put("encoding",encoding);
OutputStream outStream=out.getOutputStream();
try{
writeMetadata(metadata, outStream);
byte[] buf=new byte[2048];
int read;
while( (read=in.read(buf))!=-1 ){
outStream.write(buf,0,read);
}
}
finally{
outStream.close();
}
return true;
}
@Override
protected String getCacheKey(HttpServletRequest req, HttpMethod method, String action) {
Map<String,String> params=getSendParams(req);
params.put("requestAction",action);
return buildCacheKey(params);
}
}
| 8,254 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TemplateActionExceptionHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/TemplateActionExceptionHandler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An implementation of ActionExceptionHandler, a module that handles
* exceptions thrown by other actions. This handler uses a template to
* produce the result, much like GeneritTemplateAction. This behaves much
* the same way as GenericTemplateHandler, but does not extend from it, the
* reason being a circular dependency problem (See ActionExceptionHandler
* documentation for more about this).
* </p>
* <p>
* This uses initialisation parameters templateKey, forwardRequestParameters and
* prefixes context. and defaultRequestParameter. in exactly the same way as
* GenericTemplateAction does, refer to its documentation.
* </p>
* <p>
* Three additional variables are added to the template context. exception contains
* the exception that was caught, errorMessage contains the error message from the
* exception, this may or may not be user friendly. Finally, trace contains a
* stack trace of the exception.
* </p>
*
* @author olli
*/
public class TemplateActionExceptionHandler extends AbstractModule implements ActionExceptionHandler {
public static final String EXCEPTION_ACTION="$EXCEPTION";
protected String requestContextKey="request";
protected TemplateManager templateManager;
protected String templateKey;
protected ArrayList<String> forwardRequestParameters;
protected HashMap<String,String> defaultRequestParameters;
protected final HashMap<String,Object> staticContext=new HashMap<String,Object>();
public void putStaticContext(String key,Object o){
staticContext.put(key,o);
}
protected Template getTemplate(HttpServletRequest req, HttpMethod method, String action){
return templateManager.getTemplate(templateKey, null);
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(this,TemplateManager.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
forwardRequestParameters=new ArrayList<String>();
defaultRequestParameters=new HashMap<String,String>();
Object o=settings.get("templateKey");
if(o!=null) templateKey=o.toString();
o=settings.get("forwardRequestParameters");
if(o!=null) {
String[] split=o.toString().split("[;\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
if(s.length()>0) forwardRequestParameters.add(s);
}
}
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("context.")){
staticContext.put(key.substring("context.".length()),e.getValue());
}
else if(key.startsWith("defaultRequestParameter.")){
String param=key.substring("defaultRequestParameter.".length());
defaultRequestParameters.put(param,e.getValue().toString());
}
}
}
@Override
public void start(ModuleManager manager) throws ModuleException {
templateManager=manager.findModule(this,TemplateManager.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
templateManager=null;
super.stop(manager);
}
protected HashMap<String,Object> getStaticTemplateContext(){
HashMap<String,Object> params=new HashMap<String,Object>();
params.putAll(templateManager.getDefaultContext());
params.putAll(staticContext);
return params;
}
protected LinkedHashMap<String,String> getForwardedParameters(HttpServletRequest req){
LinkedHashMap<String,String> params=new LinkedHashMap<String, String>();
for(String s : forwardRequestParameters){
String value=req.getParameter(s);
if(value==null) {
value=defaultRequestParameters.get(s);
if(value==null) continue;
}
params.put(s,value);
}
return params;
}
protected Template getTemplate(HttpServletRequest req, HttpMethod method, ActionException exception) {
return templateManager.getTemplate(templateKey, null);
}
protected HashMap<String, Object> getTemplateContext(Template template, HttpServletRequest req, HttpMethod method, User user, ActionException ae) {
HashMap<String,Object> context=getStaticTemplateContext();
context.put(requestContextKey,req);
context.putAll(template.getTemplateContext());
context.putAll(getForwardedParameters(req));
context.put("user",user);
String errorMessage="Unspecified error";
String trace=null;
if(ae!=null) {
Throwable e=ae;
while(e!=null){
String message=e.getMessage();
if(message!=null && !(e.getCause()!=null && message.equals(e.getCause().toString())) ) {
errorMessage=message;
break;
}
e=e.getCause();
}
StringWriter sw=new StringWriter();
PrintWriter pw=new PrintWriter(sw);
ae.printStackTrace(pw);
pw.flush();
trace=sw.toString();
}
context.put("exception",ae);
context.put("errorMessage",errorMessage);
context.put("errorTrace",trace);
return context;
}
@Override
public boolean handleActionException(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, User user, ActionException ae) throws ServletException, IOException, ActionException {
Template template=getTemplate(req, method, ae);
if(template==null) return false;
HashMap<String,Object> context=getTemplateContext(template, req, method, user, ae);
if(context==null) return false;
String contentType=template.getMimeType();
String encoding=template.getEncoding();
if(contentType!=null) resp.setContentType(contentType);
if(encoding!=null) resp.setCharacterEncoding(encoding);
template.process(context, resp.getOutputStream());
return true;
}
}
| 8,043 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CachedAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/CachedAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.cache.CacheService;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* This is a base class for actions that take advantage of caching
* services. You can naturally also directly use the caching service without
* deriving from this class, but many common operations are already done here.
* </p>
* <p>
* As described in the CacheService class, the basic idea in caching is that
* each cached page has a unique key identifying it. If in the future you
* need a page with a key that has already been cached, you can just return
* the cached page instead. The key itself is just any string that identifies the
* page. As such, everything that affects the page has to be somehow included
* in the key. This class contains a method, buildCacheKey, that takes a String
* map and builds a cache key based on that. The key will essentially be a
* serialisation of the Map. It is not required that you use this method
* to make the key but it is suitable for most situations.
* </p>
* <p>
* Obviously it is not useful to cache actions that are highly dynamic
* and requests with the exact same key are unlikely to happen often.
* </p>
* <p>
* To have an action use caching at all, the caching parameter in init parameters
* has to be set to true. By default caching is turned off. This is because many
* actions derive from this class that could potentially benefit from caching
* in some situations but not always.
* </p>
* <p>
* When extending this class, you have to override at least the doOutput method,
* which writes the page into a stream. The stream might either be returned
* directly, or it may be written to a disk from where a copy is then automatically
* returned to the request.
* </p>
* <p>
* You can also override returnOutput, which forwards
* data from an input stream into an HTTP response. The input stream might be
* coming from a cached file, or directly from do Output. The default implementation
* sets the HTTP headers possibly defined in AbstractAction and then copies the
* output directly. If you wish to set additional headers, such as content type
* or character encoding, the way to do it is to use writeMetadata in doOutput,
* which writes some extra information at the start of the stream, and then
* readMetadata at returnOutput, which reads it. Then you can add headers, or
* do anything else necessary, based on the metadata. The writing and reading
* of metadata must always be done symmetrically.
* </p>
*
* @author olli
*/
public abstract class CachedAction extends AbstractAction {
/**
* The cache service used to cache this action.
*/
protected CacheService cache;
/**
* Is caching turned on.
*/
protected boolean caching=false;
protected ExecutorService threadPool=null;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.optionalModule(this,CacheService.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
Object o=settings.get("caching");
if(o!=null && o.toString().equalsIgnoreCase("true")) caching=true;
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
cache=manager.findModule(this,CacheService.class);
if(caching && cache==null) logging.info("Caching is set to true but no caching module found");
threadPool=Executors.newCachedThreadPool();
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
cache=null;
threadPool.shutdown();
try{
if(!threadPool.awaitTermination(5, TimeUnit.SECONDS)){
threadPool.shutdownNow();
}
}catch(InterruptedException ie){}
super.stop(manager);
}
/**
* Builds a cache key from a Map of Strings. Essentially serialises
* the map, with the keys having been sorted so that the same set of key-value
* pairs always returns the same cache key, even if the keys are returned
* in different order from the maps.
*
* @param params A map of key value pairs used in the cache key.
* @return A cache key.
*/
public static String buildCacheKey(Map<String,String> params){
StringBuilder sb=new StringBuilder();
ArrayList<String> keys=new ArrayList<String>(params.keySet());
Collections.sort(keys);
for(String key : keys){
String value=params.get(key);
if(sb.length()>0) sb.append(";");
key=key.replace("\\","\\\\").replace("=", "\\=").replace(";","\\s");
value=value.replace("\\","\\\\").replace(";","\\s");
sb.append(key);
sb.append("=");
sb.append(value);
}
return sb.toString();
}
/**
* Should return a string that uniquely identifies this request. A future
* request with the same cache key may use the cached copy of the page.
* If you don't want some requests cached at all, return a null cache key for
* those pages. You can use the buildCacheKey method to create a cache key out
* of a map.
*
* @param req The HTTP request which, result of which is to be cached.
* @param method The method of the HTTP request.
* @param action The parsed action parameter from the request.
* @return A cache key that uniquely identifies the results of this request
* being processed.
*/
protected abstract String getCacheKey(HttpServletRequest req, ModulesServlet.HttpMethod method, String action);
/**
* <p>
* Writes a page read from an input stream into an HTTP servlet response.
* The input stream might be coming from a cached file, or directly from the
* doOutput method if caching is not in use. In any case, the contents of it
* need to be written to the response object. Note that any HTTP headers must
* be set before writing anything else.
* </p>
* <p>
* If you used writeMetadata in doOutput, you have to override this method
* and use readMetadata correspondingly to read the metadata from the start
* of the stream. You can then, for example, set any HTTP headers you read
* from the metadata. After this, you can call this super implementation which
* will do the rest of the stream copying.
* </p>
* <p>
* Make absolutely certain that the input stream is closed before returning
* from this method. Failing to do so may cause the caching service to become
* locked which can then lock the whole application. It is best to put the
* contents in a try-finally block and then call cacheIn.close in the finally
* part. Do this even if you call the super implementation as your code could
* possibly fail before reaching that part.
* </p>
*
* @param cacheIn
* @param resp
* @throws IOException
*/
protected void returnOutput(InputStream cacheIn, HttpServletResponse resp) throws IOException {
try{
setHttpHeaders(resp, httpHeaders);
OutputStream out=resp.getOutputStream();
byte[] buf=new byte[4096];
int read;
while( (read=cacheIn.read(buf))!=-1 ){
out.write(buf, 0, read);
}
out.close();
}
finally {
cacheIn.close();
}
}
/**
* Use this to write some metadata at the start of the cached file,
* for example the mime type and character encoding of the file.
* Use this in doOutput as the first thing after opening the output stream.
* Read the metadata with readMetadata method in an overridden returnOutput.
*/
public static void writeMetadata(Map<String,String> data,OutputStream out) throws IOException {
out.write((""+data.size()).getBytes("UTF-8"));
out.write(0);
for(Map.Entry<String,String> e : data.entrySet()){
String key=e.getKey();
String value=e.getValue();
out.write(key.getBytes("UTF-8"));
out.write(0);
out.write(value.getBytes("UTF-8"));
out.write(0);
}
out.flush();
}
private static String readUntilZero(InputStream in) throws IOException {
byte[] buf=new byte[128];
int pos=0;
int read;
while( (read=in.read())!=-1 ){
if(read==0) break;
else {
if(pos>=buf.length){
byte[] newbuf=new byte[buf.length*2];
System.arraycopy(buf, 0, newbuf, 0, buf.length);
buf=newbuf;
}
buf[pos++]=(byte)read;
}
}
if(read!=0) return null; // broke out of loop due to end of file
return new String(buf,0,pos,"UTF-8");
}
/**
* Use this to read the metadata written by writeMetadata method.
* These two methods must always be used in pair, do not try to use readMetadata
* if you haven't used writeMetadata. Make your cache keys in such a way that
* you'll always know whether metadata has been used or not. Use readMetadata
* by overriding returnOutput and reading it from the cache InputStream as the
* first thing, after that you can use the original returnOutput for the rest
* of the input stream.
*/
public static Map<String,String> readMetadata(InputStream in) throws IOException {
String countS=readUntilZero(in);
if(countS==null) return null;
int count=Integer.parseInt(countS);
HashMap<String,String> ret=new HashMap<String,String>();
for(int i=0;i<count;i++){
String key=readUntilZero(in);
String value=readUntilZero(in);
ret.put(key,value);
}
return ret;
}
/**
* <p>
* Does the output that might be either cached or returned directly.
* The OutputProvider is used to get the output stream where the output should be
* written. Before you get this stream, you may abort the action by returning false
* but after the output stream is retrieved, you are committed to outputting the
* page that then might be cached for future use. Therefore
* you should do all the preparations first, and only then get the output stream
* when you know that you will be able to output something sensible.
* </p>
* <p>
* If you opened the output stream using the output provider, you must make
* sure that the stream is properly closed. It is best to place all your code
* after this in a try-finally block and close the stream in the finally part.
* Failing to do this may cause the caching service to become locked, which
* in turn could potentially lock the whole application.
* </p>
*/
protected abstract boolean doOutput(HttpServletRequest req, HttpMethod method, String action, OutputProvider out, User user) throws ServletException, IOException, ActionException;
@Override
public boolean handleAction(final HttpServletRequest req, final HttpServletResponse resp, final HttpMethod method, final String action, final User user) throws ServletException, IOException, ActionException {
if(caching && cache!=null ){
String cacheKey=getCacheKey(req, method, action);
if(cacheKey!=null){
InputStream cacheIn=cache.getPage(cacheKey, 0);
if(cacheIn!=null){
returnOutput(cacheIn, resp);
return true;
}
OutputProvider outProvider=new OutputProvider(cacheKey);
boolean cont=false;
try{
cont=doOutput(req, method, action, outProvider, user);
}
finally {
if(outProvider.out!=null) outProvider.out.close();
}
if(cont){
cacheIn=cache.getPage(cacheKey, 0);
if(cacheIn!=null){
returnOutput(cacheIn, resp);
return true;
}
else {
// If the cache is working correctly, this really shouldn't happen but let's do something sensible
logging.error("Could not find the cached page that was just saved");
return false;
}
}
else return false;
}
}
OutputProvider out=new OutputProvider(resp);
try{
boolean ret=doOutput(req, method, action, out, user);
if(ret){
out.out.close(); // this must be done before getFuture().get(), otherwise you'll get a dead lock
try {
out.getFuture().get();
return ret;
} catch (Exception ex) {
logging.info("IOException piping result",ex);
return false;
}
}
else return false;
}
finally{
if(out.out!=null) out.out.close();
}
}
/**
* A class used to pass an output stream to the doOutput method.
* The stream is not opened until getOutputStream is called. At that point
* a request is made to the caching system, if caching is used that is, to
* store the page. Some aspects of the caching system are locked while this
* stream is open. Furthermore, something sensible should be written when
* started, and that output may be used again from the cache. Thus you should
* open the stream only when you know that the request is valid and you can
* output something sensible. The stream also must be properly closed once
* done. Failing to do so will keep the caching system locked which may
* in turn lock the whole application.
*/
public class OutputProvider {
private String cacheKey;
private OutputStream out;
private HttpServletResponse resp;
private Future future;
private OutputProvider(HttpServletResponse resp){this.resp=resp;}
private OutputProvider(OutputStream out){this.out=out;}
private OutputProvider(String cacheKey){
this.cacheKey=cacheKey;
}
/**
* <p>
* Returns a future object representing a returnOutput method
* call. In case output is written directly into an HTTP response, the
* whole thing is done with piped input and output streams to
* avoid buffering all the results. Another thread is created to call the
* returnOutput method while page contents are written in doOutput.
* The Future object returned by this method represents the returnOutput
* call. Calling get method of the Future object will wait for that process
* to finish. Prior to that, the output stream must be closed, otherwise
* returnOutput won't know when the end of stream has been reached and the
* threads will dead lock.
* </p>
* <p>
* This is all done in the CachedAction implementation of handleAction.
* Unless you completely circumvent this implementation, you don't need
* to worry about any of this.
* </p>
* @return A Future object representing an asynchronous returnOutput call
* if the output is done directly to an HTTP response. Otherwise
* returns null.
*/
public Future getFuture(){return future;}
/**
* Opens and returns the output stream where page contents can
* be written.
* @return An OutputStream where to write page contents.
*/
public OutputStream getOutputStream(){
if(out!=null) return out;
else if(resp!=null){
try{
final PipedInputStream pin=new PipedInputStream();
final PipedOutputStream pout=new PipedOutputStream(pin);
out=pout;
future=threadPool.submit(new Runnable(){
@Override
public void run() {
try {
returnOutput(pin, resp);
}catch(IOException ioe){
logging.info("IOException piping result",ioe);
}
}
});
return out;
}catch(IOException ioe){
logging.warn("Unable to pipe output",ioe);
return null;
}
}
else {
this.out=cache.storePage(cacheKey, 0);
return this.out;
}
}
}
}
| 19,086 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
AbstractTemplate.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/AbstractTemplate.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* A base implementation for templates. Performs common actions to most
* templates. Among these, parses from the initialisation parameters values for
* many of the template variables, these are defined in variables named
* templateKey, templateVersion, templateMimeType and templateEncoding. Also
* templateCaching and templateFile which are not in the Template interface but
* are common template features.
* </p>
* <p>
* A default template context can also be specified in the initialisation
* parameters using the parameter name prefix "context.". The rest of parameter
* name is used as the variable name in the context.
* </p>
* <p>
* This base implementation automatically registers the template to a TemplateManager
* at module start, as all templates should do to be usable.
* </p>
*
* @author olli
*/
public abstract class AbstractTemplate extends AbstractModule implements Template {
protected TemplateManager templateManager;
protected String templateKey=null;
protected String templateVersion="";
protected String templateMime="text/html";
protected String templateEncoding="UTF-8";
protected boolean templateCaching=true;
protected String templateFile=null;
protected HashMap<String,Object> templateContext;
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
Object o;
o=settings.get("templateKey");
if(o!=null) templateKey=o.toString();
o=settings.get("templateVersion");
if(o!=null) templateVersion=o.toString();
o=settings.get("templateMimeType");
if(o!=null) templateMime=o.toString();
o=settings.get("templateEncoding");
if(o!=null) templateEncoding=o.toString();
o=settings.get("templateCaching");
if(o!=null) templateCaching=Boolean.parseBoolean(o.toString());
o=settings.get("templateFile");
if(o!=null) templateFile=o.toString();
templateContext=new HashMap<String,Object>();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("context.")){
templateContext.put(key.substring("context.".length()),e.getValue());
}
}
}
@Override
public Map<String,Object> getTemplateContext(){
return templateContext;
}
protected String getFullTemplatePath(){
return templateManager.getTemplatePath()+templateFile;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(this,TemplateManager.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
templateManager=manager.findModule(this,TemplateManager.class);
templateManager.registerTemplate(this);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
if(this.templateManager!=null) templateManager.unregisterTemplate(this);
templateManager=null;
super.stop(manager);
}
@Override
public String getKey() {
return templateKey;
}
@Override
public String getVersion() {
return templateVersion;
}
@Override
public String getMimeType() {
return templateMime;
}
@Override
public String getEncoding() {
return templateEncoding;
}
@Override
public abstract void process(Map<String, Object> params, OutputStream output);
}
| 4,990 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ActionHandler.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ActionHandler.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* This interface adds a feature to Actions needed by all the various
* contexts. The ServletModule.RequestListener is a little too generic
* for more complicated handler resolution. Thus actions should generally try
* to also implement this interface. Actions that don't implement this interface
* cannot be used in context derived from GenericContext unless the checkActions
* parameter of the context is set to false.
*
* @author olli
*/
public interface ActionHandler {
/**
* Checks if this action handler will try to handle the given action
* without handling it yet or causing any side effects. Returning true
* means that the action handler will try to handle it, not necessarily that
* the action will succeed. You may also return false from the handleRequest
* method even if you return true here. The return value should be your best
* guess as to whether you will handle it without spending too much time
* checking.
*
*
* @param req The HTTP request.
* @param resp The HTTP response.
* @param method The HTTP method of the request.
* @return
*/
public boolean isHandleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method);
}
| 2,206 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TemplateContextProvider.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/TemplateContextProvider.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.modules.servlet;
import java.util.Map;
import org.wandora.modules.Module;
/**
* This class can be used to define a default template context for
* template managers. See TemplateManager documentation for more details.
*
* @author olli
*/
public interface TemplateContextProvider extends Module {
public Map<String,Object> getTemplateBaseContext();
}
| 1,186 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
GenericTemplateAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/GenericTemplateAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* A general purpose action that uses templates for output. This can be used
* on its own or subclassed in a few different ways.
* </p>
* <p>
* Standalone use just takes some template specified in initialisation parameters,
* with parameter name templateKey, and gives it the default context returned by
* the template manager. You can add objects into the context with initialisation
* parameters of this action too, by prefixing the context variable name with
* "context.". The default context, with possible action specific additions,
* is passed to the template which can then produce the desired page.
* </p>
* <p>
* To make the produced page depend on the HTTP request parameters, you can forward
* some of them directly into the template context. To do this, list the request
* parameters you would like forwarded in an initialisation parameter named
* forwardRequestParameters, separated by semicolons. Then the contents of the
* user provided request parameters are copied into the template context. Remember
* to sanity check any values thus forwarded. You can also set default values for
* such request parameters which are used if none are provided in the request. Do
* this by prefixing the initialisation parameter name with "defaultRequestParameter."
* and then adding the parameter name and put the value in the contents of the
* param element.
* </p>
* <p>
* Simplest way to subclass is to just override the getTemplateContext method.
* It should use getDefaultTemplateContext as basis and then add whatever is needed
* in the context. If needed, you can then do any side effects here as well, like
* modifying a database or something similar.
* </p>
* <p>
* For even more control, override the handleAction method. Then you have to call
* the template yourself and write the output to the HTTP response object.
* </p>
* <p>
* This class extends CachedAction so if it is likely that the same page be
* generated often, it may be of use to cache the page. To do this, set the
* initialisation parameter caching to true, as per normal CachedAction
* behaviour. The default implementation will use the action name and all
* forwarded request parameters in the cache key. Assuming the default context
* doesn't contain anything dynamic, this should be adequate.
* </p>
*
* @author olli
*/
public class GenericTemplateAction extends CachedAction {
protected String requestContextKey="request";
protected TemplateManager templateManager;
protected String templateKey;
protected List<String> forwardRequestParameters;
protected Map<String,String> defaultRequestParameters;
protected final Map<String,Object> staticContext=new HashMap<String,Object>();
/**
* Adds a value to the action specific static template context. The
* key value pair will be passed on to templates in the context.
* @param key The name of the variable in the context.
* @param o The value of the context variable.
*/
public void putStaticContext(String key,Object o){
staticContext.put(key,o);
}
protected Template getTemplate(HttpServletRequest req, HttpMethod method, String action){
return templateManager.getTemplate(templateKey, null);
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.requireModule(this,TemplateManager.class, deps);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
forwardRequestParameters=new ArrayList<String>();
defaultRequestParameters=new HashMap<String,String>();
Object o=settings.get("templateKey");
if(o!=null) templateKey=o.toString();
o=settings.get("forwardRequestParameters");
if(o!=null) {
String[] split=o.toString().split("[;\n]");
for(int i=0;i<split.length;i++){
String s=split[i].trim();
if(s.length()>0) forwardRequestParameters.add(s);
}
}
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("context.")){
staticContext.put(key.substring("context.".length()),e.getValue());
}
else if(key.startsWith("defaultRequestParameter.")){
String param=key.substring("defaultRequestParameter.".length());
defaultRequestParameters.put(param,e.getValue().toString());
}
}
}
@Override
public void start(ModuleManager manager) throws ModuleException {
templateManager=manager.findModule(this,TemplateManager.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
templateManager=null;
super.stop(manager);
}
/**
* Gets the static context to for templates. Includes action specific
* items added with putStaticContext as well as the template manager
* default context.
* @return The static template context.
*/
protected Map<String,Object> getStaticTemplateContext(){
Map<String,Object> params=new LinkedHashMap<String,Object>();
params.putAll(templateManager.getDefaultContext());
params.putAll(staticContext);
return params;
}
/**
* Returns a map of the http request parameters that are to be
* forwarded to the template context.
* @param req The HTTP request.
* @return A Map containing the forwarded parameters and their values.
*/
protected Map<String,String> getForwardedParameters(HttpServletRequest req){
Map<String,String> params=new LinkedHashMap<String, String>();
for(String s : forwardRequestParameters){
String value=req.getParameter(s);
if(value==null) {
value=defaultRequestParameters.get(s);
if(value==null) continue;
}
params.put(s,value);
}
return params;
}
/**
* <p>
* Gets the template context used for a request. Contains the static
* context as well forwarded request parameters. The static context contains
* both action specific context items and the template manager default context.
* In addition, the logged in user, if applicable, is added with the variable
* name user. Usually you don't want anything user specific cached so as a
* safety measure, the user variable is not added if caching is turned on.
* If you for some reason do, you will have to override this method.
* </p>
* <p>
* This should be the main overriding point for extending classes. You can
* perform any tasks needed and then add things in the context. Often you
* don't need to override anything else besides this and the basic Module
* methods.
* </p>
*
* @param template The template to be used.
* @param req The HTTP request.
* @param method The method of the HTTP request.
* @param action The action parameter parsed from the HTTP request.
* @param user The logged in user, or null if not logged in.
* @return The template context used with processing the template for this action.
* @throws ActionException
*/
protected Map<String,Object> getTemplateContext(Template template, HttpServletRequest req, HttpMethod method, String action, User user) throws ActionException {
Map<String,Object> context=getStaticTemplateContext();
context.put(requestContextKey,req);
context.putAll(template.getTemplateContext());
context.putAll(getForwardedParameters(req));
// Generally you don't want to cache anything that's user specific. If
// for some reason you do, just override getTemplateContext in your action
// and add user in the context. Also add user name to cache key params if
// needed.
if(!caching) context.put("user",user);
return context;
}
/**
* Returns the parameters used in building the cache key. This implementation
* uses the request action parameter and all parameters that have been
* configured to be forwarded from the request into the template context.
*
* @param req The HTTP request for which cache key parameters are resolved.
* @param method The method of the HTTP request.
* @param action The parsed action parameter from the request.
* @return
*/
protected Map<String,String> getCacheKeyParams(HttpServletRequest req, HttpMethod method, String action){
Map<String,String> params=new LinkedHashMap<String,String>();
params.putAll(getForwardedParameters(req));
params.put("requestAction",action);
return params;
}
@Override
protected String getCacheKey(HttpServletRequest req, HttpMethod method, String action){
return buildCacheKey(getCacheKeyParams(req, method, action));
}
@Override
protected void returnOutput(InputStream cacheIn, HttpServletResponse resp) throws IOException {
try{
Map<String,String> metadata=readMetadata(cacheIn);
String mimetype=metadata.get("contenttype");
if(mimetype!=null) resp.setContentType(mimetype);
String encoding=metadata.get("encoding");
if(encoding!=null) resp.setCharacterEncoding(encoding);
super.returnOutput(cacheIn, resp);
}
finally{
cacheIn.close();
}
}
@Override
protected boolean doOutput(HttpServletRequest req, HttpMethod method, String action, OutputProvider out, User user) throws ServletException, IOException, ActionException {
Template template=getTemplate(req, method, action);
if(template==null) return false;
Map<String,Object> context=getTemplateContext(template, req, method, action, user);
if(context==null) return false;
Map<String,String> metadata=new LinkedHashMap<String,String>();
metadata.put("contenttype",template.getMimeType());
metadata.put("encoding",template.getEncoding());
OutputStream outStream=out.getOutputStream();
try{
writeMetadata(metadata, outStream);
template.process(context, outStream);
}
finally{
outStream.close();
}
return true;
}
}
| 12,233 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
TemplateManager.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/TemplateManager.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* A module where all Templates register themselves so that Actions,
* or other modules too, can find them. The other modules refer to the
* templates with their template key, not the module name. In addition, a
* template version may also be specified. The combination of key and version
* has to be unique, there can be several templates with same key but different
* versions. While the key must match exactly to the requested template key,
* version matching is not exact. Instead a best match is used. See getTemplate
* method documentation for more details.
* </p>
* <p>
* Manager specific default context variables can be specified in the initialisation
* parameters using the parameter name prefix "context.". The rest of the parameter
* is the context variable name. Note that template specific parameters can similarly
* be defined in the Template modules too (assuming they derive from the AbstractTemplate
* class).
* </p>
* <p>
* A templatePath initialisation parameter can be given, which should point to
* a directory containing template files. Templates are not required to use this,
* in fact, templates are not required to access any files at all, but it is
* good practice to respect it. However, note that VelocityTemplates in particular
* do not use this. Instead the template directory for velocity templates is defined
* in the VelocityEngineModule.
* </p>
* <p>
* A TemplateContextProvider module can be used to provide the default context.
* This is an optional dependency and will be used if it is found in the module
* manager but not having one is not an error. You can set the ignoreContextProvider
* initialisation parameter to true to override this behaviour. Both a context
* provider and context initialisation parameters in this class can be used at
* the same time. These contexts are merged into one default context. In case
* of context keys clashing, initialisation parameters of this module override
* the values of the context provider.
* </p>
*
* @author olli
*/
public class TemplateManager extends AbstractModule {
protected final Map<String,List<Template>> templateMap=new LinkedHashMap<>();
protected final Map<String,Object> defaultContext=new LinkedHashMap<>();
protected TemplateContextProvider contextProvider=null;
protected boolean ignoreContextProvider=false;
protected String templatePath="";
/**
* Gets the manager specific default context which should be used
* as a basis for template contexts.
* @return The manager specific default template context.
*/
public Map<String,Object> getDefaultContext(){
if(contextProvider!=null && !ignoreContextProvider){
Map<String,Object> ret=new LinkedHashMap<String,Object>();
ret.putAll(contextProvider.getTemplateBaseContext());
ret.putAll(defaultContext);
return ret;
}
else return defaultContext;
}
/**
* Puts an object in the manager specific default template context.
* @param key The key of the template variable.
* @param o The value of the template variable.
*/
public void putStaticContext(String key,Object o){
defaultContext.put(key,o);
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("context.")){
defaultContext.put(key.substring("context.".length()),e.getValue());
}
}
Object o=settings.get("templatePath");
if(o!=null) {
templatePath=o.toString();
if(templatePath.length()>0 && !templatePath.endsWith(File.separator)) templatePath+=File.separator;
}
o=settings.get("ignoreContextProvider");
if(o!=null) ignoreContextProvider=Boolean.parseBoolean(o.toString().trim());
}
@Override
public void stop(ModuleManager manager) {
contextProvider=null;
super.stop(manager);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
contextProvider=manager.findModule(this, TemplateContextProvider.class);
super.start(manager);
}
/**
* Gets the specified path for template files.
* @return The template path.
*/
public String getTemplatePath(){
return templatePath;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.optionalModule(this, TemplateContextProvider.class, deps);
requireLogging(manager, deps);
return deps;
}
/**
* Gets the template using the specified key and version. The key
* must match exactly with the key the template was registered with but
* version matching is fuzzy. If multiple versions of the same template
* have been registered, the one with the most matching characters from the
* start is used. You can always use null for version if you don't use
* different template versions.
*
* @param key The key of the template to get.
* @param version The version of the template, or null if not applicable.
* @return The template that should be used, or null if no suitable template was found.
*/
public Template getTemplate(String key,String version){
synchronized(templateMap){
List<Template> templates=templateMap.get(key);
if(templates==null || templates.isEmpty()) return null;
if(templates.size()==1) return templates.get(0);
Template best=null;
int bestScore=-1;
if(version==null) version="";
version=version.toLowerCase();
for(Template t : templates){
String tVersion=t.getVersion();
if(tVersion==null) tVersion="";
tVersion=tVersion.toLowerCase();
int i=0;
for(i=0;i<tVersion.length() && i<version.length();i++){
if(tVersion.charAt(i)!=version.charAt(i)){
break;
}
}
if(i>bestScore){
bestScore=i;
best=t;
}
}
return best;
}
}
/**
* Register a template for this manager. After this, the manager may
* return the template when getTemplate is called.
*
* @param template The template to register.
*/
public void registerTemplate(Template template){
synchronized(templateMap){
String key=template.getKey();
if(key==null) {
logging.warn("Tried to register template with null key");
return;
}
List<Template> templates=templateMap.get(key);
if(templates==null){
templates=new ArrayList<Template>();
templateMap.put(key,templates);
}
templates.add(template);
}
}
/**
* Unregisters a template. After this, the template will no longer be
* returned as a result of getTemplate.
* @param template The template to unregister.
*/
public void unregisterTemplate(Template template){
synchronized(templateMap){
String key=template.getKey();
if(key==null) return;
List<Template> templates=templateMap.get(key);
if(templates==null) return;
templates.remove(template);
if(templates.isEmpty()) templateMap.remove(key);
}
}
}
| 9,115 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
StaticContentAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/StaticContentAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package org.wandora.modules.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.eclipse.jetty.http.MimeTypes;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author olli
*/
public class StaticContentAction extends AbstractAction {
protected String mountPoint=null;
protected List<Pattern> forbidden=new ArrayList<Pattern>();
protected String urlPrefix="";
private MimeTypes mimeTypes;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
this.isDefaultAction=true; // defaultAction defaults to true, can still be changed with init params
Object o;
o=settings.get("urlPrefix");
if(o!=null) urlPrefix=o.toString().trim();
o=settings.get("mountPoint");
if(o!=null) {
try{
File f=new File(o.toString().trim());
if(!f.exists() || !f.isDirectory()) {
throw new ModuleException("Mount point \""+o.toString().trim()+"\" doesn't exist or is not a directory");
}
mountPoint=f.getCanonicalPath();
if(!mountPoint.endsWith(File.separator)) mountPoint+=File.separator;
}catch(IOException ioe){
throw new ModuleException("Couldn't get canonical path of mount point",ioe);
}
}
else {
String moduleSource=manager.getModuleSettings(this).source;
if(moduleSource!=null){
File f=new File(moduleSource);
if(f.exists()){
f=f.getAbsoluteFile();
if(!f.isDirectory()) {
f=f.getParentFile();
}
if(f!=null){
try{
mountPoint=f.getCanonicalPath();
if(!mountPoint.endsWith(File.separator)) mountPoint+=File.separator;
}catch(IOException ioe){
throw new ModuleException("Couldn't get canonical path of mount point",ioe);
}
}
}
}
}
if(mountPoint==null) throw new ModuleException("Mount point not specified and could not determine it automatically");
o=settings.get("forbidden");
if(o==null) o=".*config.xml\n.*/templates/.*\n.*cache/.*\n~";
String[] split=o.toString().split("\n+");
for(String s : split){
forbidden.add(Pattern.compile(s));
}
mimeTypes=new MimeTypes();
super.init(manager, settings);
}
protected String getLocalPath(HttpServletRequest req){
// ContextPath is the part of the request uri which was used to select
// the servlet context. Remove it from the start of the request uri
// to get the target relative to this context. Request URI does not
// contain any parameters, even if they were used in the http request.
String context=req.getContextPath();
if(context==null || context.length()==0) context="/";
if(!context.endsWith("/")) context+="/";
String target=req.getRequestURI();
if(target.startsWith(context)) {
target=target.substring(context.length());
}
else return null;
if(!target.startsWith(urlPrefix)) return null;
target=target.substring(urlPrefix.length());
if(!File.separator.equals("/")) {
target=target.replace("/", File.separator);
}
String localPath=mountPoint+target;
File f=new File(localPath);
if(!f.exists() || f.isDirectory()) return null;
try{
localPath=f.getCanonicalPath();
/* Checking that canonical form of localPath starts with the canonical
* form of mountPoint makes sure that localPath really is under
* mountPoint. Tricks like using .. in the path will be taken care of
* by this. The downside is that symbolic links under the mount point pointing
* to a destination outside the mount point will not work.
*/
if(!localPath.startsWith(mountPoint)) return null;
for(Pattern p : forbidden){
if(p.matcher(localPath).matches()) return null;
}
return localPath;
}catch(IOException ioe){
logging.warn("Couldn't get canonical path of requested file",ioe);
return null;
}
}
protected boolean returnFile(HttpServletResponse response,File f) throws IOException {
if(!f.exists() || f.isDirectory()){
return false;
}
Object o=mimeTypes.getMimeByExtension(f.getName());
if(o!=null) response.setContentType(o.toString());
else response.setContentType("text/plain");
OutputStream out=response.getOutputStream();
InputStream in=new FileInputStream(f);
byte[] buf=new byte[8192];
int read=-1;
while((read=in.read(buf))!=-1){
out.write(buf,0,read);
}
out.flush();
in.close();
return true;
}
@Override
public boolean isHandleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method) {
if(super.isHandleAction(req, resp, method)){
return getLocalPath(req)!=null;
}
else return false;
}
@Override
public boolean handleAction(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, String action, User user) throws ServletException, IOException, ActionException {
String localPath=getLocalPath(req);
if(localPath!=null) {
return returnFile(resp,new File(localPath));
}
else return false;
}
}
| 7,591 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ServletModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ServletModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.IOException;
import org.wandora.modules.Module;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* A module that hooks to a servlet, or something similar. The typical
* case is where it is an actual servlet from which HTTP requests are received.
* RequestListeners can register themselves to the servlet module and then get
* a chance to handle the requests.
*
* @author olli
*/
public interface ServletModule extends Module {
public void addRequestListener(ServletModule.RequestListener listener);
public void removeRequestListener(ServletModule.RequestListener listener);
/**
* Returns the base URL for this servlet.
* @return The base URL for this servlet.
*/
public String getServletURL();
/**
* Returns the local path which this servlet should use as a basis
* for files it needs to access.
* @return A local path which should be the basis of local files.
*/
public String getContextPath();
/**
* An interface for all RequestListeners which wish to be notified of
* incoming requests.
*/
public static interface RequestListener {
/**
* <p>
* Handles the request, if this is the type of request the listener
* is interested in. If the listener does not wish to handle the request,
* it should return false. False return value indicates that the request
* should be passed to other listeners, a true return value indicates
* that this should not happen and a response to the request has been
* sent. Thus it is possible that you perform some action and still
* return false and let some other action write the response.
* </p>
* <p>
* However,
* keep in mind that some other listener may grab any request before
* your listener and your listener will then never even see the request.
* Thus, you will not necessarily be notified of every single request.
* If this is your goal, you should probably make a separate context
* that all requests will pass through before they are passed on to
* other actions, see GenericContext.
* </p>
*
* @param req The HTTP request.
* @param resp The HTTP response.
* @param method The HTTP method of the request.
* @param user The logged in user if applicable or null.
* @return True if a response has been sent and no further listener should
* try to process the request. False if the request can be forwarded
* to other listeners for processing.
* @throws ServletException
* @throws IOException
* @throws ActionException
*/
public boolean handleRequest(HttpServletRequest req, HttpServletResponse resp, ModulesServlet.HttpMethod method, User user) throws ServletException, IOException, ActionException;
}
}
| 3,949 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
VelocityTemplate.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/VelocityTemplate.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.velocityhelpers.InstanceMaker;
import org.wandora.modules.velocityhelpers.URLEncoder;
/**
* <p>
* A Template implementation using the Apache Velocity templating engine.
* The engine itself is required as a separate module, VelocityEngineModule.
* The base functionality is defined in the AbstractTemplate base class and only
* the actual template processing is done here.
* </p>
* <p>
* A few items are automatically added in the template context, in addition
* to the ones specified in initialisation parameters, as described in
* AbstractTemplate documentation. These are used to overcome some of the
* limitations in Velocity template language. The urlencoder parameter contains
* a URLEncoder object which can help with encoding values used in URLs.
* listmaker variable contains an InstanceMaker that can make ArrayLists, it is
* difficult to create new lists in Velocity without this. These helper classes
* are defined in org.wandora.modules.velocityhelpers along with other similar
* helpers, which you may want to add to the context manually.
* </p>
*
* @author olli
*/
public class VelocityTemplate extends AbstractTemplate {
protected org.apache.velocity.Template vTemplate;
protected VelocityEngineModule engineModule;
protected synchronized VelocityEngine getVelocityEngine(){
Properties props=new Properties();
props.setProperty("webapp.resource.loader.path", templateManager.getTemplatePath());
VelocityEngine engine = new VelocityEngine(props);
return engine;
}
@Override
protected String getFullTemplatePath(){
// don't add the template path of the manager as that's added to the velocity engine search path already
return templateFile;
}
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
manager.optionalModules(VelocityEngineModule.class, deps);
return deps;
}
@Override
public void start(ModuleManager manager) throws ModuleException {
engineModule=manager.findModule(this,VelocityEngineModule.class);
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
engineModule=null;
vTemplate=null;
super.stop(manager);
}
@Override
public Map<String, Object> getTemplateContext() {
Map<String,Object> context=super.getTemplateContext();
if(!context.containsKey("urlencoder")) context.put("urlencoder",new URLEncoder());
if(!context.containsKey("listmaker")) context.put("listmaker",new InstanceMaker(java.util.ArrayList.class));
return context;
}
@Override
public void process(Map<String, Object> params, OutputStream output) {
org.apache.velocity.Template vTemplate=this.vTemplate;
if(vTemplate==null || !templateCaching){
String templatePath=getFullTemplatePath();
try {
if(engineModule!=null) {
vTemplate=engineModule.getEngine().getTemplate(templatePath,templateEncoding);
}
else {
vTemplate=Velocity.getTemplate(templatePath,templateEncoding);
}
}catch(ResourceNotFoundException rnfe){
logging.warn("Velocity template "+templatePath+" not found.",rnfe);
}catch(ParseErrorException pee){
logging.warn("Parse error in velocity template "+templatePath+": "+pee.getMessage());
}catch(Exception ex){
logging.warn("Couldn't load velocity template "+templatePath+": "+ex.getMessage());
logging.debug(ex);
}
this.vTemplate=vTemplate;
}
VelocityContext context=new VelocityContext();
Iterator iter=params.entrySet().iterator();
while(iter.hasNext()){
Map.Entry e=(Map.Entry)iter.next();
context.put(e.getKey().toString(),e.getValue());
}
try{
Writer writer=new BufferedWriter(new OutputStreamWriter(output,getEncoding()));
vTemplate.merge(context, writer);
writer.flush();
}catch(Throwable ex){
logging.warn("Couldn't merge template "+getFullTemplatePath(),ex);
Throwable cause=ex.getCause();
if(cause!=null){
logging.warn("Cause",cause);
}
}
}
}
| 6,033 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ActionAuthenticationException.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ActionAuthenticationException.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import org.wandora.modules.usercontrol.User;
/**
*
* @author olli
*/
public class ActionAuthenticationException extends ActionException {
protected User user;
public ActionAuthenticationException(ActionHandler action) {
super(action);
}
public ActionAuthenticationException(String message, ActionHandler action) {
super(message, action);
}
public ActionAuthenticationException(String message, Throwable cause, ActionHandler action) {
super(message, cause, action);
}
public ActionAuthenticationException(Throwable cause, ActionHandler action) {
super(cause, action);
}
public ActionAuthenticationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, ActionHandler action) {
super(message, cause, enableSuppression, writableStackTrace, action);
}
public ActionAuthenticationException() {
}
public ActionAuthenticationException(String message) {
super(message);
}
public ActionAuthenticationException(String message, Throwable cause) {
super(message, cause);
}
public ActionAuthenticationException(Throwable cause) {
super(cause);
}
public ActionAuthenticationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ActionAuthenticationException(String message,User user) {
super(message);
this.user=user;
}
public ActionAuthenticationException(String message, Throwable cause, User user) {
super(message, cause);
this.user=user;
}
public ActionAuthenticationException(String message, ActionHandler action,User user) {
super(message, action);
this.user=user;
}
public User getUser(){return user;}
public void setUser(User user){this.user=user;}
}
| 2,819 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Template.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/Template.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
/**
* <p>
* The interface for all templates. A template is an object which can
* executed with a given template context to produce content of some kind.
* Typically the template is defined with some template language. The template
* is read from a file and the bulk of the output in literal text with some
* special markup for dynamic elements. The dynamic elements may then refer
* to the variables in the template context to fill in the rest of the page.
* </p>
* <p>
* The interface however is generic enough for many other types of templates too.
* You need not read a template from an actual file. Any kind of dynamic content
* generation based on some context parameters could work as a template.
* </p>
*
* @author olli
*/
public interface Template {
/**
* Returns the template key. The template key is how actions refer to
* this template.
* @return The template key.
*/
public String getKey();
/**
* Returns the template version. You may define several templates using
* the same key with different versions. For example, you could differentiate
* between language versions of the otherwise same template.
* @return The version identifier.
*/
public String getVersion();
/**
* Returns the mime type of the content from this template.
* @return The mime type of the content returned by this template.
*/
public String getMimeType();
/**
* Returns the character encoding used by the returned content.
* @return The character encoding used by the content returned from this template.
*/
public String getEncoding();
/**
* Processes the template with the given context and writes the resulting
* content in the output stream.
* @param params The template context used for processing of the template.
* @param output The output stream where the result is written.
*/
public void process(java.util.Map<String,Object> params,java.io.OutputStream output);
/**
* Returns the default context for this template. You may then add more
* content into the context before passing it on to process.
* @return The default context of the template.
*/
public java.util.Map<String,Object> getTemplateContext();
}
| 3,129 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
ImageResizeAction.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/servlet/ImageResizeAction.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.servlet;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
import org.wandora.modules.servlet.ModulesServlet.HttpMethod;
import org.wandora.modules.usercontrol.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* <p>
* An action that reads images from a source directory and resizes them
* to fit specified dimensions. Can optionally also watermark the images.
* One or more image profiles are defined in the initialisation parameters,
* images may then be resized to fit any of the defined profiles. Typically you
* will use the caching with this action so that the fairly costly resize
* operation is only done once for each image and profile.
* </p>
* <p>
* Images are read from one or more image directories. Each directory is specified
* as a source. Typically the source directories themselves should not be open
* to the internet, they should only be accessible locally to the servlet.
* Images are retrieved using an image id, which can really be any string uniquely
* defining the image file. Typically it is some part or the full file name.
* One or more sources can be specified which translate the image id into an actual
* full file path for the image. This is done using regular expression matching and
* replacement. More complicated image file resolution requires extending this
* action.
* </p>
* <p>
* In the initialisation parameters, you can specify the default profile with
* a parameter named defaultProfile. This defaults to null, i.e. no default
* profile. The profile used must be specified in the request or an error
* is generated. If a default profile is specified, that will be used if the
* request doesn't specify otherwise.
* </p>
* <p>
* profileParamKey parameter can be used to specify which HTTP request parameter
* contains the profile name. This defaults to "profile".
* </p>
* <p>
* imageIdParamKey parameter can be used to specify which HTTP request parameter
* contains the image id. This defaults to "imageid".
* </p>
* <p>
* Image sources are defined using parameter names "source.sourcekey.pattern"
* and "source.sourcekey.replacement". The sourcekey part in the middle is
* replaced with any alphanumeric string identifying the source. It has no other
* significance except to link the two different parameters. For example,
* to define two different sources, you would use a total of four keys:
* </p>
* <pre>
* source.source1.pattern = ...
* source.source1.replacement = ...
* source.source2.pattern = ...
* source.source2.replacement = ...
* </pre>
* <p>
* The pattern is a regular expression that the image id needs to match for this
* source to be applicable. Replacement is a replacement string, with back
* references to the matching done with dollar sign and number combination. The
* replacement is done using default Java String.replaceAll. The result of this
* should be a URL to the actual image. Typically a URL to a local file but
* not necessarily.
* </p>
* <p>
* Sources are tried in the order they are specified in initialisation
* parameters until one is found where the pattern matches and the replacement
* results in a URL from which an actual image can be read. It is not considered
* to be an error if the URL points to nothing and nothing can be read from there,
* in such a case the next source will simply be tried.
* </p>
* <p>
* Image profiles are defined in a similar manner. The pattern for the parameter
* names is "profile.profilename.property" where profilename is substituted for
* the profile name and property for the property you want to define for the
* profile. Unlike the sources, the profile name is significant here in the
* sense that it is referred to with this name in the HTTP requests and the
* defaultProfile parameter.
* </p>
* <p>
* Supported profile properties are width, height, crop, noextracanvas, bgcolor,
* quality, watermark, watermarkmode and errorimage.
* </p>
* <p>
* Width and height specify the dimensions of the image. If either one is -1,
* or left undefined, then the image is scaled according to the other dimension
* retaining aspect ratio. You can also leave both undefined to do no scaling at
* all. If both are defined, the image is scaled down to fit the dimension so that
* it's at most their size. If noextracanvas is set to true, this is the image
* that is returned. Otherwise blank bars are added as needed to make the image
* exactly the size of the specified dimensions. These bars are black by default
* but can be changed to other colour with the bgcolor parameter.
* the returned image will have exactly those dimensions. If crop
* is set to true, original image is scaled and cropped so that it completely
* fills the specified dimensions. Otherwise the image is scaled to fit the
* dimensions with black bars at edges as needed. The colour of the bars can
* but can be changed to other colour with the bgcolor parameter, which is
* specified with the #XXXXXX format. Quality of the returned jpeg
* image can be specified with the quality parameter.
* </p>
* <p>
* A watermark can be added by specifying the watermark image URL in the
* watermark parameter. The only supported watermarkmode currently is
* "lowerright". In the future this parameter could be used to specify other
* placements for the watermark.
* </p>
* <p>
* You can also specify an error image for the profile which will be used if no
* source image was found, or any other error occurred while processing the image.
* The error image is not scaled according to the profile settings, it should be
* preprocessed to be exactly as it needs to be.
* </p>
* <p>
* To change the image source resolution to something more complicated, override
* the init method and add an ImageSource object in the imageSources map.
* ImageSource is a simple interface which just transforms an image id into
* a URL pointing to the image. If needed, you can also override readImage to
* change how the image is read. You could use a custom ad-hoc URL scheme and do
* your own handling for that here if the image cannot be retrieved using a normal
* URL.
* </p>
*
* @author olli
*/
public class ImageResizeAction extends CachedAction {
protected boolean exceptionOnImageRead=false;
protected String defaultProfile=null;
protected String imageIdParamKey="imageid";
protected String profileParamKey="profile";
protected HashMap<String,ImageProfile> imageProfiles;
protected LinkedHashMap<String,ImageSource> imageSources;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
protected void returnOutput(InputStream cacheIn, HttpServletResponse resp) throws IOException {
try{
Map<String,String> metadata=readMetadata(cacheIn);
String contenttype=metadata.get("contenttype");
resp.setContentType(contenttype);
super.returnOutput(cacheIn, resp);
}
finally{
cacheIn.close();
}
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
imageProfiles=new HashMap<String,ImageProfile>();
imageSources=new LinkedHashMap<String,ImageSource>();
Object o=settings.get("defaultProfile");
if(o!=null) defaultProfile=o.toString();
o=settings.get("imageIdParamKey");
if(o!=null) imageIdParamKey=o.toString();
o=settings.get("profileParamKey");
if(o!=null) profileParamKey=o.toString();
for(Map.Entry<String,Object> e : settings.entrySet()){
String key=e.getKey();
if(key.startsWith("profile.")){
key=key.substring("profile.".length());
int ind=key.indexOf(".");
if(ind<0) continue;
String profileName=key.substring(0,ind);
key=key.substring(ind+1);
ImageProfile profile=imageProfiles.get(profileName);
if(profile==null) {
profile=new ImageProfile();
profile.id=profileName;
profile.imageMaker=new DefaultImageMaker();
imageProfiles.put(profileName,profile);
}
String value=e.getValue().toString();
if(key.equalsIgnoreCase("quality")) profile.quality=Integer.parseInt(value);
else if(key.equalsIgnoreCase("width")) ((DefaultImageMaker)profile.imageMaker).width=Integer.parseInt(value);
else if(key.equalsIgnoreCase("height")) ((DefaultImageMaker)profile.imageMaker).height=Integer.parseInt(value);
else if(key.equalsIgnoreCase("bgcolor")) {
if(value.startsWith("#")) value=value.substring(1);
int r=Integer.parseInt(value.substring(0, 2),16);
int g=Integer.parseInt(value.substring(2, 4),16);
int b=Integer.parseInt(value.substring(4, 6),16);
((DefaultImageMaker)profile.imageMaker).bgColor=new java.awt.Color(r, g, b);
}
else if(key.equalsIgnoreCase("crop")) ((DefaultImageMaker)profile.imageMaker).crop=Boolean.parseBoolean(value);
else if(key.equalsIgnoreCase("noextracanvas")) ((DefaultImageMaker)profile.imageMaker).noExtraCanvas=Boolean.parseBoolean(value);
else if(key.equalsIgnoreCase("watermark")) ((DefaultImageMaker)profile.imageMaker).watermark=value;
else if(key.equalsIgnoreCase("watermarkmode")) ((DefaultImageMaker)profile.imageMaker).watermarkMode=value;
else if(key.equalsIgnoreCase("errorimage")) profile.error=value;
}
else if(key.startsWith("source.")){
key=key.substring("source.".length());
int ind=key.indexOf(".");
if(ind<0) continue;
String sourceName=key.substring(0,ind);
key=key.substring(ind+1);
ImageSource source=imageSources.get(sourceName);
if(source==null) {
source=new PatternImageSource();
((PatternImageSource)source).id=sourceName;
imageSources.put(sourceName,source);
}
String value=e.getValue().toString();
if(key.equalsIgnoreCase("pattern")) ((PatternImageSource)source).pattern=Pattern.compile(value);
else if(key.equalsIgnoreCase("replacement")) ((PatternImageSource)source).replacement=value;
}
}
super.init(manager, settings);
}
@Override
public void start(ModuleManager manager) throws ModuleException {
if(defaultProfile!=null && !imageProfiles.containsKey(defaultProfile)) {
logging.warn("Default profile \""+defaultProfile+"\" doesn't exist.");
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
super.stop(manager);
}
/**
* Reads an image from the specified URL and returns it as a
* BufferedImage.
* @param url The URL pointing to the image.
* @return The image as a BufferedImage.
* @throws IOException
*/
protected BufferedImage readImage(String url) throws IOException {
return ImageIO.read(new URL(url));
}
/**
* Writes the image into the given output stream. Does not perform
* full image processing with the profile. Only uses the relevant output format
* parameters from the profile. The default implementation only uses the quality.
*
* @param img The image that must be written.
* @param profile The profile used for the image.
* @param out The output stream where the image is written.
* @throws IOException
*/
protected void writeImage(BufferedImage img, ImageProfile profile, OutputStream out) throws IOException {
int quality=( profile != null ? profile.quality : 85 );
ImageOutputStream output = null;
try {
ImageWriter writer=ImageIO.getImageWritersByFormatName("jpeg").next();
IIOImage iioi=new IIOImage(img,null,null);
ImageWriteParam param=writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality((float)quality / 100.0f);
output=new MemoryCacheImageOutputStream(out);
writer.setOutput(output);
writer.write(null,iioi,param);
}
catch(Exception e) {
logging.warn(e);
}
finally {
if(output != null) {
output.close();
}
}
}
@Override
protected boolean doOutput(HttpServletRequest req, HttpMethod method, String action, OutputProvider out, User user) throws ServletException, IOException {
String profileKey=req.getParameter(profileParamKey);
if(profileKey==null || profileKey.length()==0) {
if(defaultProfile!=null) profileKey=defaultProfile;
else return false;
}
ImageProfile profile=imageProfiles.get(profileKey);
if(profile==null) return false;
String imageid=req.getParameter(imageIdParamKey);
if(imageid==null || imageid.length()==0) return false;
for(ImageSource source : imageSources.values()){
String s=source.matchSource(imageid);
if(s!=null){
try {
BufferedImage img=readImage(s);
if(img==null) continue;
BufferedImage processedImg=profile.imageMaker.makeImg(img);
if(processedImg==null) {
logging.warn("Image maker returned null");
break;
}
OutputStream outStream=out.getOutputStream();
try {
HashMap<String,String> metadata=new HashMap<String,String>();
metadata.put("contenttype","image/jpeg");
writeMetadata(metadata, outStream);
writeImage(processedImg, profile, outStream);
}
finally{
outStream.close();
}
return true;
}
catch(IOException ioe){
logging.debug("Couldn't read image "+s,ioe);
}
}
}
BufferedImage errorImage=profile.getErrorImage();
if(errorImage!=null){
OutputStream outStream=out.getOutputStream();
try {
HashMap<String,String> metadata=new HashMap<String,String>();
metadata.put("contenttype","image/jpeg");
writeMetadata(metadata, outStream);
writeImage(errorImage, profile, outStream);
}
finally{
outStream.close();
}
return true;
}
return false;
}
private LinkedHashMap<String,String> getCacheKeyParams(HttpServletRequest req, HttpMethod method, String action) {
LinkedHashMap<String,String> params=new LinkedHashMap<String,String>();
String profile=req.getParameter(profileParamKey);
if(profile==null || profile.length()==0) {
if(defaultProfile!=null) {
profile=defaultProfile;
}
else return null;
}
String imageid=req.getParameter(imageIdParamKey);
if(imageid==null || imageid.length()==0) return null;
params.put("profile",profile);
params.put("imageid",imageid);
params.put("action",action);
return params;
}
@Override
protected String getCacheKey(HttpServletRequest req, HttpMethod method, String action) {
LinkedHashMap<String,String> cacheKeyParams=getCacheKeyParams(req, method, action);
if(cacheKeyParams==null) return null;
return CachedAction.buildCacheKey(cacheKeyParams);
}
/**
* A simple interface for image sources. An image source is just a
* function that translates an image id into an image URL.
*/
public static interface ImageSource {
/**
* Translate an image id into an image URL. If this image source
* is not applicable with the given id, return null instead.
* @param imageid The image id.
* @return The URL the image id translates to, or null if this source
* is not applicable with the given id.
*/
public String matchSource(String imageid);
}
/**
* An image source that does the image id translation using regular
* expressions.
*/
public static class PatternImageSource implements ImageSource {
public String id;
public Pattern pattern;
public String replacement;
public PatternImageSource(){}
@Override
public String matchSource(String imageid) {
Matcher m=pattern.matcher(imageid);
if(m.matches()){
return m.replaceAll(replacement);
}
else return null;
}
}
/**
* A data structure that holds information about the image profile.
*/
public static class ImageProfile {
public String id; // id for the profile used in settings file, used also in the URL to select profile
public int quality=85; // quality at which the cached image is saved (for jpg 0-100)
public String error=null; // image to use in all error cases
public BufferedImage errorImage=null; // error image is cached here when it's first needed
public ImageMaker imageMaker; // ImageMaker that transforms original image into cached image
public ImageProfile(){}
public BufferedImage getErrorImage(){
if(error!=null){
if(errorImage==null){
try{
errorImage=ImageIO.read(new URL(error));
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
return errorImage;
}
else return null;
}
}
public static interface ImageMaker {
public BufferedImage makeImg(BufferedImage original);
}
public static class DefaultImageMaker implements ImageMaker {
public int width=-1; // width of the image or -1 to determine it automatically
public int height=-1; // height of the image or -1 to determine it automatically
public java.awt.Color bgColor=java.awt.Color.BLACK; // bg color of image if the original image doesn't fill the cached image completely
boolean crop=false; // if true, original image is cropped so that it fills the cached image, otherwise it is scaled to fit in the cached image
boolean noExtraCanvas=false;
public String watermark=null; // image file for watermark
public String watermarkMode="lowerright"; // how to place watermark, currently only supports "lowerright"
public double scale=1.0; // scale image after width, height and cropping mode have been decided
public BufferedImage watermarkImage=null; // watermark image is cached here when it is first needed
public DefaultImageMaker(){};
public DefaultImageMaker(int width,int height,java.awt.Color bgColor,boolean crop, boolean noExtraCanvas, double scale,String watermark,String watermarkMode){
this.width=width;
this.height=height;
this.bgColor=bgColor;
this.crop=crop;
this.noExtraCanvas=noExtraCanvas;
this.scale=scale;
this.watermark=watermark;
this.watermarkMode=watermarkMode;
}
@Override
public BufferedImage makeImg(BufferedImage original){
int width=this.width;
int height=this.height;
int ow=original.getWidth();
int oh=original.getHeight();
double or=(double)ow/(double)oh;
int nw=0;
int nh=0;
if(width==-1 && height!=-1) {
width=(int)(height*or+0.5);
}
else if(width!=-1 && height==-1){
height=(int)(width/or+0.5);
}
else if(width==-1 && height==-1){
height=oh;
width=ow;
}
double nr=(double)width/(double)height;
if(crop){
if(or>nr){
nh=height;
nw=(int)(height*or+0.5);
}
else{
nw=width;
nh=(int)(width/or+0.5);
}
}
else{
if(or>nr){
nw=width;
nh=(int)(width/or+0.5);
}
else{
nh=height;
nw=(int)(height*or+0.5);
}
}
if(scale!=1.0){
nw=(int)((double)ow+scale*((double)nw-(double)ow)+0.5);
nh=(int)((double)oh+scale*((double)nh-(double)oh)+0.5);
}
if(noExtraCanvas) {
width = nw;
height = nh;
}
BufferedImage img;
Graphics2D g2;
if(ow==width && oh==height && nw==width && nh==height && watermark==null) {
img=original;
g2 = img.createGraphics();
}
else {
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g2 = img.createGraphics();
g2.setColor(bgColor);
g2.fillRect(0,0, width,height);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY );
Image resized = original.getScaledInstance( nw, nh, BufferedImage.SCALE_SMOOTH );
g2.drawImage(resized, (int)(width/2.0-nw/2.0+0.5), (int)(height/2.0-nh/2.0+0.5), null);
//g2.drawImage(original, (int)(width/2.0-nw/2.0+0.5), (int)(height/2.0-nh/2.0+0.5), nw, nh, null);
}
if(watermark!=null){
if(watermarkImage==null){
try{
watermarkImage=ImageIO.read(new URL(watermark));
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
if(watermarkMode.equals("lowerright")){
if(watermarkImage != null) {
try {
int x=width-watermarkImage.getWidth();
int y=height-watermarkImage.getHeight();
g2.drawImage(watermarkImage,x,y,null);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
return img;
}
}
}
| 25,924 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
DiskCacheModule.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/cache/DiskCacheModule.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.cache;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.wandora.modules.AbstractModule;
import org.wandora.modules.Module;
import org.wandora.modules.ModuleException;
import org.wandora.modules.ModuleManager;
/**
* <p>
* Stores cached content on a file system. The file names are MD5 hashes
* of the provided cache key. To avoid hash collisions, the key is stored at the
* start of each cache file and is checked when the cached input stream is returned.
* The returned input and output streams are at the position where the actual
* cached contents are read/written, that is, this class handles internally
* everything about the keys. Note that hash collisions should be extremely
* rare.
* </p>
* <p>
* Use parameter name cacheDir in init options to set the directory where files
* are cached. maxCacheTime parameter can be used to set the maximum age of
* cached content. Any page that is older than that will not be returned from the
* cache. The time is given in milliseconds. Use 0 for no cache expiry, this is
* the default setting.
* </p>
* <p>
* The cached files can optionally be organised into a directory tree based on
* the first few characters of the MD5 hash. This avoids having directories
* with massive amounts of files which may in some situations be problematic. To
* configure this in the module parameters, use parameter names numSubdirs and
* subdirPrefixLength. subdirPrefixLength is the number of characters to use for
* each subdir, it defaults to 2. numSubdirs is the number of subdirectories to
* use, it defaults to 0, i.e. put everything directly under the cache directory
* instead of using any subdirectories.
* </p>
* <p>
* It is essential that the streams returned by getPage and storePage be closed
* properly. Failing to do so will cause the cache to remain locked. Even if an
* IOException is thrown by one of the read methods, close should still be called.
* </p>
*
* @author olli
*/
public class DiskCacheModule extends AbstractModule implements CacheService {
protected final String COLLISION_SUFFIX="___collision";
protected int numSubdirs=0;
protected int subdirPrefixLength=2;
protected long maxCacheTime=0;
protected ReadWriteLock cacheLock = new ReentrantReadWriteLock(false);
protected String cacheDir;
@Override
public Collection<Module> getDependencies(ModuleManager manager) throws ModuleException {
Collection<Module> deps=super.getDependencies(manager);
requireLogging(manager, deps);
return deps;
}
@Override
public void init(ModuleManager manager, Map<String, Object> settings) throws ModuleException {
super.init(manager, settings);
Object cacheDirO=settings.get("cacheDir");
if(cacheDirO!=null) {
this.cacheDir=cacheDirO.toString();
if(!this.cacheDir.endsWith(File.separator)) this.cacheDir=this.cacheDir+File.separator;
}
else throw new ModuleException("Cache dir not provided, use key cacheDir");
Object o=settings.get("maxCacheTime");
if(o!=null) maxCacheTime=Long.parseLong(o.toString());
o=settings.get("numSubdirs");
if(o!=null) numSubdirs=Integer.parseInt(o.toString());
o=settings.get("subdirPrefixLength");
if(o!=null) subdirPrefixLength=Integer.parseInt(o.toString());
}
@Override
public void start(ModuleManager manager) throws ModuleException {
File dir=new File(cacheDir);
if(!dir.exists()) {
if(!dir.mkdirs()) throw new ModuleException("Could not create cache directory");
}
else {
if(!dir.isDirectory())
throw new ModuleException("File with the same name as the cache directory already exists");
}
super.start(manager);
}
@Override
public void stop(ModuleManager manager) {
cacheLock.writeLock().lock();
try{
super.stop(manager);
}finally{
cacheLock.writeLock().unlock();
}
}
protected String makeHash(String key){
MessageDigest hasher=null;
try{
hasher=MessageDigest.getInstance("MD5");
}catch(NoSuchAlgorithmException nsae){
// this shouldn't happen, MD5 is required to be implemented by all Java VMs
logging.error(nsae);
return null;
}
try{
byte[] hashBytes=hasher.digest(key.getBytes("UTF-8"));
StringBuilder sb=new StringBuilder();
for(int i=0;i<hashBytes.length;i++){
String s=Integer.toHexString(hashBytes[i]<0?256+hashBytes[i]:hashBytes[i]);
if(s.length()==1) sb.append("0");
sb.append(s);
}
return sb.toString();
}
catch(UnsupportedEncodingException uee){
logging.error(uee);
return null;
}
}
protected String readCacheFileKey(InputStream in) throws IOException {
byte[] keyBytes=new byte[256];
int pos=0;
int read=in.read();
while(read!=-1 && read!=0){
if(pos==keyBytes.length) {
byte[] newBytes=new byte[keyBytes.length*2];
System.arraycopy(keyBytes, 0, newBytes, 0, keyBytes.length);
keyBytes=newBytes;
}
keyBytes[pos++]=(byte)read;
read=in.read();
}
try{
return new String(keyBytes, 0, pos, "UTF-8");
}catch(UnsupportedEncodingException uee){
logging.error(uee);
return null;
}
}
protected String getSubdirs(String hash){
if(numSubdirs<=0 || subdirPrefixLength<=0) return "";
String subdirs="";
for(int i=0;i<numSubdirs;i++){
subdirs+=hash.substring(i*subdirPrefixLength,(i+1)*subdirPrefixLength)+File.separator;
}
return subdirs;
}
// you should have the read lock before calling this
protected InputStream getInputStream(String originalKey, long modifyTime) {
String key=originalKey;
try{
while(true){
String hash=makeHash(key);
String subdirs=getSubdirs(hash);
File f=new File(cacheDir+subdirs+hash);
if(!f.exists()) return null;
FileInputStream fis=new FileInputStream(f);
// read bytes until first zero byte, those bytes contain the key used to store this file
String readKey=readCacheFileKey(fis);
// make sure that the key we read is the expected key
if(!readKey.equals(originalKey)) {
// hash collision, close this input stream and try again with a different key
fis.close();
key=key+COLLISION_SUFFIX;
}
else {
// check the modify time if we were provided a sane value for it
if(modifyTime>0 && modifyTime>f.lastModified()) return null;
return fis;
}
}
}catch(IOException ioe){
logging.error(ioe);
return null;
}
}
protected void writeCacheFileKey(OutputStream out, String key) throws IOException {
byte[] bytes=key.getBytes("UTF-8");
out.write(bytes);
out.write(0);
}
// you should have the write lock before calling this
protected OutputStream getOutputStream(String originalKey) throws IOException {
String key=originalKey;
try{
while(true){
String hash=makeHash(key);
String subdirs=getSubdirs(hash);
if(subdirs.length()>0){
File dir=new File(cacheDir+subdirs);
if(!dir.exists()) {
if(!dir.mkdirs()) {
logging.error("Couldn't create cache prefix directory "+cacheDir+subdirs);
return null;
}
}
}
File f=new File(cacheDir+subdirs+hash);
if(f.exists()) {
FileInputStream fis=new FileInputStream(f);
// read bytes until first zero byte, those bytes contain the key used to store this file
String readKey=readCacheFileKey(fis);
// make sure that the key we read is the expected key
if(!readKey.equals(originalKey)) {
// hash collision, close this input stream and try again with a different key
fis.close();
key=key+COLLISION_SUFFIX;
logging.debug("Cache hash collision for keys "+readKey+" and "+key);
continue;
}
else {
// this file is the old version of the page we want to store
// so we can just overwrite this file
fis.close();
}
}
OutputStream out=new FileOutputStream(f);
writeCacheFileKey(out, originalKey);
return out;
}
}catch(IOException ioe){
logging.error(ioe);
return null;
}
}
@Override
public InputStream getPage(String key, long modifyTime) {
cacheLock.readLock().lock();
boolean lockReturned=false;
try{
if(maxCacheTime>0){
modifyTime=Math.max(modifyTime, System.currentTimeMillis()-maxCacheTime);
}
InputStream in=getInputStream(key, modifyTime);
if(in!=null){
// lockReturned=true;
// return new LockedInputStream(in);
return in;
}
else return null;
}
finally{
if(!lockReturned) cacheLock.readLock().unlock();
}
}
@Override
public OutputStream storePage(String key, long modifyTime) {
cacheLock.writeLock().lock();
boolean lockReturned=false;
try{
OutputStream out=getOutputStream(key);
if(out!=null) {
lockReturned=true;
return new LockedOutputStream(out);
}
else return null;
}
catch(IOException ioe){
logging.error(ioe);
return null;
}
finally {
if(!lockReturned) cacheLock.writeLock().unlock();
}
}
private class LockedInputStream extends InputStream {
private InputStream in;
private boolean released=false;
public LockedInputStream(InputStream in){
this.in=in;
}
private void release(){
if(!released) {
cacheLock.readLock().unlock();
released=true;
}
}
@Override
public int available() throws IOException {
return in.available();
}
@Override
public void close() throws IOException {
release();
in.close();
}
@Override
public int read(byte[] b) throws IOException {
return in.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
@Override
public int read() throws IOException {
return in.read();
}
}
private class LockedOutputStream extends OutputStream {
private OutputStream out;
private boolean released=false;
public LockedOutputStream(OutputStream out){
this.out=out;
}
private void release(){
if(!released){
cacheLock.writeLock().unlock();
released=true;
}
}
@Override
public void close() throws IOException {
release();
out.close();
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void write(byte[] b) throws IOException {
out.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
}
}
| 14,140 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
CacheService.java | /FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/modules/cache/CacheService.java | /*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2023 Wandora Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.wandora.modules.cache;
import org.wandora.modules.Module;
/**
* <p>
* An interface for caching services. Pages, which can be any content really,
* can be stored in the cache using cache keys. The key is just any string that
* identifies the cached page. The pages are then retrieved using the same keys.
* In addition, timestamps in milliseconds can be used so that cached pages older
* than a specified value are not reused.
* </p>
* <p>
* It is vital that the InputStreams and OutputStreams returned by getPage and
* storePage be properly closed in all cases, even if exceptions are encountered.
* Failing to do so may cause the cache to remain in a locked state and other
* threads be unable to use it.
* </p>
* <p>
* See CachedAction for an abstract action that can take advantage of caching
* services.
* </p>
* @author olli
*/
public interface CacheService extends Module {
/**
* Gets a cached version of a page if one exists in the cache. If
* modifyTime parameter is greater than 0, the page must be never than the
* time indicated by the parameter. If a cached version doesn't exist, or
* it is too old, returns null.
*
* @param key The key of the cached page.
* @param modifyTime The minimum caching time of the page, or 0 if no such limit is used.
* @return An input stream from which the stored page can be read. The
* stream must be properly closed afterwards.
*/
public java.io.InputStream getPage(String key,long modifyTime);
/**
* Stores a cached version of a page with the given time stamp.
*
* @param key The key of the cached page.
* @param modifyTime A timestamp for the cached version.
* @return An output stream into which the cached version is written. The
* stream must be properly closed afterwards.
*/
public java.io.OutputStream storePage(String key,long modifyTime);
}
| 2,754 | Java | .java | wandora-team/wandora | 126 | 26 | 0 | 2014-06-30T10:25:42Z | 2023-09-09T07:13:29Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.