lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | agpl-3.0 | 1d6fe2631747b6e6f82b2523a372c11edb24d5eb | 0 | jpos/jPOS,yinheli/jPOS,barspi/jPOS,juanibdn/jPOS,jpos/jPOS,fayezasar/jPOS,yinheli/jPOS,juanibdn/jPOS,bharavi/jPOS,fayezasar/jPOS,sebastianpacheco/jPOS,c0deh4xor/jPOS,alcarraz/jPOS,atancasis/jPOS,alcarraz/jPOS,bharavi/jPOS,sebastianpacheco/jPOS,poynt/jPOS,bharavi/jPOS,chhil/jPOS,jpos/jPOS,juanibdn/jPOS,alcarraz/jPOS,c0deh4xor/jPOS,imam-san/jPOS-1,imam-san/jPOS-1,barspi/jPOS,chhil/jPOS,atancasis/jPOS,atancasis/jPOS,c0deh4xor/jPOS,poynt/jPOS,imam-san/jPOS-1,barspi/jPOS,yinheli/jPOS,sebastianpacheco/jPOS,poynt/jPOS | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2012 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.util;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* Simple Profiler
* @author Alejandro P. Revilla
* @author David D. Bergert
* @version $Id$
*/
public class Profiler implements Loggeable {
long start, partial;
LinkedHashMap events;
public static final int TO_MILLIS = 1000000;
public Profiler () {
super();
reset();
}
/**
* reset timers
*/
public void reset() {
start = partial = System.nanoTime();
events = new LinkedHashMap();
}
/**
* mark checkpoint
* @param detail checkpoint information
*/
@SuppressWarnings("unchecked")
public synchronized void checkPoint (String detail) {
long now = System.nanoTime();
Entry e = new Entry();
e.setDurationInNanos((now - partial));
e.setTotalDurationInNanos((now - start));
if (events.containsKey(detail)) {
for (int i=1; ;i++) {
String d = detail + "-" + i;
if (!events.containsKey (d)) {
detail = d;
break;
}
}
}
e.setEventName(detail);
events.put (detail, e);
partial = now;
}
/**
* @return total elapsed time since last reset
*/
public long getElapsed() {
return System.nanoTime() - start;
}
/**
* @return parcial elapsed time since last reset
*/
public long getPartial() {
return System.nanoTime() - partial;
}
public void dump (PrintStream p, String indent) {
String inner = indent + " ";
if (!events.containsKey("end"))
checkPoint ("end");
Collection c = events.values();
Iterator iter = c.iterator();
p.println (indent + "<profiler>");
while (iter.hasNext())
p.println (inner + iter.next().toString());
p.println (indent + "</profiler>");
}
public Entry getEntry(String eventName) {
return (Entry)events.get(eventName);
}
public static class Entry {
String eventName;
long duration;
long totalDuration;
public Entry() {
eventName = "";
duration = 0L;
totalDuration = 0L;
}
public void setEventName (String myEvent) {
this.eventName = myEvent;
}
public String getEventName () {
return eventName;
}
public void setDurationInNanos (long duration) {
this.duration = duration;
}
public long getDuration () {
return duration / TO_MILLIS;
}
public long getDurationInNanos() {
return duration;
}
public void setTotalDurationInNanos (long totalDuration) {
this.totalDuration = totalDuration;
}
public long getTotalDuration () {
return totalDuration / TO_MILLIS;
}
public long getTotalDurationInNanos () {
return totalDuration;
}
public String toString() {
StringBuilder sb = new StringBuilder (eventName);
sb.append (" [");
sb.append (getDuration());
sb.append ('.');
sb.append ((duration % TO_MILLIS) / 100000);
sb.append ('/');
sb.append (getTotalDuration ());
sb.append ('.');
sb.append ((totalDuration % TO_MILLIS) / 100000);
sb.append (']');
return sb.toString();
}
}
}
| jpos/src/main/java/org/jpos/util/Profiler.java | /*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2012 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.util;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
/**
* Simple Profiler
* @author Alejandro P. Revilla
* @author David D. Bergert
* @version $Id$
*/
public class Profiler implements Loggeable {
long start, partial;
LinkedHashMap events;
public static final int TO_MILLIS = 1000000;
public Profiler () {
super();
reset();
}
/**
* reset timers
*/
public void reset() {
start = partial = System.nanoTime();
events = new LinkedHashMap();
}
/**
* mark checkpoint
* @param detail checkpoint information
*/
@SuppressWarnings("unchecked")
public synchronized void checkPoint (String detail) {
long now = System.nanoTime();
Entry e = new Entry();
e.setDurationInNanos((now - partial));
e.setTotalDurationInNanos((now - start));
if (events.containsKey(detail)) {
for (int i=1; ;i++) {
String d = detail + "-" + i;
if (!events.containsKey (d)) {
detail = d;
break;
}
}
}
e.setEventName(detail);
events.put (detail, e);
partial = now;
}
/**
* @return total elapsed time since last reset
*/
public long getElapsed() {
return System.nanoTime() - start;
}
/**
* @return parcial elapsed time since last reset
*/
public long getPartial() {
return System.nanoTime() - partial;
}
public void dump (PrintStream p, String indent) {
String inner = indent + " ";
partial = start;
if (!events.containsKey("end"))
checkPoint ("end");
Collection c = events.values();
Iterator iter = c.iterator();
p.println (indent + "<profiler>");
while (iter.hasNext())
p.println (inner + iter.next().toString());
p.println (indent + "</profiler>");
}
public Entry getEntry(String eventName) {
return (Entry)events.get(eventName);
}
public static class Entry {
String eventName;
long duration;
long totalDuration;
public Entry() {
eventName = "";
duration = 0L;
totalDuration = 0L;
}
public void setEventName (String myEvent) {
this.eventName = myEvent;
}
public String getEventName () {
return eventName;
}
public void setDurationInNanos (long duration) {
this.duration = duration;
}
public long getDuration () {
return duration / TO_MILLIS;
}
public long getDurationInNanos() {
return duration;
}
public void setTotalDurationInNanos (long totalDuration) {
this.totalDuration = totalDuration;
}
public long getTotalDuration () {
return totalDuration / TO_MILLIS;
}
public long getTotalDurationInNanos () {
return totalDuration;
}
public String toString() {
StringBuilder sb = new StringBuilder (eventName);
sb.append (" [");
sb.append (getDuration());
sb.append ('.');
sb.append ((duration % TO_MILLIS) / 100000);
sb.append ('/');
sb.append (getTotalDuration ());
sb.append ('.');
sb.append ((totalDuration % TO_MILLIS) / 100000);
sb.append (']');
return sb.toString();
}
}
}
| End now shows partial time after last checkpoint
Issue detected by @andyorrock, patch provided by @murtuzachhil - THANK YOU!
| jpos/src/main/java/org/jpos/util/Profiler.java | End now shows partial time after last checkpoint |
|
Java | lgpl-2.1 | 7476fbc2e021b17f94b8b89c78dfc74c5714bd70 | 0 | aaronc/jfreechart,aaronc/jfreechart,aaronc/jfreechart | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2009, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------
* JDBCXYDataset.java
* ------------------
* (C) Copyright 2002-2009, by Bryan Scott and Contributors.
*
* Original Author: Bryan Scott;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Eric Alexander;
*
*
* Changes
* -------
* 14-Mar-2002 : Version 1 contributed by Bryan Scott (DG);
* 19-Apr-2002 : Updated executeQuery, to close cursors and to improve support
* for types.
* 26-Apr-2002 : Renamed JdbcXYDataset to better fit in with the existing data
* source conventions.
* 26-Apr-2002 : Changed to extend AbstractDataset.
* 13-Aug-2002 : Updated Javadoc comments and imports (DG);
* 18-Sep-2002 : Updated to support BIGINT (BS);
* 21-Jan-2003 : Renamed JdbcXYDataset --> JDBCXYDataset (DG);
* 01-Jul-2003 : Added support to query whether a timeseries (BS);
* 30-Jul-2003 : Added empty contructor and executeQuery(connection,string)
* method (BS);
* 24-Sep-2003 : Added a check to ensure at least two valid columns are
* returned by the query in executeQuery as suggest in online
* forum by anonymous (BS);
* 02-Dec-2003 : Throwing exceptions allows to handle errors, removed default
* constructor, as without a connection, a query can never be
* executed.
* 16-Mar-2004 : Added check for null values (EA);
* 05-May-2004 : Now extends AbstractXYDataset (DG);
* 21-May-2004 : Implemented TableXYDataset, added support for SMALLINT and
* fixed bug in code that determines the min and max values (see
* bug id 938138) (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 18-Nov-2004 : Updated for changes in RangeInfo interface (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 17-Oct-2006 : Deprecated unused methods - see bug 1578293 (DG);
* 19-May-2009 : Fixed FindBugs warnings, patch by Michal Wozniak (DG);
*
*/
package org.jfree.data.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.Dataset;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.util.Log;
/**
* This class provides an {@link XYDataset} implementation over a database
* JDBC result set. The dataset is populated via a call to executeQuery with
* the string sql query. The sql query must return at least two columns.
* The first column will be the x-axis and remaining columns y-axis values.
* executeQuery can be called a number of times.
*
* The database connection is read-only and no write back facility exists.
*/
public class JDBCXYDataset extends AbstractXYDataset
implements XYDataset, TableXYDataset, RangeInfo {
/** The database connection. */
private transient Connection connection;
/** Column names. */
private String[] columnNames = {};
/** Rows. */
private ArrayList rows;
/** The maximum y value of the returned result set */
private double maxValue = 0.0;
/** The minimum y value of the returned result set */
private double minValue = 0.0;
/** Is this dataset a timeseries ? */
private boolean isTimeSeries = false;
/**
* Creates a new JDBCXYDataset (initially empty) with no database
* connection.
*/
private JDBCXYDataset() {
this.rows = new ArrayList();
}
/**
* Creates a new dataset (initially empty) and establishes a new database
* connection.
*
* @param url URL of the database connection.
* @param driverName the database driver class name.
* @param user the database user.
* @param password the database user's password.
*
* @throws ClassNotFoundException if the driver cannot be found.
* @throws SQLException if there is a problem connecting to the database.
*/
public JDBCXYDataset(String url,
String driverName,
String user,
String password)
throws SQLException, ClassNotFoundException {
this();
Class.forName(driverName);
this.connection = DriverManager.getConnection(url, user, password);
}
/**
* Creates a new dataset (initially empty) using the specified database
* connection.
*
* @param con the database connection.
*
* @throws SQLException if there is a problem connecting to the database.
*/
public JDBCXYDataset(Connection con) throws SQLException {
this();
this.connection = con;
}
/**
* Creates a new dataset using the specified database connection, and
* populates it using data obtained with the supplied query.
*
* @param con the connection.
* @param query the SQL query.
*
* @throws SQLException if there is a problem executing the query.
*/
public JDBCXYDataset(Connection con, String query) throws SQLException {
this(con);
executeQuery(query);
}
/**
* Returns <code>true</code> if the dataset represents time series data,
* and <code>false</code> otherwise.
*
* @return A boolean.
*/
public boolean isTimeSeries() {
return this.isTimeSeries;
}
/**
* Sets a flag that indicates whether or not the data represents a time
* series.
*
* @param timeSeries the new value of the flag.
*/
public void setTimeSeries(boolean timeSeries) {
this.isTimeSeries = timeSeries;
}
/**
* ExecuteQuery will attempt execute the query passed to it against the
* existing database connection. If no connection exists then no action
* is taken.
*
* The results from the query are extracted and cached locally, thus
* applying an upper limit on how many rows can be retrieved successfully.
*
* @param query the query to be executed.
*
* @throws SQLException if there is a problem executing the query.
*/
public void executeQuery(String query) throws SQLException {
executeQuery(this.connection, query);
}
/**
* ExecuteQuery will attempt execute the query passed to it against the
* provided database connection. If connection is null then no action is
* taken.
*
* The results from the query are extracted and cached locally, thus
* applying an upper limit on how many rows can be retrieved successfully.
*
* @param query the query to be executed.
* @param con the connection the query is to be executed against.
*
* @throws SQLException if there is a problem executing the query.
*/
public void executeQuery(Connection con, String query)
throws SQLException {
if (con == null) {
throw new SQLException(
"There is no database to execute the query."
);
}
ResultSet resultSet = null;
Statement statement = null;
try {
statement = con.createStatement();
resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
int numberOfValidColumns = 0;
int [] columnTypes = new int[numberOfColumns];
for (int column = 0; column < numberOfColumns; column++) {
try {
int type = metaData.getColumnType(column + 1);
switch (type) {
case Types.NUMERIC:
case Types.REAL:
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
case Types.DECIMAL:
case Types.BIT:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.BIGINT:
case Types.SMALLINT:
++numberOfValidColumns;
columnTypes[column] = type;
break;
default:
Log.warn(
"Unable to load column "
+ column + " (" + type + ","
+ metaData.getColumnClassName(column + 1)
+ ")"
);
columnTypes[column] = Types.NULL;
break;
}
}
catch (SQLException e) {
columnTypes[column] = Types.NULL;
throw e;
}
}
if (numberOfValidColumns <= 1) {
throw new SQLException(
"Not enough valid columns where generated by query."
);
}
/// First column is X data
this.columnNames = new String[numberOfValidColumns - 1];
/// Get the column names and cache them.
int currentColumn = 0;
for (int column = 1; column < numberOfColumns; column++) {
if (columnTypes[column] != Types.NULL) {
this.columnNames[currentColumn]
= metaData.getColumnLabel(column + 1);
++currentColumn;
}
}
// Might need to add, to free memory from any previous result sets
if (this.rows != null) {
for (int column = 0; column < this.rows.size(); column++) {
ArrayList row = (ArrayList) this.rows.get(column);
row.clear();
}
this.rows.clear();
}
// Are we working with a time series.
switch (columnTypes[0]) {
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
this.isTimeSeries = true;
break;
default :
this.isTimeSeries = false;
break;
}
// Get all rows.
// rows = new ArrayList();
while (resultSet.next()) {
ArrayList newRow = new ArrayList();
for (int column = 0; column < numberOfColumns; column++) {
Object xObject = resultSet.getObject(column + 1);
switch (columnTypes[column]) {
case Types.NUMERIC:
case Types.REAL:
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
case Types.DECIMAL:
case Types.BIGINT:
case Types.SMALLINT:
newRow.add(xObject);
break;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
newRow.add(new Long(((Date) xObject).getTime()));
break;
case Types.NULL:
break;
default:
System.err.println("Unknown data");
columnTypes[column] = Types.NULL;
break;
}
}
this.rows.add(newRow);
}
/// a kludge to make everything work when no rows returned
if (this.rows.size() == 0) {
ArrayList newRow = new ArrayList();
for (int column = 0; column < numberOfColumns; column++) {
if (columnTypes[column] != Types.NULL) {
newRow.add(new Integer(0));
}
}
this.rows.add(newRow);
}
/// Determine max and min values.
if (this.rows.size() < 1) {
this.maxValue = 0.0;
this.minValue = 0.0;
}
else {
this.maxValue = Double.NEGATIVE_INFINITY;
this.minValue = Double.POSITIVE_INFINITY;
for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) {
ArrayList row = (ArrayList) this.rows.get(rowNum);
for (int column = 1; column < numberOfColumns; column++) {
Object testValue = row.get(column);
if (testValue != null) {
double test = ((Number) testValue).doubleValue();
if (test < this.minValue) {
this.minValue = test;
}
if (test > this.maxValue) {
this.maxValue = test;
}
}
}
}
}
fireDatasetChanged(); // Tell the listeners a new table has arrived.
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (Exception e) {
// TODO: is this a good idea?
}
}
if (statement != null) {
try {
statement.close();
}
catch (Exception e) {
// TODO: is this a good idea?
}
}
}
}
/**
* Returns the x-value for the specified series and item. The
* implementation is responsible for ensuring that the x-values are
* presented in ascending order.
*
* @param seriesIndex the series (zero-based index).
* @param itemIndex the item (zero-based index).
*
* @return The x-value
*
* @see XYDataset
*/
public Number getX(int seriesIndex, int itemIndex) {
ArrayList row = (ArrayList) this.rows.get(itemIndex);
return (Number) row.get(0);
}
/**
* Returns the y-value for the specified series and item.
*
* @param seriesIndex the series (zero-based index).
* @param itemIndex the item (zero-based index).
*
* @return The yValue value
*
* @see XYDataset
*/
public Number getY(int seriesIndex, int itemIndex) {
ArrayList row = (ArrayList) this.rows.get(itemIndex);
return (Number) row.get(seriesIndex + 1);
}
/**
* Returns the number of items in the specified series.
*
* @param seriesIndex the series (zero-based index).
*
* @return The itemCount value
*
* @see XYDataset
*/
public int getItemCount(int seriesIndex) {
return this.rows.size();
}
/**
* Returns the number of items in all series. This method is defined by
* the {@link TableXYDataset} interface.
*
* @return The item count.
*/
public int getItemCount() {
return getItemCount(0);
}
/**
* Returns the number of series in the dataset.
*
* @return The seriesCount value
*
* @see XYDataset
* @see Dataset
*/
public int getSeriesCount() {
return this.columnNames.length;
}
/**
* Returns the key for the specified series.
*
* @param seriesIndex the series (zero-based index).
*
* @return The seriesName value
*
* @see XYDataset
* @see Dataset
*/
public Comparable getSeriesKey(int seriesIndex) {
if ((seriesIndex < this.columnNames.length)
&& (this.columnNames[seriesIndex] != null)) {
return this.columnNames[seriesIndex];
}
else {
return "";
}
}
/**
* Returns the number of items that should be displayed in the legend.
*
* @return The legendItemCount value
*
* @deprecated This method is not used in JFreeChart 1.0.x (it was left in
* the API by mistake and is officially deprecated from version 1.0.3
* onwards).
*/
public int getLegendItemCount() {
return getSeriesCount();
}
/**
* Returns the legend item labels.
*
* @return The legend item labels.
*
* @deprecated This method is not used in JFreeChart 1.0.x (it was left in
* the API by mistake and is officially deprecated from version 1.0.3
* onwards).
*/
public String[] getLegendItemLabels() {
return this.columnNames;
}
/**
* Close the database connection
*/
public void close() {
try {
this.connection.close();
}
catch (Exception e) {
System.err.println("JdbcXYDataset: swallowing exception.");
}
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*/
public double getRangeLowerBound(boolean includeInterval) {
return this.minValue;
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*/
public double getRangeUpperBound(boolean includeInterval) {
return this.maxValue;
}
/**
* Returns the range of the values in this dataset's range.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range.
*/
public Range getRangeBounds(boolean includeInterval) {
return new Range(this.minValue, this.maxValue);
}
}
| source/org/jfree/data/jdbc/JDBCXYDataset.java | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------
* JDBCXYDataset.java
* ------------------
* (C) Copyright 2002-2008, by Bryan Scott and Contributors.
*
* Original Author: Bryan Scott;
* Contributor(s): David Gilbert (for Object Refinery Limited);
* Eric Alexander;
*
*
* Changes
* -------
* 14-Mar-2002 : Version 1 contributed by Bryan Scott (DG);
* 19-Apr-2002 : Updated executeQuery, to close cursors and to improve support
* for types.
* 26-Apr-2002 : Renamed JdbcXYDataset to better fit in with the existing data
* source conventions.
* 26-Apr-2002 : Changed to extend AbstractDataset.
* 13-Aug-2002 : Updated Javadoc comments and imports (DG);
* 18-Sep-2002 : Updated to support BIGINT (BS);
* 21-Jan-2003 : Renamed JdbcXYDataset --> JDBCXYDataset (DG);
* 01-Jul-2003 : Added support to query whether a timeseries (BS);
* 30-Jul-2003 : Added empty contructor and executeQuery(connection,string)
* method (BS);
* 24-Sep-2003 : Added a check to ensure at least two valid columns are
* returned by the query in executeQuery as suggest in online
* forum by anonymous (BS);
* 02-Dec-2003 : Throwing exceptions allows to handle errors, removed default
* constructor, as without a connection, a query can never be
* executed.
* 16-Mar-2004 : Added check for null values (EA);
* 05-May-2004 : Now extends AbstractXYDataset (DG);
* 21-May-2004 : Implemented TableXYDataset, added support for SMALLINT and
* fixed bug in code that determines the min and max values (see
* bug id 938138) (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 18-Nov-2004 : Updated for changes in RangeInfo interface (DG);
* 11-Jan-2005 : Removed deprecated code in preparation for the 1.0.0
* release (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 17-Oct-2006 : Deprecated unused methods - see bug 1578293 (DG);
*
*/
package org.jfree.data.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import org.jfree.data.Range;
import org.jfree.data.RangeInfo;
import org.jfree.data.general.Dataset;
import org.jfree.data.xy.AbstractXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.util.Log;
/**
* This class provides an {@link XYDataset} implementation over a database
* JDBC result set. The dataset is populated via a call to executeQuery with
* the string sql query. The sql query must return at least two columns.
* The first column will be the x-axis and remaining columns y-axis values.
* executeQuery can be called a number of times.
*
* The database connection is read-only and no write back facility exists.
*/
public class JDBCXYDataset extends AbstractXYDataset
implements XYDataset, TableXYDataset, RangeInfo {
/** The database connection. */
private transient Connection connection;
/** Column names. */
private String[] columnNames = {};
/** Rows. */
private ArrayList rows;
/** The maximum y value of the returned result set */
private double maxValue = 0.0;
/** The minimum y value of the returned result set */
private double minValue = 0.0;
/** Is this dataset a timeseries ? */
private boolean isTimeSeries = false;
/**
* Creates a new JDBCXYDataset (initially empty) with no database
* connection.
*/
private JDBCXYDataset() {
this.rows = new ArrayList();
}
/**
* Creates a new dataset (initially empty) and establishes a new database
* connection.
*
* @param url URL of the database connection.
* @param driverName the database driver class name.
* @param user the database user.
* @param password the database user's password.
*
* @throws ClassNotFoundException if the driver cannot be found.
* @throws SQLException if there is a problem connecting to the database.
*/
public JDBCXYDataset(String url,
String driverName,
String user,
String password)
throws SQLException, ClassNotFoundException {
this();
Class.forName(driverName);
this.connection = DriverManager.getConnection(url, user, password);
}
/**
* Creates a new dataset (initially empty) using the specified database
* connection.
*
* @param con the database connection.
*
* @throws SQLException if there is a problem connecting to the database.
*/
public JDBCXYDataset(Connection con) throws SQLException {
this();
this.connection = con;
}
/**
* Creates a new dataset using the specified database connection, and
* populates it using data obtained with the supplied query.
*
* @param con the connection.
* @param query the SQL query.
*
* @throws SQLException if there is a problem executing the query.
*/
public JDBCXYDataset(Connection con, String query) throws SQLException {
this(con);
executeQuery(query);
}
/**
* Returns <code>true</code> if the dataset represents time series data,
* and <code>false</code> otherwise.
*
* @return A boolean.
*/
public boolean isTimeSeries() {
return this.isTimeSeries;
}
/**
* Sets a flag that indicates whether or not the data represents a time
* series.
*
* @param timeSeries the new value of the flag.
*/
public void setTimeSeries(boolean timeSeries) {
this.isTimeSeries = timeSeries;
}
/**
* ExecuteQuery will attempt execute the query passed to it against the
* existing database connection. If no connection exists then no action
* is taken.
*
* The results from the query are extracted and cached locally, thus
* applying an upper limit on how many rows can be retrieved successfully.
*
* @param query the query to be executed.
*
* @throws SQLException if there is a problem executing the query.
*/
public void executeQuery(String query) throws SQLException {
executeQuery(this.connection, query);
}
/**
* ExecuteQuery will attempt execute the query passed to it against the
* provided database connection. If connection is null then no action is
* taken.
*
* The results from the query are extracted and cached locally, thus
* applying an upper limit on how many rows can be retrieved successfully.
*
* @param query the query to be executed.
* @param con the connection the query is to be executed against.
*
* @throws SQLException if there is a problem executing the query.
*/
public void executeQuery(Connection con, String query)
throws SQLException {
if (con == null) {
throw new SQLException(
"There is no database to execute the query."
);
}
ResultSet resultSet = null;
Statement statement = null;
try {
statement = con.createStatement();
resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
int numberOfValidColumns = 0;
int [] columnTypes = new int[numberOfColumns];
for (int column = 0; column < numberOfColumns; column++) {
try {
int type = metaData.getColumnType(column + 1);
switch (type) {
case Types.NUMERIC:
case Types.REAL:
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
case Types.DECIMAL:
case Types.BIT:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.BIGINT:
case Types.SMALLINT:
++numberOfValidColumns;
columnTypes[column] = type;
break;
default:
Log.warn(
"Unable to load column "
+ column + " (" + type + ","
+ metaData.getColumnClassName(column + 1)
+ ")"
);
columnTypes[column] = Types.NULL;
break;
}
}
catch (SQLException e) {
columnTypes[column] = Types.NULL;
throw e;
}
}
if (numberOfValidColumns <= 1) {
throw new SQLException(
"Not enough valid columns where generated by query."
);
}
/// First column is X data
this.columnNames = new String[numberOfValidColumns - 1];
/// Get the column names and cache them.
int currentColumn = 0;
for (int column = 1; column < numberOfColumns; column++) {
if (columnTypes[column] != Types.NULL) {
this.columnNames[currentColumn]
= metaData.getColumnLabel(column + 1);
++currentColumn;
}
}
// Might need to add, to free memory from any previous result sets
if (this.rows != null) {
for (int column = 0; column < this.rows.size(); column++) {
ArrayList row = (ArrayList) this.rows.get(column);
row.clear();
}
this.rows.clear();
}
// Are we working with a time series.
switch (columnTypes[0]) {
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
this.isTimeSeries = true;
break;
default :
this.isTimeSeries = false;
break;
}
// Get all rows.
// rows = new ArrayList();
while (resultSet.next()) {
ArrayList newRow = new ArrayList();
for (int column = 0; column < numberOfColumns; column++) {
Object xObject = resultSet.getObject(column + 1);
switch (columnTypes[column]) {
case Types.NUMERIC:
case Types.REAL:
case Types.INTEGER:
case Types.DOUBLE:
case Types.FLOAT:
case Types.DECIMAL:
case Types.BIGINT:
case Types.SMALLINT:
newRow.add(xObject);
break;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
newRow.add(new Long(((Date) xObject).getTime()));
break;
case Types.NULL:
break;
default:
System.err.println("Unknown data");
columnTypes[column] = Types.NULL;
break;
}
}
this.rows.add(newRow);
}
/// a kludge to make everything work when no rows returned
if (this.rows.size() == 0) {
ArrayList newRow = new ArrayList();
for (int column = 0; column < numberOfColumns; column++) {
if (columnTypes[column] != Types.NULL) {
newRow.add(new Integer(0));
}
}
this.rows.add(newRow);
}
/// Determine max and min values.
if (this.rows.size() < 1) {
this.maxValue = 0.0;
this.minValue = 0.0;
}
else {
ArrayList row = (ArrayList) this.rows.get(0);
this.maxValue = Double.NEGATIVE_INFINITY;
this.minValue = Double.POSITIVE_INFINITY;
for (int rowNum = 0; rowNum < this.rows.size(); ++rowNum) {
row = (ArrayList) this.rows.get(rowNum);
for (int column = 1; column < numberOfColumns; column++) {
Object testValue = row.get(column);
if (testValue != null) {
double test = ((Number) testValue).doubleValue();
if (test < this.minValue) {
this.minValue = test;
}
if (test > this.maxValue) {
this.maxValue = test;
}
}
}
}
}
fireDatasetChanged(); // Tell the listeners a new table has arrived.
}
finally {
if (resultSet != null) {
try {
resultSet.close();
}
catch (Exception e) {
// TODO: is this a good idea?
}
}
if (statement != null) {
try {
statement.close();
}
catch (Exception e) {
// TODO: is this a good idea?
}
}
}
}
/**
* Returns the x-value for the specified series and item. The
* implementation is responsible for ensuring that the x-values are
* presented in ascending order.
*
* @param seriesIndex the series (zero-based index).
* @param itemIndex the item (zero-based index).
*
* @return The x-value
*
* @see XYDataset
*/
public Number getX(int seriesIndex, int itemIndex) {
ArrayList row = (ArrayList) this.rows.get(itemIndex);
return (Number) row.get(0);
}
/**
* Returns the y-value for the specified series and item.
*
* @param seriesIndex the series (zero-based index).
* @param itemIndex the item (zero-based index).
*
* @return The yValue value
*
* @see XYDataset
*/
public Number getY(int seriesIndex, int itemIndex) {
ArrayList row = (ArrayList) this.rows.get(itemIndex);
return (Number) row.get(seriesIndex + 1);
}
/**
* Returns the number of items in the specified series.
*
* @param seriesIndex the series (zero-based index).
*
* @return The itemCount value
*
* @see XYDataset
*/
public int getItemCount(int seriesIndex) {
return this.rows.size();
}
/**
* Returns the number of items in all series. This method is defined by
* the {@link TableXYDataset} interface.
*
* @return The item count.
*/
public int getItemCount() {
return getItemCount(0);
}
/**
* Returns the number of series in the dataset.
*
* @return The seriesCount value
*
* @see XYDataset
* @see Dataset
*/
public int getSeriesCount() {
return this.columnNames.length;
}
/**
* Returns the key for the specified series.
*
* @param seriesIndex the series (zero-based index).
*
* @return The seriesName value
*
* @see XYDataset
* @see Dataset
*/
public Comparable getSeriesKey(int seriesIndex) {
if ((seriesIndex < this.columnNames.length)
&& (this.columnNames[seriesIndex] != null)) {
return this.columnNames[seriesIndex];
}
else {
return "";
}
}
/**
* Returns the number of items that should be displayed in the legend.
*
* @return The legendItemCount value
*
* @deprecated This method is not used in JFreeChart 1.0.x (it was left in
* the API by mistake and is officially deprecated from version 1.0.3
* onwards).
*/
public int getLegendItemCount() {
return getSeriesCount();
}
/**
* Returns the legend item labels.
*
* @return The legend item labels.
*
* @deprecated This method is not used in JFreeChart 1.0.x (it was left in
* the API by mistake and is officially deprecated from version 1.0.3
* onwards).
*/
public String[] getLegendItemLabels() {
return this.columnNames;
}
/**
* Close the database connection
*/
public void close() {
try {
this.connection.close();
}
catch (Exception e) {
System.err.println("JdbcXYDataset: swallowing exception.");
}
}
/**
* Returns the minimum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The minimum value.
*/
public double getRangeLowerBound(boolean includeInterval) {
return this.minValue;
}
/**
* Returns the maximum y-value in the dataset.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The maximum value.
*/
public double getRangeUpperBound(boolean includeInterval) {
return this.maxValue;
}
/**
* Returns the range of the values in this dataset's range.
*
* @param includeInterval a flag that determines whether or not the
* y-interval is taken into account.
*
* @return The range.
*/
public Range getRangeBounds(boolean includeInterval) {
return new Range(this.minValue, this.maxValue);
}
}
| Fixed FindBugs warnings.
git-svn-id: ca96c60061366ac92493e2142a352bb838ea8caa@2082 4df5dd95-b682-48b0-b31b-748e37b65e73
| source/org/jfree/data/jdbc/JDBCXYDataset.java | Fixed FindBugs warnings. |
|
Java | unlicense | 29bca26177a22e5ebfdb81fd7f8580229556ac38 | 0 | charlesmadere/smash-ranks-android | package com.garpr.android.preferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public interface Preference<T> {
void addListener(@NonNull final OnPreferenceChangeListener<T> listener);
void delete();
void delete(final boolean notifyListeners);
boolean exists();
@Nullable
T get();
String getDefaultValue();
String getKey();
String getName();
void removeListener(@NonNull final OnPreferenceChangeListener<T> listener);
void set(@Nullable final T newValue);
void set(@Nullable final T newValue, final boolean notifyListeners);
void set(@NonNull final Preference<T> preference);
void set(@NonNull final Preference<T> preference, final boolean notifyListeners);
interface OnPreferenceChangeListener<T> {
void onPreferenceChange(final Preference<T> preference);
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/preferences/Preference.java | package com.garpr.android.preferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public interface Preference<T> {
interface OnPreferenceChangeListener<T> {
void onPreferenceChange(final Preference<T> preference);
}
void addListener(@NonNull final OnPreferenceChangeListener<T> listener);
void delete();
void delete(final boolean notifyListeners);
boolean exists();
@Nullable
T get();
String getDefaultValue();
String getKey();
String getName();
void removeListener(@NonNull final OnPreferenceChangeListener<T> listener);
void set(@Nullable final T newValue);
void set(@Nullable final T newValue, final boolean notifyListeners);
void set(@NonNull final Preference<T> preference);
void set(@NonNull final Preference<T> preference, final boolean notifyListeners);
}
| tiny cleanup
| smash-ranks-android/app/src/main/java/com/garpr/android/preferences/Preference.java | tiny cleanup |
|
Java | unlicense | 9d7468a802058c75c60c07a2bf0d9a83af59f5b9 | 0 | gvlfm78/BukkitOldCombatMechanics | package kernitus.plugin.OldCombatMechanics.module;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import kernitus.plugin.OldCombatMechanics.OCMMain;
import kernitus.plugin.OldCombatMechanics.utilities.ItemUtils;
/**
* Created by Rayzr522 on 7/4/16.
*/
public class ModuleSwordBlocking extends Module {
private static ModuleSwordBlocking INSTANCE;
private static final ItemStack SHIELD = ItemUtils.makeItem("shield");
private HashMap<UUID, ItemStack> storedOffhandItems = new HashMap<UUID, ItemStack>();
public ModuleSwordBlocking(OCMMain plugin) {
super(plugin, "sword-blocking");
INSTANCE = this;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onRightClick(PlayerInteractEvent e) {
if (!e.getAction().toString().startsWith("RIGHT_CLICK")) {
return;
}
if (e.getItem() == null) {
return;
}
Player p = e.getPlayer();
World world = p.getWorld();
if (!isEnabled(world)) {
return;
}
UUID id = p.getUniqueId();
if (isBlocking(id)) return;
ItemStack item = e.getItem();
if (!isHolding(item.getType(), "sword") || hasShield(p)) return;
PlayerInventory inv = p.getInventory();
storedOffhandItems.put(id, inv.getItemInOffHand());
inv.setItemInOffHand(SHIELD);
scheduleRestore(p);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onProjectileHit(EntityDamageByEntityEvent e){
//TODO Check if projectile had explosive or fire damage and apply it
DamageCause cause = e.getCause();
Entity ent = e.getEntity();
Entity damager = e.getDamager();
if(ent != null && ent instanceof Player){
Player p = (Player) ent;
//Checks for arrows, fireballs, snowballs
if(cause.equals(DamageCause.PROJECTILE) || (cause.equals(DamageCause.ENTITY_EXPLOSION) && damager instanceof Fireball) ){
//Checking if an arrow hit the player while they were blocking
//and reduce damage by 1/2 a heart instead of completely blocking it
//This would make sure if they blocked direct damage from the projectile it gets applied with a 1/2 heart reduction
if(isBlocking(p.getUniqueId())){
double damageReduction = e.getDamage(); //This would mean blocking all damage
if((damageReduction - 1) >= 0)
damageReduction = -1;
//Reduce the damage by 1/2 a heart if it doesn't result in the damage being negative
//Otherwise reduce damage entirely
e.setDamage(DamageModifier.BLOCKING, damageReduction);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onWorldChange(PlayerChangedWorldEvent e) {
restore(e.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogout(PlayerQuitEvent e) {
restore(e.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent e) {
if (!isBlocking(e.getEntity().getUniqueId())) return;
Player p = e.getEntity();
UUID id = p.getUniqueId();
e.getDrops().remove(SHIELD);
e.getDrops().add(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent e){
Player p = e.getPlayer();
if (isBlocking(p.getUniqueId()))
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent e){
if(e.getWhoClicked() instanceof Player){
Player p = (Player) e.getWhoClicked();
if (isBlocking(p.getUniqueId())){
if(e.getCursor().getType().equals(Material.SHIELD) || e.getCurrentItem().getType().equals(Material.SHIELD)){
e.setCancelled(true);
restore(p);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemDrop(PlayerDropItemEvent e){
Item is = e.getItemDrop();
Player p = e.getPlayer();
if (isBlocking(p.getUniqueId())){
if(is.getType().equals(Material.SHIELD)){
e.setCancelled(true);
restore(p);
}
}
}
private void scheduleRestore(final Player p) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
restore(p);
}
}, 60);
}
private void restore(Player p) {
UUID id = p.getUniqueId();
if (!isBlocking(id)) {
return;
}
p.getInventory().setItemInOffHand(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
public static void RestoreAll() {
INSTANCE.restoreAll();
}
public void restoreAll() {
for (Map.Entry<UUID, ItemStack> entry : storedOffhandItems.entrySet()) {
UUID id = entry.getKey();
Player p = Bukkit.getPlayer(id);
p.getInventory().setItemInOffHand(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
}
private boolean isBlocking(UUID uuid){
return storedOffhandItems.containsKey(uuid);
}
private boolean hasShield(Player p) {
return p.getInventory().getItemInOffHand().getType() == Material.SHIELD;
}
private boolean isHolding(Material mat, String type) {
return mat.toString().endsWith("_" + type.toUpperCase());
}
}
| src/main/java/gvlfm78/plugin/OldCombatMechanics/module/ModuleSwordBlocking.java | package kernitus.plugin.OldCombatMechanics.module;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerSwapHandItemsEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import kernitus.plugin.OldCombatMechanics.OCMMain;
import kernitus.plugin.OldCombatMechanics.utilities.ItemUtils;
/**
* Created by Rayzr522 on 7/4/16.
*/
public class ModuleSwordBlocking extends Module {
private static ModuleSwordBlocking INSTANCE;
private static final ItemStack SHIELD = ItemUtils.makeItem("shield");
private HashMap<UUID, ItemStack> storedOffhandItems = new HashMap<UUID, ItemStack>();
public ModuleSwordBlocking(OCMMain plugin) {
super(plugin, "sword-blocking");
INSTANCE = this;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onRightClick(PlayerInteractEvent e) {
if (!e.getAction().toString().startsWith("RIGHT_CLICK")) {
return;
}
if (e.getItem() == null) {
return;
}
Player p = e.getPlayer();
World world = p.getWorld();
if (!isEnabled(world)) {
return;
}
UUID id = p.getUniqueId();
if (isBlocking(id)) return;
ItemStack item = e.getItem();
if (!isHolding(item.getType(), "sword") || hasShield(p)) return;
PlayerInventory inv = p.getInventory();
storedOffhandItems.put(id, inv.getItemInOffHand());
inv.setItemInOffHand(SHIELD);
scheduleRestore(p);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onProjectileHit(EntityDamageByEntityEvent e){
//TODO Check if projectile had explosive or fire damage and apply it
DamageCause cause = e.getCause();
if(cause.equals(DamageCause.PROJECTILE)){ //Hit by a projectile
//Checking if an arrow hit the player while they were blocking
//and reduce damage by 1/2 a heart instead of completely blocking it
Entity ent = e.getEntity();
if(ent != null && ent instanceof Player){
Player p = (Player) ent;
if(isBlocking(p.getUniqueId())){
double damageReduction = e.getDamage(); //This would mean blocking all damage
if((damageReduction - 1) >= 0)
damageReduction = -1;
//Reduce the damage by 1/2 a heart if it doesn't result in the damage being negative
//Otherwise reduce damage entirely
e.setDamage(DamageModifier.BLOCKING, damageReduction);
}
}
}
if(cause.equals(DamageCause.ENTITY_EXPLOSION)){
}
}
/*@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDamaged(EntityDamageEvent e){
Entity entity = e.getEntity();
if(isBlocking(entity.getUniqueId())){
Player p = (Player) e.getEntity();
debug("Damage: "+e.getDamage()+" final: "+e.getFinalDamage(), p);
//Check if they are holding a shield
if(p.getInventory().getItemInOffHand().getType().equals(Material.SHIELD)){
double damage = (e.getDamage()/0.33D)-1;
if(damage < 0) damage = 0;
e.setDamage(damage);
}
}
}*/
@EventHandler(priority = EventPriority.HIGHEST)
public void onWorldChange(PlayerChangedWorldEvent e) {
restore(e.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerLogout(PlayerQuitEvent e) {
restore(e.getPlayer());
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDeathEvent e) {
if (!isBlocking(e.getEntity().getUniqueId())) return;
Player p = e.getEntity();
UUID id = p.getUniqueId();
e.getDrops().remove(SHIELD);
e.getDrops().add(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerSwapHandItems(PlayerSwapHandItemsEvent e){
Player p = e.getPlayer();
if (isBlocking(p.getUniqueId()))
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent e){
if(e.getWhoClicked() instanceof Player){
Player p = (Player) e.getWhoClicked();
if (isBlocking(p.getUniqueId())){
if(e.getCursor().getType().equals(Material.SHIELD) || e.getCurrentItem().getType().equals(Material.SHIELD)){
e.setCancelled(true);
restore(p);
}
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onItemDrop(PlayerDropItemEvent e){
Item is = e.getItemDrop();
Player p = e.getPlayer();
if (isBlocking(p.getUniqueId())){
if(is.getType().equals(Material.SHIELD)){
e.setCancelled(true);
restore(p);
}
}
}
private void scheduleRestore(final Player p) {
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
public void run() {
restore(p);
}
}, 60);
}
private void restore(Player p) {
UUID id = p.getUniqueId();
if (!isBlocking(id)) {
return;
}
p.getInventory().setItemInOffHand(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
public static void RestoreAll() {
INSTANCE.restoreAll();
}
public void restoreAll() {
for (Map.Entry<UUID, ItemStack> entry : storedOffhandItems.entrySet()) {
UUID id = entry.getKey();
Player p = Bukkit.getPlayer(id);
p.getInventory().setItemInOffHand(storedOffhandItems.get(id));
storedOffhandItems.remove(id);
}
}
private boolean isBlocking(UUID uuid){
return storedOffhandItems.containsKey(uuid);
}
private boolean hasShield(Player p) {
return p.getInventory().getItemInOffHand().getType() == Material.SHIELD;
}
private boolean isHolding(Material mat, String type) {
return mat.toString().endsWith("_" + type.toUpperCase());
}
}
| Adding correct shield damage reduction values | src/main/java/gvlfm78/plugin/OldCombatMechanics/module/ModuleSwordBlocking.java | Adding correct shield damage reduction values |
|
Java | apache-2.0 | 3ebef5f774e0b36e2d90a1b18d3f9524f2d5d3bf | 0 | wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel | /*
* Copyright 2006 Wyona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.wyona.org/licenses/APACHE-LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wyona.yanel.core.navigation;
/**
* Also see org.w3c.dom.Node
*/
public interface Node {
/**
* @return new child
*/
public Node insertAsFirstChild(Node child);
/**
* @return new child
*/
public Node insertBeforeChild(Node newChild, Node refChild);
/**
* @return new child
*/
public Node insertAfterChild(Node newChild, Node refChild);
/**
* @return new child
*/
public Node appendChild(Node child);
/**
*/
public void removeChild(Node child);
/**
*
*/
public boolean isResource();
/**
*
*/
public boolean isCollection();
/**
*
*/
public Node[] getChildren();
/**
*
*/
public Node getParent();
/**
*
*/
public Node getNextSibling();
/**
*
*/
public Node getPreviousSibling();
/**
*
*/
public String getPath();
/**
*
*/
public String getName();
}
| src/core/java/org/wyona/yanel/core/navigation/Node.java | /*
* Copyright 2006 Wyona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.wyona.org/licenses/APACHE-LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wyona.yanel.core.navigation;
import org.wyona.yanel.core.Path;
/**
* Also see org.w3c.dom.Node
*/
public interface Node {
/**
* @return new child
*/
public Node insertAsFirstChild(Node child);
/**
* @return new child
*/
public Node insertBeforeChild(Node newChild, Node refChild);
/**
* @return new child
*/
public Node insertAfterChild(Node newChild, Node refChild);
/**
* @return new child
*/
public Node appendChild(Node child);
/**
*/
public void removeChild(Node child);
/**
*
*/
public boolean isResource();
/**
*
*/
public boolean isCollection();
/**
*
*/
public Node[] getChildren();
/**
*
*/
public Node getParent();
/**
*
*/
public Node getNextSibling();
/**
*
*/
public Node getPreviousSibling();
/**
*
*/
public String getPath();
/**
*
*/
public String getName();
}
| obsolete import removed
| src/core/java/org/wyona/yanel/core/navigation/Node.java | obsolete import removed |
|
Java | apache-2.0 | 0dd367230b03c3a7f12869437137fc793b73a139 | 0 | openpreserve/scape-fcrepo4-connector | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package eu.scape_project.web.listener;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFactory;
import javax.jcr.nodetype.NodeTypeDefinition;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.NodeTypeTemplate;
import javax.jcr.nodetype.PropertyDefinitionTemplate;
import javax.ws.rs.ext.Provider;
import org.fcrepo.http.commons.session.SessionFactory;
import org.fcrepo.kernel.RdfLexicon;
import org.fcrepo.kernel.services.NodeService;
import org.fcrepo.kernel.services.ObjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.update.UpdateAction;
import com.sun.jersey.api.model.AbstractResourceModelContext;
import com.sun.jersey.api.model.AbstractResourceModelListener;
import eu.scape_project.rdf.ScapeRDFVocabulary;
import eu.scape_project.service.ConnectorService;
/**
* A JAX-RS Provider which initializes the webapp
* @author frank asseg
*
*/
@Component
@Provider
public class ScapeInitializer implements AbstractResourceModelListener {
private static final Logger LOG = LoggerFactory
.getLogger(ScapeInitializer.class);
@Autowired
private NodeService nodeService;
@Autowired
private ObjectService objectService;
@Autowired
private SessionFactory sessionFactory;
/*
* (non-Javadoc)
* @see
* com.sun.jersey.api.model.AbstractResourceModelListener#onLoaded(com.sun
* .jersey.api.model.AbstractResourceModelContext)
*/
@Override
public void onLoaded(AbstractResourceModelContext modelContext) {
try {
final Session session = this.sessionFactory.getInternalSession();
/* make sure that the scape namespace is available in fcrepo */
final Dataset namespace =
this.nodeService.getNamespaceRegistryGraph(session);
UpdateAction.parseExecute(
"INSERT {<" + ScapeRDFVocabulary.SCAPE_NAMESPACE + "> <" +
RdfLexicon.HAS_NAMESPACE_PREFIX +
"> \"scape\"} WHERE {}", namespace);
/* make sure that the queue object exists for async ingests */
this.objectService.createObject(session,
ConnectorService.QUEUE_NODE);
session.save();
/* add the scape node mixin types */
// Get the node type manager ...
final NodeTypeManager mgr =
session.getWorkspace().getNodeTypeManager();
// Create templates for the node types ...
final NodeTypeTemplate entityType = mgr.createNodeTypeTemplate();
entityType.setName("scape:intellectual-entity");
entityType.setDeclaredSuperTypeNames(new String[] {
"fedora:resource", "fedora:object"});
entityType.setMixin(true);
entityType.setQueryable(true);
entityType.setAbstract(false);
entityType.getPropertyDefinitionTemplates().add(createMultiPropertyDefTemplate(session, mgr, "scape:hasRepresentation"));
entityType.getPropertyDefinitionTemplates().add(createMultiPropertyDefTemplate(session, mgr, "scape:hasVersion"));
final NodeTypeTemplate repType = mgr.createNodeTypeTemplate();
repType.setName("scape:representation");
repType.setDeclaredSuperTypeNames(new String[] {"fedora:resource", "fedora:object"});
repType.setMixin(true);
repType.setQueryable(true);
repType.setAbstract(false);
final NodeTypeTemplate fileType = mgr.createNodeTypeTemplate();
fileType.setName("scape:file");
fileType.setDeclaredSuperTypeNames(new String[] {"fedora:resource",
"fedora:object"});
fileType.setMixin(true);
fileType.setQueryable(true);
fileType.setAbstract(false);
// and register them
mgr.registerNodeTypes(new NodeTypeDefinition[] {fileType,
entityType, repType}, true);
} catch (RepositoryException e) {
LOG.error("Error while setting up scape connector api", e);
throw new RuntimeException("Unable to setup scape on fedora");
}
}
private PropertyDefinitionTemplate createMultiPropertyDefTemplate(final Session session, final NodeTypeManager mgr, final String name) throws UnsupportedRepositoryOperationException, RepositoryException {
PropertyDefinitionTemplate propDefn = mgr.createPropertyDefinitionTemplate();
propDefn.setName(name);
propDefn.setRequiredType(PropertyType.STRING);
ValueFactory valueFactory = session.getValueFactory();
propDefn.setMultiple(true);
propDefn.setFullTextSearchable(false);
propDefn.setQueryOrderable(false);
return propDefn;
}
}
| src/main/java/eu/scape_project/web/listener/ScapeInitializer.java | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package eu.scape_project.web.listener;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ValueFactory;
import javax.jcr.nodetype.NodeTypeDefinition;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.NodeTypeTemplate;
import javax.jcr.nodetype.PropertyDefinitionTemplate;
import javax.ws.rs.ext.Provider;
import org.fcrepo.http.commons.session.SessionFactory;
import org.fcrepo.kernel.RdfLexicon;
import org.fcrepo.kernel.services.NodeService;
import org.fcrepo.kernel.services.ObjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.update.UpdateAction;
import com.sun.jersey.api.model.AbstractResourceModelContext;
import com.sun.jersey.api.model.AbstractResourceModelListener;
import eu.scape_project.rdf.ScapeRDFVocabulary;
import eu.scape_project.service.ConnectorService;
/**
* A JAX-RS Provider which initializes the webapp
* @author frank asseg
*
*/
@Component
@Provider
public class ScapeInitializer implements AbstractResourceModelListener {
private static final Logger LOG = LoggerFactory
.getLogger(ScapeInitializer.class);
@Autowired
private NodeService nodeService;
@Autowired
private ObjectService objectService;
@Autowired
private SessionFactory sessionFactory;
/*
* (non-Javadoc)
* @see
* com.sun.jersey.api.model.AbstractResourceModelListener#onLoaded(com.sun
* .jersey.api.model.AbstractResourceModelContext)
*/
@Override
public void onLoaded(AbstractResourceModelContext modelContext) {
try {
final Session session = this.sessionFactory.getInternalSession();
/* make sure that the scape namespace is available in fcrepo */
final Dataset namespace =
this.nodeService.getNamespaceRegistryGraph(session);
UpdateAction.parseExecute(
"INSERT {<" + ScapeRDFVocabulary.SCAPE_NAMESPACE + "> <" +
RdfLexicon.HAS_NAMESPACE_PREFIX +
"> \"scape\"} WHERE {}", namespace);
/* make sure that the queue object exists for async ingests */
this.objectService.createObject(session,
ConnectorService.QUEUE_NODE);
session.save();
/* add the scape node mixin types */
// Get the node type manager ...
final NodeTypeManager mgr =
session.getWorkspace().getNodeTypeManager();
// Create templates for the node types ...
final NodeTypeTemplate entityType = mgr.createNodeTypeTemplate();
entityType.setName("scape:intellectual-entity");
entityType.setDeclaredSuperTypeNames(new String[] {
"fedora:resource", "fedora:object"});
entityType.setMixin(true);
entityType.setQueryable(true);
entityType.setAbstract(false);
entityType.getPropertyDefinitionTemplates().add(createPropertyDefTemplate(session, mgr));
final NodeTypeTemplate repType = mgr.createNodeTypeTemplate();
repType.setName("scape:representation");
repType.setDeclaredSuperTypeNames(new String[] {"fedora:resource", "fedora:object"});
repType.setMixin(true);
repType.setQueryable(true);
repType.setAbstract(false);
final NodeTypeTemplate fileType = mgr.createNodeTypeTemplate();
fileType.setName("scape:file");
fileType.setDeclaredSuperTypeNames(new String[] {"fedora:resource",
"fedora:object"});
fileType.setMixin(true);
fileType.setQueryable(true);
fileType.setAbstract(false);
// and register them
mgr.registerNodeTypes(new NodeTypeDefinition[] {fileType,
entityType, repType}, true);
} catch (RepositoryException e) {
LOG.error("Error while setting up scape connector api", e);
throw new RuntimeException("Unable to setup scape on fedora");
}
}
private PropertyDefinitionTemplate createPropertyDefTemplate(final Session session, final NodeTypeManager mgr) throws UnsupportedRepositoryOperationException, RepositoryException {
PropertyDefinitionTemplate propDefn = mgr.createPropertyDefinitionTemplate();
propDefn.setName("scape:hasRepresentation");
propDefn.setRequiredType(PropertyType.STRING);
ValueFactory valueFactory = session.getValueFactory();
propDefn.setMultiple(true);
propDefn.setFullTextSearchable(false);
propDefn.setQueryOrderable(false);
return propDefn;
}
}
| fixed last failing test, by adding a property def template for hasversion
| src/main/java/eu/scape_project/web/listener/ScapeInitializer.java | fixed last failing test, by adding a property def template for hasversion |
|
Java | apache-2.0 | f6c982c0eed0e8613aa31d14f8dd0f33917d143e | 0 | evilmucedin/sweble-wikitext,harshal/sweble-wikitext,harshal/sweble-wikitext,evilmucedin/sweble-wikitext,evilmucedin/sweble-wikitext,pumpadump/sweble-wikitext,pumpadump/sweble-wikitext,harshal/sweble-wikitext,pumpadump/sweble-wikitext | /**
* Copyright 2011 The Open Source Research Group,
* University of Erlangen-Nürnberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sweble.wikitext.engine;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.sweble.wikitext.engine.config.WikiConfigurationInterface;
import org.sweble.wikitext.engine.log.CompilerLog;
import org.sweble.wikitext.engine.log.ParseException;
import org.sweble.wikitext.engine.log.ParserLog;
import org.sweble.wikitext.engine.log.PostprocessorLog;
import org.sweble.wikitext.engine.log.PpResolverLog;
import org.sweble.wikitext.engine.log.PreprocessorLog;
import org.sweble.wikitext.engine.log.UnhandledException;
import org.sweble.wikitext.engine.log.ValidatorLog;
import org.sweble.wikitext.lazy.LazyEncodingValidator;
import org.sweble.wikitext.lazy.LazyParser;
import org.sweble.wikitext.lazy.LazyPostprocessor;
import org.sweble.wikitext.lazy.LazyPreprocessor;
import org.sweble.wikitext.lazy.parser.LazyParsedPage;
import org.sweble.wikitext.lazy.parser.PreprocessorToParserTransformer;
import org.sweble.wikitext.lazy.preprocessor.LazyPreprocessedPage;
import org.sweble.wikitext.lazy.preprocessor.PreprocessedWikitext;
import de.fau.cs.osr.ptk.common.EntityMap;
import de.fau.cs.osr.ptk.common.ast.AstNode;
import de.fau.cs.osr.ptk.common.ast.ContentNode;
import de.fau.cs.osr.utils.StopWatch;
public class Compiler
{
private static final Logger logger = Logger.getLogger(Compiler.class);
// =========================================================================
private WikiConfigurationInterface wikiConfig;
// =========================================================================
public Compiler(WikiConfigurationInterface wikiConfig)
{
super();
this.wikiConfig = wikiConfig;
}
public WikiConfigurationInterface getWikiConfig()
{
return wikiConfig;
}
// =========================================================================
/**
* Takes wikitext and preprocesses the wikitext (without performing
* expansion). The following steps are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for inclusion/viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* </ul>
*/
public CompiledPage preprocess(
PageId pageId,
String wikitext,
boolean forInclusion,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, forInclusion, entityMap, log);
pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
/**
* Takes wikitext and expands the wikitext. The following steps are
* performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Expansion</li>
* </ul>
*/
public CompiledPage expand(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null || callback == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = pprAst;
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
/**
* Takes wikitext and parses the wikitext for viewing. The following steps
* are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* <li>Parsing</li>
* <li>Entity substitution</li>
* </ul>
*/
public CompiledPage parse(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyParsedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = parse(title, pprAst, entityMap, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
/**
* Takes wikitext and parses the wikitext for viewing. The following steps
* are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* <li>Parsing</li>
* <li>Entity substitution</li>
* <li>Postprocessing</li>
* </ul>
*/
public CompiledPage postprocess(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyParsedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = parse(title, pprAst, entityMap, log);
pAst = postprocess(title, pAst, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
/**
* Takes an AST after preprocessing or after expansion and performs the
* following steps:
* <ul>
* <li>Parsing</li>
* <li>Entity substitution</li>
* <li>Postprocessing</li>
* </ul>
*/
public CompiledPage postprocessPpOrExpAst(
PageId pageId,
LazyPreprocessedPage pprAst,
EntityMap entityMap)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyParsedPage pAst;
try
{
pAst = parse(title, pprAst, entityMap, log);
pAst = postprocess(title, pAst, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
// =========================================================================
/**
* This function is only called by preprocessor frames to pull in pages for
* transclusion or redirection. It takes wikitext and parses the wikitext
* for inclusion or viewing. The following steps are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for inclusion/viewing)</li>
* <li>Entity substitution</li>
* <li>Expansion</li>
* </ul>
*/
protected CompiledPage preprocessAndExpand(
ExpansionCallback callback,
PageId pageId,
String wikitext,
boolean forInclusion,
EntityMap entityMap,
Map<String, AstNode> arguments,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
if (wikitext == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, forInclusion, entityMap, log);
pprAst = expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
protected CompiledPage expand(
ExpansionCallback callback,
PageId pageId,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
boolean forInclusion,
Map<String, AstNode> arguments,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
if (ppAst == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
pprAst = expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
// =========================================================================
/**
* Validates wikitext.
*/
private String validate(
PageTitle title,
String wikitext,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
ValidatorLog log = new ValidatorLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyEncodingValidator validator = new LazyEncodingValidator();
String validatedWikitext = validator.validate(
wikitext,
title.getFullTitle(),
entityMap);
return validatedWikitext;
}
catch (Throwable e)
{
logger.error("Validation failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Validation failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Preprocesses validated wikitext and substitutes entities.
*/
private LazyPreprocessedPage preprocess(
PageTitle title,
String validatedWikitext,
boolean forInclusion,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
PreprocessorLog log = new PreprocessorLog();
parentLog.getContent().add(log);
log.setForInclusion(forInclusion);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyPreprocessor preprocessor = new LazyPreprocessor(wikiConfig);
LazyPreprocessedPage preprocessedAst =
(LazyPreprocessedPage) preprocessor.parseArticle(
validatedWikitext,
title.getFullTitle(),
forInclusion);
return preprocessedAst;
}
catch (xtc.parser.ParseException e)
{
log.getContent().add(new ParseException(e.getMessage()));
throw new CompilerException("Preprocessing failed!", e);
}
catch (Throwable e)
{
logger.error("Preprocessing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Preprocessing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Starts the expansion process of a preprocessed page with the preprocessed
* page as root of the expansion process.
*/
private LazyPreprocessedPage expand(
ExpansionCallback callback,
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
LinkedHashMap<String, AstNode> arguments,
boolean forInclusion,
ContentNode parentLog)
throws CompilerException
{
return expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
null,
null,
parentLog);
}
/**
* Starts the expansion process of a preprocessed page.
*/
private LazyPreprocessedPage expand(
ExpansionCallback callback,
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
Map<String, AstNode> arguments,
boolean forInclusion,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame,
ContentNode parentLog)
throws CompilerException
{
PpResolverLog log = new PpResolverLog();
parentLog.getContent().add(log);
if (arguments == null)
arguments = new HashMap<String, AstNode>();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
ExpansionFrame frame;
if (rootFrame != null)
{
frame = new ExpansionFrame(
this,
callback,
title,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
ppAst.getWarnings(),
log);
}
else
{
frame = new ExpansionFrame(
this,
callback,
title,
entityMap,
ppAst.getWarnings(),
log);
}
LazyPreprocessedPage expanded =
(LazyPreprocessedPage) frame.expand(ppAst);
return expanded;
}
catch (Throwable e)
{
logger.error("Resolution failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Resolution failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Parses a preprocessed page and substitutes entities.
*/
private LazyParsedPage parse(
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
ParserLog log = new ParserLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
PreprocessedWikitext preprocessedWikitext =
PreprocessorToParserTransformer.transform(
ppAst,
entityMap,
true);
LazyParser parser = new LazyParser(wikiConfig);
LazyParsedPage parsedAst =
(LazyParsedPage) parser.parseArticle(
preprocessedWikitext,
title.getTitle());
parsedAst.getWarnings().addAll(ppAst.getWarnings());
return parsedAst;
}
catch (xtc.parser.ParseException e)
{
log.getContent().add(new ParseException(e.getMessage()));
throw new CompilerException("Parsing failed!", e);
}
catch (Throwable e)
{
logger.error("Parsing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Parsing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
private LazyParsedPage postprocess(
PageTitle title,
LazyParsedPage pAst,
CompilerLog parentLog)
throws CompilerException
{
PostprocessorLog log = new PostprocessorLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyPostprocessor lpp = new LazyPostprocessor(wikiConfig);
pAst = (LazyParsedPage) lpp.postprocess(pAst, title.getTitle());
return pAst;
}
catch (Throwable e)
{
logger.error("Postprocessing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Postprocessing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
}
| swc-engine/src/main/java/org/sweble/wikitext/engine/Compiler.java | /**
* Copyright 2011 The Open Source Research Group,
* University of Erlangen-Nürnberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sweble.wikitext.engine;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.sweble.wikitext.engine.config.WikiConfigurationInterface;
import org.sweble.wikitext.engine.log.CompilerLog;
import org.sweble.wikitext.engine.log.ParseException;
import org.sweble.wikitext.engine.log.ParserLog;
import org.sweble.wikitext.engine.log.PostprocessorLog;
import org.sweble.wikitext.engine.log.PpResolverLog;
import org.sweble.wikitext.engine.log.PreprocessorLog;
import org.sweble.wikitext.engine.log.UnhandledException;
import org.sweble.wikitext.engine.log.ValidatorLog;
import org.sweble.wikitext.lazy.LazyEncodingValidator;
import org.sweble.wikitext.lazy.LazyParser;
import org.sweble.wikitext.lazy.LazyPostprocessor;
import org.sweble.wikitext.lazy.LazyPreprocessor;
import org.sweble.wikitext.lazy.parser.LazyParsedPage;
import org.sweble.wikitext.lazy.parser.PreprocessorToParserTransformer;
import org.sweble.wikitext.lazy.preprocessor.LazyPreprocessedPage;
import org.sweble.wikitext.lazy.preprocessor.PreprocessedWikitext;
import de.fau.cs.osr.ptk.common.EntityMap;
import de.fau.cs.osr.ptk.common.ast.AstNode;
import de.fau.cs.osr.ptk.common.ast.ContentNode;
import de.fau.cs.osr.utils.StopWatch;
public class Compiler
{
private static final Logger logger = Logger.getLogger(Compiler.class);
// =========================================================================
private WikiConfigurationInterface wikiConfig;
// =========================================================================
public Compiler(WikiConfigurationInterface wikiConfig)
{
super();
this.wikiConfig = wikiConfig;
}
public WikiConfigurationInterface getWikiConfig()
{
return wikiConfig;
}
// =========================================================================
/**
* Takes wikitext and preprocesses the wikitext (without performing
* expansion). The following steps are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for inclusion/viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* </ul>
*/
public CompiledPage preprocess(
PageId pageId,
String wikitext,
boolean forInclusion,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, forInclusion, entityMap, log);
pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
/**
* Takes wikitext and expands the wikitext. The following steps are
* performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Expansion</li>
* </ul>
*/
public CompiledPage expand(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null || callback == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = pprAst;
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
/**
* Takes wikitext and parses the wikitext for viewing. The following steps
* are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* <li>Parsing</li>
* <li>Entity substitution</li>
* </ul>
*/
public CompiledPage parse(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyParsedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = parse(title, pprAst, entityMap, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
/**
* Takes wikitext and parses the wikitext for viewing. The following steps
* are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for viewing)</li>
* <li>Entity substitution</li>
* <li>Optional: Expansion</li>
* <li>Parsing</li>
* <li>Entity substitution</li>
* <li>Postprocessing</li>
* </ul>
*/
public CompiledPage postprocess(
PageId pageId,
String wikitext,
ExpansionCallback callback)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyParsedPage pAst;
try
{
EntityMap entityMap = new EntityMap();
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, false, entityMap, log);
LazyPreprocessedPage pprAst = ppAst;
if (callback != null)
pprAst = expand(callback, title, ppAst, entityMap, null, false, log);
pAst = parse(title, pprAst, entityMap, log);
pAst = postprocess(title, pAst, log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pAst.getContent()),
pAst.getWarnings(),
log);
}
// =========================================================================
/**
* This function is only called by preprocessor frames to pull in pages for
* transclusion or redirection. It takes wikitext and parses the wikitext
* for inclusion or viewing. The following steps are performed:
* <ul>
* <li>Validation</li>
* <li>Preprocessing (for inclusion/viewing)</li>
* <li>Entity substitution</li>
* <li>Expansion</li>
* </ul>
*/
protected CompiledPage preprocessAndExpand(
ExpansionCallback callback,
PageId pageId,
String wikitext,
boolean forInclusion,
EntityMap entityMap,
Map<String, AstNode> arguments,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
if (wikitext == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
String validatedWikitext =
validate(title, wikitext, entityMap, log);
LazyPreprocessedPage ppAst =
preprocess(title, validatedWikitext, forInclusion, entityMap, log);
pprAst = expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
protected CompiledPage expand(
ExpansionCallback callback,
PageId pageId,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
boolean forInclusion,
Map<String, AstNode> arguments,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame)
throws CompilerException
{
if (pageId == null)
throw new NullPointerException();
if (ppAst == null)
throw new NullPointerException();
PageTitle title = pageId.getTitle();
CompilerLog log = new CompilerLog();
log.setTitle(title.getFullTitle());
log.setRevision(pageId.getRevision());
LazyPreprocessedPage pprAst;
try
{
pprAst = expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
log);
}
catch (CompilerException e)
{
e.attachLog(log);
throw e;
}
catch (Throwable e)
{
throw new CompilerException("Compilation failed!", e, log);
}
return new CompiledPage(
new Page(pprAst.getContent()),
pprAst.getWarnings(),
log);
}
// =========================================================================
/**
* Validates wikitext.
*/
private String validate(
PageTitle title,
String wikitext,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
ValidatorLog log = new ValidatorLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyEncodingValidator validator = new LazyEncodingValidator();
String validatedWikitext = validator.validate(
wikitext,
title.getFullTitle(),
entityMap);
return validatedWikitext;
}
catch (Throwable e)
{
logger.error("Validation failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Validation failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Preprocesses validated wikitext and substitutes entities.
*/
private LazyPreprocessedPage preprocess(
PageTitle title,
String validatedWikitext,
boolean forInclusion,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
PreprocessorLog log = new PreprocessorLog();
parentLog.getContent().add(log);
log.setForInclusion(forInclusion);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyPreprocessor preprocessor = new LazyPreprocessor(wikiConfig);
LazyPreprocessedPage preprocessedAst =
(LazyPreprocessedPage) preprocessor.parseArticle(
validatedWikitext,
title.getFullTitle(),
forInclusion);
return preprocessedAst;
}
catch (xtc.parser.ParseException e)
{
log.getContent().add(new ParseException(e.getMessage()));
throw new CompilerException("Preprocessing failed!", e);
}
catch (Throwable e)
{
logger.error("Preprocessing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Preprocessing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Starts the expansion process of a preprocessed page with the preprocessed
* page as root of the expansion process.
*/
private LazyPreprocessedPage expand(
ExpansionCallback callback,
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
LinkedHashMap<String, AstNode> arguments,
boolean forInclusion,
ContentNode parentLog)
throws CompilerException
{
return expand(
callback,
title,
ppAst,
entityMap,
arguments,
forInclusion,
null,
null,
parentLog);
}
/**
* Starts the expansion process of a preprocessed page.
*/
private LazyPreprocessedPage expand(
ExpansionCallback callback,
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
Map<String, AstNode> arguments,
boolean forInclusion,
ExpansionFrame rootFrame,
ExpansionFrame parentFrame,
ContentNode parentLog)
throws CompilerException
{
PpResolverLog log = new PpResolverLog();
parentLog.getContent().add(log);
if (arguments == null)
arguments = new HashMap<String, AstNode>();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
ExpansionFrame frame;
if (rootFrame != null)
{
frame = new ExpansionFrame(
this,
callback,
title,
entityMap,
arguments,
forInclusion,
rootFrame,
parentFrame,
ppAst.getWarnings(),
log);
}
else
{
frame = new ExpansionFrame(
this,
callback,
title,
entityMap,
ppAst.getWarnings(),
log);
}
LazyPreprocessedPage expanded =
(LazyPreprocessedPage) frame.expand(ppAst);
return expanded;
}
catch (Throwable e)
{
logger.error("Resolution failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Resolution failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
/**
* Parses a preprocessed page and substitutes entities.
*/
private LazyParsedPage parse(
PageTitle title,
LazyPreprocessedPage ppAst,
EntityMap entityMap,
ContentNode parentLog)
throws CompilerException
{
ParserLog log = new ParserLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
PreprocessedWikitext preprocessedWikitext =
PreprocessorToParserTransformer.transform(
ppAst,
entityMap,
true);
LazyParser parser = new LazyParser(wikiConfig);
LazyParsedPage parsedAst =
(LazyParsedPage) parser.parseArticle(
preprocessedWikitext,
title.getTitle());
parsedAst.getWarnings().addAll(ppAst.getWarnings());
return parsedAst;
}
catch (xtc.parser.ParseException e)
{
log.getContent().add(new ParseException(e.getMessage()));
throw new CompilerException("Parsing failed!", e);
}
catch (Throwable e)
{
logger.error("Parsing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Parsing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
private LazyParsedPage postprocess(
PageTitle title,
LazyParsedPage pAst,
CompilerLog parentLog)
throws CompilerException
{
PostprocessorLog log = new PostprocessorLog();
parentLog.getContent().add(log);
StopWatch stopWatch = new StopWatch();
stopWatch.start();
try
{
LazyPostprocessor lpp = new LazyPostprocessor(wikiConfig);
pAst = (LazyParsedPage) lpp.postprocess(pAst, title.getTitle());
return pAst;
}
catch (Throwable e)
{
logger.error("Postprocessing failed!", e);
StringWriter w = new StringWriter();
e.printStackTrace(new PrintWriter(w));
log.getContent().add(new UnhandledException(e, w.toString()));
throw new CompilerException("Postprocessing failed!", e);
}
finally
{
stopWatch.stop();
log.setTimeNeeded(stopWatch.getElapsedTime());
}
}
}
| Added Compiler.postprocessPpOrExpAst() which let's you continue with parsing after preprocessing or expansion
| swc-engine/src/main/java/org/sweble/wikitext/engine/Compiler.java | Added Compiler.postprocessPpOrExpAst() which let's you continue with parsing after preprocessing or expansion |
|
Java | apache-2.0 | 001891b8b329be8317c8c4bb6e46177440b2f60c | 0 | arquivo/functional-tests,arquivo/functional-tests | /**
* Copyright (C) 2011 Simao Fontes <[email protected]>
* Copyright (C) 2011 SAW Group - FCCN <[email protected]>
*
* 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 pt.fccn.arquivo.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import pt.fccn.arquivo.pages.IndexPage;
import pt.fccn.saw.selenium.WebDriverTestBaseParalell;
import pt.fccn.saw.selenium.Retry;
/**
* @author Hugo Viana
*
*/
public class UrlsearchTest extends WebDriverTestBaseParalell{
/**
* Tests an Url search
*/
public UrlsearchTest(String os, String version, String browser, String deviceName, String deviceOrientation) {
super(os, version, browser, deviceName, deviceOrientation);
}
String term = "fccn.pt";
String termPT = "fccn.PT";
@Test
@Retry
public void UrlsearchTest() {
System.out.print("Running UrlsearchTest. \n");
IndexPage index = new IndexPage(driver);
assertTrue("Problems when searching by URL, i.e: fccn.pt and fccn.PT are not the same",
index.searchbyURL(term,termPT));
}
}
| test/pt/fccn/arquivo/tests/UrlsearchTest.java | /**
* Copyright (C) 2011 Simao Fontes <[email protected]>
* Copyright (C) 2011 SAW Group - FCCN <[email protected]>
*
* 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 pt.fccn.arquivo.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import pt.fccn.arquivo.pages.IndexPage;
import pt.fccn.saw.selenium.WebDriverTestBaseParalell;
import pt.fccn.saw.selenium.Retry;
/**
* @author Hugo Viana
*
*/
public class UrlsearchTest extends WebDriverTestBaseParalell{
/**
* Tests an Url search
*/
public UrlsearchTest(String os, String version, String browser, String deviceName, String deviceOrientation) {
super(os, version, browser, deviceName, deviceOrientation);
}
String term = "fccn.pt";
String termPT = "fccn.PT";
@Test
@Retry
public void AdvancedTest() {
System.out.print("Running UrlsearchTest. \n");
IndexPage index = new IndexPage(driver);
assertTrue("Problems when searching by URL, i.e: fccn.pt and fccn.PT are not the same",
index.searchbyURL(term,termPT));
}
}
| fixing UrlsearchTest
| test/pt/fccn/arquivo/tests/UrlsearchTest.java | fixing UrlsearchTest |
|
Java | apache-2.0 | b53286c887fdd59b31e2059bf40a37fe475b388e | 0 | dbflute/dbflute-intro,dbflute/dbflute-intro,dbflute/dbflute-intro,dbflute/dbflute-intro,dbflute/dbflute-intro,dbflute/dbflute-intro,dbflute/dbflute-intro | package org.dbflute.intro.app.web.document.decomment;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.dbflute.intro.app.model.document.decomment.parts.DfDecoMapColumnPart;
import org.dbflute.intro.app.model.document.decomment.parts.DfDecoMapTablePart;
import org.lastaflute.web.validation.Required;
/**
* @author hakiba
* @author jflute
* @author cabos
*/
public class DecommentPickupResult {
// ===================================================================================
// Attribute
// =========
@Valid
@Required
public List<TablePart> tables;
// done hakiba move it under tables by jflute (2017/08/17)
// done hakiba validator annotation (Required only) by jflute (2017/08/17)
public static class TablePart {
@Required
public String tableName;
@Valid
@Required
public List<ColumnPart> columns;
public TablePart(DfDecoMapTablePart tablePart) {
this.tableName = tablePart.getTableName();
this.columns = tablePart.getColumns().stream().map(columnPart -> new ColumnPart(columnPart)).collect(Collectors.toList());
}
public static class ColumnPart {
@Required
public String columnName;
@Valid
@Required
public List<PropertyPart> properties;
public ColumnPart(DfDecoMapColumnPart columnPart) {
this.columnName = columnPart.getColumnName();
this.properties =
columnPart.getProperties().stream().map(property -> new PropertyPart(property)).collect(Collectors.toList());
}
// done hakiba PropertyPart by jflute (2017/08/17)
public static class PropertyPart {
@Required
public String decomment;
@Required
public String databaseComment;
@Required
public String previousWholeComment;
@Required
public Long commentVersion;
@Valid
@Required
public List<String> authorList;
public PropertyPart(DfDecoMapColumnPart.ColumnPropertyPart property) {
this.decomment = property.getDecomment();
this.databaseComment = property.getDatabaseComment();
this.previousWholeComment = property.getPreviousWholeComment();
this.commentVersion = property.getCommentVersion();
this.authorList = property.getAuthorList();
}
}
}
}
// ===================================================================================
// Constructor
// ===========
public DecommentPickupResult(List<DfDecoMapTablePart> tableParts) {
this.tables = tableParts.stream().map(tablePart -> new TablePart(tablePart)).collect(Collectors.toList());
}
}
| src/main/java/org/dbflute/intro/app/web/document/decomment/DecommentPickupResult.java | package org.dbflute.intro.app.web.document.decomment;
import java.util.List;
import java.util.stream.Collectors;
import org.dbflute.intro.app.model.document.decomment.parts.DfDecoMapColumnPart;
import org.dbflute.intro.app.model.document.decomment.parts.DfDecoMapTablePart;
import org.lastaflute.web.validation.Required;
/**
* @author hakiba
* @author jflute
*/
public class DecommentPickupResult {
// ===================================================================================
// Attribute
// =========
@Required
public List<TablePart> tables;
// done hakiba move it under tables by jflute (2017/08/17)
// done hakiba validator annotation (Required only) by jflute (2017/08/17)
public static class TablePart {
@Required
public String tableName;
@Required
public List<ColumnPart> columns;
public TablePart(DfDecoMapTablePart tablePart) {
this.tableName = tablePart.getTableName();
this.columns = tablePart.getColumns().stream().map(columnPart -> new ColumnPart(columnPart)).collect(Collectors.toList());
}
public static class ColumnPart {
@Required
public String columnName;
@Required
public List<PropertyPart> properties;
public ColumnPart(DfDecoMapColumnPart columnPart) {
this.columnName = columnPart.getColumnName();
this.properties =
columnPart.getProperties().stream().map(property -> new PropertyPart(property)).collect(Collectors.toList());
}
// done hakiba PropertyPart by jflute (2017/08/17)
public static class PropertyPart {
@Required
public String decomment;
@Required
public String databaseComment;
@Required
public String previousWholeComment;
@Required
public Long commentVersion;
@Required
public List<String> authorList;
public PropertyPart(DfDecoMapColumnPart.ColumnPropertyPart property) {
this.decomment = property.getDecomment();
this.databaseComment = property.getDatabaseComment();
this.previousWholeComment = property.getPreviousWholeComment();
this.commentVersion = property.getCommentVersion();
this.authorList = property.getAuthorList();
}
}
}
}
// ===================================================================================
// Constructor
// ===========
public DecommentPickupResult(List<DfDecoMapTablePart> tableParts) {
this.tables = tableParts.stream().map(tablePart -> new TablePart(tablePart)).collect(Collectors.toList());
}
}
| add "@Valid" to DecommentPickupResult's field
| src/main/java/org/dbflute/intro/app/web/document/decomment/DecommentPickupResult.java | add "@Valid" to DecommentPickupResult's field |
|
Java | apache-2.0 | 4b6e1cbe806eb88607fb955efa32eaa50e6aab43 | 0 | vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java,vam-google/google-cloud-java | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.core.InternalApi;
import com.google.api.gax.paging.Page;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import java.io.Serializable;
import java.util.Objects;
import javax.annotation.Nullable;
public class TableResult implements Page<FieldValueList>, Serializable {
private static final long serialVersionUID = -4831062717210349819L;
@Nullable private final Schema schema;
private final long totalRows;
private final Page<FieldValueList> pageNoSchema;
/**
* If {@code schema} is non-null, {@code TableResult} adds the schema to {@code FieldValueList}s
* when iterating through them. {@code pageNoSchema} must not be null.
*/
@InternalApi("Exposed for testing")
public TableResult(Schema schema, long totalRows, Page<FieldValueList> pageNoSchema) {
this.schema = schema;
this.totalRows = totalRows;
this.pageNoSchema = checkNotNull(pageNoSchema);
}
/** Returns the schema of the results. Null if the schema is not supplied. */
public Schema getSchema() {
return schema;
}
/**
* Returns the total number of rows in the complete result set, which can be more than the number
* of rows in the first page of results returned by {@link #getValues()}.
*/
public long getTotalRows() {
return totalRows;
}
@Override
public boolean hasNextPage() {
return pageNoSchema.hasNextPage();
}
@Override
public String getNextPageToken() {
return pageNoSchema.getNextPageToken();
}
@Override
public TableResult getNextPage() {
if (pageNoSchema.hasNextPage()) {
return new TableResult(schema, totalRows, pageNoSchema.getNextPage());
}
return null;
}
@Override
public Iterable<FieldValueList> iterateAll() {
return addSchema(pageNoSchema.iterateAll());
}
@Override
public Iterable<FieldValueList> getValues() {
return addSchema(pageNoSchema.getValues());
}
private Iterable<FieldValueList> addSchema(Iterable<FieldValueList> iter) {
if (schema == null) {
return iter;
}
return Iterables.transform(
iter,
new Function<FieldValueList, FieldValueList>() {
@Override
public FieldValueList apply(FieldValueList list) {
return list.withSchema(schema.getFields());
}
});
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("rows", getValues())
.add("schema", schema)
.add("totalRows", totalRows)
.add("cursor", getNextPageToken())
.toString();
}
@Override
public final int hashCode() {
return Objects.hash(pageNoSchema, schema, totalRows);
}
@Override
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !obj.getClass().equals(TableResult.class)) {
return false;
}
TableResult response = (TableResult) obj;
return Objects.equals(getNextPageToken(), response.getNextPageToken())
&& Iterators.elementsEqual(getValues().iterator(), response.getValues().iterator())
&& Objects.equals(schema, response.schema)
&& totalRows == response.totalRows;
}
}
| google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableResult.java | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.gax.paging.Page;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import java.io.Serializable;
import java.util.Objects;
import javax.annotation.Nullable;
public class TableResult implements Page<FieldValueList>, Serializable {
private static final long serialVersionUID = -4831062717210349819L;
@Nullable private final Schema schema;
private final long totalRows;
private final Page<FieldValueList> pageNoSchema;
TableResult(Schema schema, long totalRows, Page<FieldValueList> pageNoSchema) {
this.schema = schema;
this.totalRows = totalRows;
this.pageNoSchema = checkNotNull(pageNoSchema);
}
/** Returns the schema of the results. Null if the schema is not supplied. */
public Schema getSchema() {
return schema;
}
/**
* Returns the total number of rows in the complete result set, which can be more than the number
* of rows in the first page of results returned by {@link #getValues()}.
*/
public long getTotalRows() {
return totalRows;
}
@Override
public boolean hasNextPage() {
return pageNoSchema.hasNextPage();
}
@Override
public String getNextPageToken() {
return pageNoSchema.getNextPageToken();
}
@Override
public TableResult getNextPage() {
if (pageNoSchema.hasNextPage()) {
return new TableResult(schema, totalRows, pageNoSchema.getNextPage());
}
return null;
}
@Override
public Iterable<FieldValueList> iterateAll() {
return addSchema(pageNoSchema.iterateAll());
}
@Override
public Iterable<FieldValueList> getValues() {
return addSchema(pageNoSchema.getValues());
}
private Iterable<FieldValueList> addSchema(Iterable<FieldValueList> iter) {
if (schema == null) {
return iter;
}
return Iterables.transform(
iter,
new Function<FieldValueList, FieldValueList>() {
@Override
public FieldValueList apply(FieldValueList list) {
return list.withSchema(schema.getFields());
}
});
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("rows", getValues())
.add("schema", schema)
.add("totalRows", totalRows)
.add("cursor", getNextPageToken())
.toString();
}
@Override
public final int hashCode() {
return Objects.hash(pageNoSchema, schema, totalRows);
}
@Override
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || !obj.getClass().equals(TableResult.class)) {
return false;
}
TableResult response = (TableResult) obj;
return Objects.equals(getNextPageToken(), response.getNextPageToken())
&& Iterators.elementsEqual(getValues().iterator(), response.getValues().iterator())
&& Objects.equals(schema, response.schema)
&& totalRows == response.totalRows;
}
}
| bigquery: let users contruct TableResult for testing (#3242)
Fixes #3228.
| google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableResult.java | bigquery: let users contruct TableResult for testing (#3242) |
|
Java | apache-2.0 | 90039bdd830e52f1a4e517ca7748a31207f76310 | 0 | ol-loginov/intellij-community,allotria/intellij-community,asedunov/intellij-community,samthor/intellij-community,robovm/robovm-studio,caot/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,xfournet/intellij-community,joewalnes/idea-community,caot/intellij-community,nicolargo/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,suncycheng/intellij-community,da1z/intellij-community,da1z/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,diorcety/intellij-community,holmes/intellij-community,diorcety/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,consulo/consulo,adedayo/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,izonder/intellij-community,FHannes/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,vvv1559/intellij-community,kool79/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,allotria/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ernestp/consulo,blademainer/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,ernestp/consulo,jagguli/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,hurricup/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,kool79/intellij-community,ernestp/consulo,tmpgit/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,holmes/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,kdwink/intellij-community,samthor/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,apixandru/intellij-community,retomerz/intellij-community,FHannes/intellij-community,kool79/intellij-community,retomerz/intellij-community,adedayo/intellij-community,holmes/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,asedunov/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,adedayo/intellij-community,clumsy/intellij-community,ryano144/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,da1z/intellij-community,nicolargo/intellij-community,holmes/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,slisson/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,jexp/idea2,fitermay/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,holmes/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,ernestp/consulo,youdonghai/intellij-community,slisson/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,adedayo/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,clumsy/intellij-community,kdwink/intellij-community,diorcety/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,supersven/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,consulo/consulo,diorcety/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,signed/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,hurricup/intellij-community,samthor/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,vladmm/intellij-community,vladmm/intellij-community,xfournet/intellij-community,retomerz/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,kool79/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,supersven/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,signed/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,izonder/intellij-community,fnouama/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,vladmm/intellij-community,semonte/intellij-community,ryano144/intellij-community,signed/intellij-community,fitermay/intellij-community,ernestp/consulo,kool79/intellij-community,robovm/robovm-studio,ibinti/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,holmes/intellij-community,kool79/intellij-community,tmpgit/intellij-community,holmes/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,hurricup/intellij-community,FHannes/intellij-community,ernestp/consulo,petteyg/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,jagguli/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,fitermay/intellij-community,holmes/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,adedayo/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,consulo/consulo,ibinti/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,jagguli/intellij-community,xfournet/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,fitermay/intellij-community,joewalnes/idea-community,ibinti/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,samthor/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,da1z/intellij-community,semonte/intellij-community,amith01994/intellij-community,samthor/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,da1z/intellij-community,allotria/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,jexp/idea2,michaelgallacher/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,slisson/intellij-community,fnouama/intellij-community,slisson/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,holmes/intellij-community,kdwink/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,izonder/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,consulo/consulo,petteyg/intellij-community,kdwink/intellij-community,signed/intellij-community,slisson/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,jexp/idea2,da1z/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,signed/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,asedunov/intellij-community,semonte/intellij-community,semonte/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,jexp/idea2,alphafoobar/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,xfournet/intellij-community,allotria/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,FHannes/intellij-community,blademainer/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,consulo/consulo,holmes/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,caot/intellij-community,kool79/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,izonder/intellij-community,jagguli/intellij-community,da1z/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,jexp/idea2,amith01994/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,joewalnes/idea-community,izonder/intellij-community,signed/intellij-community,nicolargo/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,kdwink/intellij-community,samthor/intellij-community,diorcety/intellij-community,diorcety/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,supersven/intellij-community,kdwink/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,adedayo/intellij-community,jagguli/intellij-community,ibinti/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,xfournet/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,supersven/intellij-community,xfournet/intellij-community,samthor/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,petteyg/intellij-community,blademainer/intellij-community,caot/intellij-community,ol-loginov/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,jexp/idea2,clumsy/intellij-community,allotria/intellij-community,ryano144/intellij-community,caot/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,dslomov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,ol-loginov/intellij-community,kdwink/intellij-community,jagguli/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,caot/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,jexp/idea2,lucafavatella/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,caot/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,FHannes/intellij-community,consulo/consulo,dslomov/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,holmes/intellij-community,apixandru/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,slisson/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,izonder/intellij-community,akosyakov/intellij-community,semonte/intellij-community,da1z/intellij-community,joewalnes/idea-community,asedunov/intellij-community,diorcety/intellij-community,joewalnes/idea-community,supersven/intellij-community,apixandru/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,signed/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,dslomov/intellij-community,fnouama/intellij-community,holmes/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,samthor/intellij-community,slisson/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,joewalnes/idea-community,robovm/robovm-studio,xfournet/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,signed/intellij-community,ryano144/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,caot/intellij-community,semonte/intellij-community,allotria/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,apixandru/intellij-community,caot/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,da1z/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,FHannes/intellij-community,robovm/robovm-studio | package com.intellij.openapi.vcs.changes.committed;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.CachingCommittedChangesProvider;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import javax.swing.*;
import java.text.DateFormat;
/**
* @author yole
*/
public class ChangeListDetailsAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
final Project project = e.getData(DataKeys.PROJECT);
final ChangeList[] changeLists = e.getData(DataKeys.CHANGE_LISTS);
if (changeLists != null && changeLists.length > 0 && changeLists [0] instanceof CommittedChangeList) {
showDetailsPopup(project, (CommittedChangeList) changeLists [0]);
}
}
public void update(final AnActionEvent e) {
final Project project = e.getData(DataKeys.PROJECT);
final ChangeList[] changeLists = e.getData(DataKeys.CHANGE_LISTS);
e.getPresentation().setEnabled(project != null && changeLists != null && changeLists.length > 0 &&
changeLists [0] instanceof CommittedChangeList);
}
public static void showDetailsPopup(final Project project, final CommittedChangeList changeList) {
StringBuilder detailsBuilder = new StringBuilder("<html><body>");
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
final AbstractVcs vcs = changeList.getVcs();
if (vcs != null) {
CachingCommittedChangesProvider provider = vcs.getCachingCommittedChangesProvider();
if (provider != null && provider.getChangelistTitle() != null) {
detailsBuilder.append(provider.getChangelistTitle()).append(" #").append(changeList.getNumber()).append("<br>");
}
}
detailsBuilder.append("Committed by <b>").append(changeList.getCommitterName()).append("</b> at ");
detailsBuilder.append(dateFormat.format(changeList.getCommitDate())).append("<br>");
detailsBuilder.append(XmlStringUtil.escapeString(changeList.getComment()).replace("\n", "<br>"));
detailsBuilder.append("</body></html>");
JEditorPane editorPane = new JEditorPane(UIUtil.HTML_MIME, detailsBuilder.toString());
editorPane.setEditable(false);
editorPane.setBackground(HintUtil.INFORMATION_COLOR);
editorPane.select(0, 0);
JScrollPane scrollPane = new JScrollPane(editorPane);
final JBPopup hint =
JBPopupFactory.getInstance().createComponentPopupBuilder(scrollPane, editorPane)
.setDimensionServiceKey(project, "changelist.details.popup", false)
.setResizable(true)
.setMovable(true)
.setRequestFocus(true)
.setTitle(VcsBundle.message("changelist.details.title"))
.createPopup();
hint.showInBestPositionFor(DataManager.getInstance().getDataContext());
}
} | source/com/intellij/openapi/vcs/changes/committed/ChangeListDetailsAction.java | package com.intellij.openapi.vcs.changes.committed;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.CachingCommittedChangesProvider;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.ChangeList;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import javax.swing.*;
import java.text.DateFormat;
/**
* @author yole
*/
public class ChangeListDetailsAction extends AnAction {
public void actionPerformed(AnActionEvent e) {
final Project project = e.getData(DataKeys.PROJECT);
final ChangeList[] changeLists = e.getData(DataKeys.CHANGE_LISTS);
if (changeLists != null && changeLists.length > 0 && changeLists [0] instanceof CommittedChangeList) {
showDetailsPopup(project, (CommittedChangeList) changeLists [0]);
}
}
public void update(final AnActionEvent e) {
final Project project = e.getData(DataKeys.PROJECT);
final ChangeList[] changeLists = e.getData(DataKeys.CHANGE_LISTS);
e.getPresentation().setEnabled(project != null && changeLists != null && changeLists.length > 0 &&
changeLists [0] instanceof CommittedChangeList);
}
public static void showDetailsPopup(final Project project, final CommittedChangeList changeList) {
StringBuilder detailsBuilder = new StringBuilder("<html><body>");
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
final AbstractVcs vcs = changeList.getVcs();
if (vcs != null) {
CachingCommittedChangesProvider provider = vcs.getCachingCommittedChangesProvider();
if (provider != null && provider.getChangelistTitle() != null) {
detailsBuilder.append(provider.getChangelistTitle()).append(" #").append(changeList.getNumber()).append("<br>");
}
}
detailsBuilder.append("Committed by <b>").append(changeList.getCommitterName()).append("</b> at ");
detailsBuilder.append(dateFormat.format(changeList.getCommitDate())).append("<br>");
detailsBuilder.append(XmlStringUtil.escapeString(changeList.getComment()));
detailsBuilder.append("</body></html>");
JEditorPane editorPane = new JEditorPane(UIUtil.HTML_MIME, detailsBuilder.toString());
editorPane.setEditable(false);
editorPane.setBackground(HintUtil.INFORMATION_COLOR);
JScrollPane scrollPane = new JScrollPane(editorPane);
final JBPopup hint =
JBPopupFactory.getInstance().createComponentPopupBuilder(scrollPane, editorPane)
.setDimensionServiceKey(project, "changelist.details.popup", false)
.setResizable(true)
.setMovable(true)
.setRequestFocus(true)
.setTitle(VcsBundle.message("changelist.details.title"))
.createPopup();
hint.showInBestPositionFor(DataManager.getInstance().getDataContext());
}
} | changelist details presentation tweaks
| source/com/intellij/openapi/vcs/changes/committed/ChangeListDetailsAction.java | changelist details presentation tweaks |
|
Java | apache-2.0 | ff551599de3eb5b02c929cb909cb52744a3efa30 | 0 | NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra,NationalSecurityAgency/ghidra | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.functioncompare;
import static org.junit.Assert.assertNotNull;
import java.awt.Window;
import java.util.Date;
import java.util.Set;
import javax.swing.JPanel;
import org.junit.*;
import docking.action.DockingActionIf;
import docking.widgets.dialogs.TableChooserDialog;
import docking.widgets.table.GFilterTable;
import generic.test.AbstractGenericTest;
import ghidra.app.plugin.core.codebrowser.CodeBrowserPlugin;
import ghidra.app.plugin.core.function.FunctionPlugin;
import ghidra.app.plugin.core.functionwindow.FunctionRowObject;
import ghidra.app.plugin.core.functionwindow.FunctionTableModel;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.address.Address;
import ghidra.program.model.data.ByteDataType;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.*;
import ghidra.program.util.ProgramLocation;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.TestEnv;
/**
* Tests for the {@link FunctionComparisonPlugin function comparison plugin}
* that involve the GUI
*/
public class CompareFunctionsTestSlow extends AbstractGhidraHeadedIntegrationTest {
private TestEnv env;
private Program program1;
private Program program2;
private Function foo;
private Function bar;
private Function bat;
private FunctionComparisonPlugin plugin;
private FunctionComparisonProvider provider;
private FunctionPlugin functionPlugin;
private CodeBrowserPlugin cbPlugin;
@Before
public void setUp() throws Exception {
env = new TestEnv();
plugin = env.addPlugin(FunctionComparisonPlugin.class);
functionPlugin = env.addPlugin(FunctionPlugin.class);
cbPlugin = env.addPlugin(CodeBrowserPlugin.class);
assertNotNull(plugin);
assertNotNull(functionPlugin);
buildTestProgram1();
buildTestProgram2();
showTool(plugin.getTool());
env.open(program1);
}
@After
public void tearDown() throws Exception {
env.dispose();
}
@Test
public void testRemoveLastItem() throws Exception {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
provider = plugin.compareFunctions(functions);
provider = waitForComponentProvider(FunctionComparisonProvider.class);
plugin.removeFunction(foo, provider);
assert (!provider.isVisible());
}
@Test
public void testCloseProgram() throws Exception {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);
plugin.programClosed(program1);
CompareFunctionsTestUtility.checkSourceFunctions(provider, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, bar);
plugin.programClosed(program2);
CompareFunctionsTestUtility.checkSourceFunctions(provider);
}
@Test
public void testNextPreviousAction() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
DockingActionIf nextAction = getAction(plugin, "Compare Next Function");
DockingActionIf prevAction = getAction(plugin, "Compare Previous Function");
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
performAction(nextAction);
assert (!nextAction.isEnabled());
assert (prevAction.isEnabled());
}
@Test
public void testNextPreviousActionSwitchPanelFocus() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
DockingActionIf nextAction = getAction(plugin, "Compare Next Function");
DockingActionIf prevAction = getAction(plugin, "Compare Previous Function");
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
performAction(nextAction);
assert (!nextAction.isEnabled());
assert (prevAction.isEnabled());
JPanel rightPanel =
provider.getComponent().getDualListingPanel().getRightPanel().getFieldPanel();
clickMouse(rightPanel, 1, 30, 30, 1, 0);
waitForSwing();
provider.getComponent().updateActionEnablement();
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
}
@Test
public void testOpenFunctionTableActionForAdd() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
DockingActionIf openTableAction = getAction(plugin, "Add Functions To Comparison");
performAction(openTableAction);
Window selectWindow = waitForWindowByTitleContaining("Select Functions");
assert (selectWindow != null);
}
@SuppressWarnings("unchecked")
@Test
public void testAddFunctionToExistingCompare() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
assert (provider.getModel().getSourceFunctions().size() == 1);
DockingActionIf openTableAction = getAction(plugin, "Add Functions To Comparison");
performAction(openTableAction);
TableChooserDialog<FunctionTableModel> chooser =
waitForDialogComponent(TableChooserDialog.class);
assert (chooser != null);
GFilterTable<FunctionRowObject> table =
(GFilterTable<FunctionRowObject>) getInstanceField("gFilterTable", chooser);
assert (table.getModel().getRowCount() == 2);
clickTableCell(table.getTable(), 1, 0, 1);
pressButtonByText(chooser, "OK");
waitForSwing();
assert (provider.getModel().getSourceFunctions().size() == 2);
}
@Test
public void testDeleteFunctionFromListing() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
assert (provider.getModel().getSourceFunctions().size() == 2);
assert (provider.getModel().getSourceFunctions().contains(foo));
assert (provider.getModel().getSourceFunctions().contains(bar));
Address addr = program1.getAddressFactory().getAddress("10018cf");
ProgramLocation loc = new ProgramLocation(program1, addr);
cbPlugin.goTo(loc);
DockingActionIf deleteAction = getAction(functionPlugin, "Delete Function");
performAction(deleteAction);
waitForSwing();
assert (provider.getModel().getSourceFunctions().size() == 1);
assert (provider.getModel().getSourceFunctions().contains(bar));
}
/**
* Builds a program with 2 functions
*/
private ProgramBuilder buildTestProgram1() throws Exception {
ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
builder.createMemory(".text", "0x1001000", 0x6600);
builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent
// functions
DataType dt = new ByteDataType();
Parameter p = new ParameterImpl(null, dt, builder.getProgram());
foo = builder.createEmptyFunction("Foo", "10018cf", 10, null, p);
bat = builder.createEmptyFunction("Bat", "100299e", 130, null, p, p, p);
program1 = builder.getProgram();
AbstractGenericTest.setInstanceField("recordChanges", program1, Boolean.TRUE);
return builder;
}
/**
* Builds a program with 1 function
*/
private ProgramBuilder buildTestProgram2() throws Exception {
ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
builder.createMemory(".text", "0x1001000", 0x6600);
builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent
// functions
DataType dt = new ByteDataType();
Parameter p = new ParameterImpl(null, dt, builder.getProgram());
bar = builder.createEmptyFunction("Bar", "10018cf", 10, null, p);
program2 = builder.getProgram();
AbstractGenericTest.setInstanceField("recordChanges", program2, Boolean.TRUE);
return builder;
}
}
| Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/functioncompare/CompareFunctionsTestSlow.java | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.functioncompare;
import static org.junit.Assert.assertNotNull;
import java.awt.Window;
import java.util.Date;
import java.util.Set;
import javax.swing.JPanel;
import org.junit.*;
import docking.action.DockingActionIf;
import docking.widgets.dialogs.TableChooserDialog;
import docking.widgets.table.GFilterTable;
import generic.test.AbstractGenericTest;
import ghidra.app.plugin.core.functionwindow.FunctionRowObject;
import ghidra.app.plugin.core.functionwindow.FunctionTableModel;
import ghidra.program.database.ProgramBuilder;
import ghidra.program.model.data.ByteDataType;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.*;
import ghidra.test.AbstractGhidraHeadedIntegrationTest;
import ghidra.test.TestEnv;
/**
* Tests for the {@link FunctionComparisonPlugin function comparison plugin}
* that involve the GUI
*/
public class CompareFunctionsTestSlow extends AbstractGhidraHeadedIntegrationTest {
private TestEnv env;
private Program program1;
private Program program2;
private Function foo;
private Function bar;
private Function bat;
private FunctionComparisonPlugin plugin;
private FunctionComparisonProvider provider;
@Before
public void setUp() throws Exception {
env = new TestEnv();
plugin = env.addPlugin(FunctionComparisonPlugin.class);
assertNotNull(plugin);
buildTestProgram1();
buildTestProgram2();
showTool(plugin.getTool());
env.open(program1);
}
@After
public void tearDown() throws Exception {
env.dispose();
}
@Test
public void testRemoveLastItem() throws Exception {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
provider = plugin.compareFunctions(functions);
provider = waitForComponentProvider(FunctionComparisonProvider.class);
plugin.removeFunction(foo, provider);
assert (!provider.isVisible());
}
@Test
public void testCloseProgram() throws Exception {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
CompareFunctionsTestUtility.checkSourceFunctions(provider, foo, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, foo, foo, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, foo, bar);
plugin.programClosed(program1);
CompareFunctionsTestUtility.checkSourceFunctions(provider, bar);
CompareFunctionsTestUtility.checkTargetFunctions(provider, bar, bar);
plugin.programClosed(program2);
CompareFunctionsTestUtility.checkSourceFunctions(provider);
}
@Test
public void testNextPreviousAction() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
DockingActionIf nextAction = getAction(plugin, "Compare Next Function");
DockingActionIf prevAction = getAction(plugin, "Compare Previous Function");
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
performAction(nextAction);
assert (!nextAction.isEnabled());
assert (prevAction.isEnabled());
}
@Test
public void testNextPreviousActionSwitchPanelFocus() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
DockingActionIf nextAction = getAction(plugin, "Compare Next Function");
DockingActionIf prevAction = getAction(plugin, "Compare Previous Function");
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
performAction(nextAction);
assert (!nextAction.isEnabled());
assert (prevAction.isEnabled());
JPanel rightPanel =
provider.getComponent().getDualListingPanel().getRightPanel().getFieldPanel();
clickMouse(rightPanel, 1, 30, 30, 1, 0);
waitForSwing();
provider.getComponent().updateActionEnablement();
assert (nextAction.isEnabled());
assert (!prevAction.isEnabled());
}
@Test
public void testOpenFunctionTableActionForAdd() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo, bar);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
DockingActionIf openTableAction = getAction(plugin, "Add Functions To Comparison");
performAction(openTableAction);
Window selectWindow = waitForWindowByTitleContaining("Select Functions");
assert (selectWindow != null);
}
@SuppressWarnings("unchecked")
@Test
public void testAddFunctionToExistingCompare() {
Set<Function> functions = CompareFunctionsTestUtility.getFunctionsAsSet(foo);
provider = plugin.compareFunctions(functions);
provider.setVisible(true);
waitForSwing();
// Must do this or there will be no "active" provider in the actions
// initiated below
clickComponentProvider(provider);
assert (provider.getModel().getSourceFunctions().size() == 1);
DockingActionIf openTableAction = getAction(plugin, "Add Functions To Comparison");
performAction(openTableAction);
TableChooserDialog<FunctionTableModel> chooser =
waitForDialogComponent(TableChooserDialog.class);
assert (chooser != null);
GFilterTable<FunctionRowObject> table =
(GFilterTable<FunctionRowObject>) getInstanceField("gFilterTable", chooser);
assert (table.getModel().getRowCount() == 2);
clickTableCell(table.getTable(), 1, 0, 1);
pressButtonByText(chooser, "OK");
waitForSwing();
assert (provider.getModel().getSourceFunctions().size() == 2);
}
/**
* Builds a program with 2 functions
*/
private ProgramBuilder buildTestProgram1() throws Exception {
ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
builder.createMemory(".text", "0x1001000", 0x6600);
builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent
// functions
DataType dt = new ByteDataType();
Parameter p = new ParameterImpl(null, dt, builder.getProgram());
foo = builder.createEmptyFunction("Foo", "10018cf", 10, null, p);
bat = builder.createEmptyFunction("Bar", "100299e", 130, null, p, p, p);
program1 = builder.getProgram();
AbstractGenericTest.setInstanceField("recordChanges", program1, Boolean.TRUE);
return builder;
}
/**
* Builds a program with 1 function
*/
private ProgramBuilder buildTestProgram2() throws Exception {
ProgramBuilder builder = new ProgramBuilder("TestPgm1", ProgramBuilder._TOY_BE);
builder.createMemory(".text", "0x1001000", 0x6600);
builder.setProperty(Program.DATE_CREATED, new Date(100000000)); // arbitrary, but consistent
// functions
DataType dt = new ByteDataType();
Parameter p = new ParameterImpl(null, dt, builder.getProgram());
bar = builder.createEmptyFunction("Bar", "10018cf", 10, null, p);
program2 = builder.getProgram();
AbstractGenericTest.setInstanceField("recordChanges", program2, Boolean.TRUE);
return builder;
}
}
| GT-2229: added test for function delete | Ghidra/Features/Base/src/test/java/ghidra/app/plugin/core/functioncompare/CompareFunctionsTestSlow.java | GT-2229: added test for function delete |
|
Java | apache-2.0 | 3e5e2dda3bfe1f79994b1d10b298a950a64de8a7 | 0 | nabedge/mixer2,nabedge/mixer2 | package org.mixer2.spring.webmvc;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mixer2.Mixer2Engine;
import org.mixer2.jaxb.xhtml.Html;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Abstract class to create view class for Spring MVC.
* <p>
* use this class with {@link Mixer2XhtmlViewResolver}
* </p>
*
* <h4>implementation sample</h4>
*
* <pre><code>
* public class HelloWorldView extends AbstractMixer2XhtmlView {
*
* {@literal @}Autowired
* private FooBar fooBar;
*
* {@literal @}Override
* protected Html renderHtml(Html html, Map<String, Object> model, HttpServletRequest request,
* HttpServletResponse response) throws TagTypeUnmatchException {
*
* {@literal @}SuppressWarnings("unchecked")
* String message = (String) model.get("helloMessage");
* Div div = html.getById("message", Div.class);
* div.unsetContent();
* div.getContent().add(message);
*
* return html;
* }
* </code></pre>
*
* <p>
* You NEED NOT to add "@Component" annotation because
* {@link Mixer2XhtmlViewResolver} instantiate the view class
* through AutowireCapableBeanFactory.
* </p>
*
* @see {@link http://mixer2.org/site/helloworld.html}
* @see {@link http://mixer2.org/site/springmvcsample.html}
* @see {@link https://github.com/nabedge/mixer2-sample/tree/master/mixer2-fruitshop-springmvc}
* @author kazuki43zoo
* @author nabedge
*
*/
public abstract class AbstractMixer2XhtmlView extends AbstractUrlBasedView {
private static String lineBreakChar = System.getProperty("line.separator");
private ResourceLoader resourceLoader;
private String docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
private Mixer2Engine mixer2Engine;
public static final AbstractMixer2XhtmlView createDefaultView() {
return new AbstractMixer2XhtmlView() {
@Override
protected Html renderHtml(Html templateHtml,
Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
return templateHtml;
};
};
}
public AbstractMixer2XhtmlView() {
setContentType("text/html; charset=UTF-8");
}
public void setDocType(String docType) {
this.docType = docType;
}
public void setMixer2Engine(Mixer2Engine mixer2Engine) {
this.mixer2Engine = mixer2Engine;
}
protected Mixer2Engine getMixer2Engine() {
return mixer2Engine;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.notNull(mixer2Engine, "Property 'mixer2Engine' is required.");
Assert.notNull(resourceLoader, "Property 'resourceLoader' is required.");
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Html templateHtml = mixer2Engine
.checkAndLoadHtmlTemplate(resourceLoader.getResource(getUrl())
.getInputStream());
Html renderedHtml = renderHtml(templateHtml, model, request, response);
response.setContentType(getContentType());
responseHtml(renderedHtml, response);
}
protected void responseHtml(Html renderedHtml, HttpServletResponse response)
throws IOException {
PrintWriter writer = response.getWriter();
StringBuilder sb = new StringBuilder();
if (docType != null && !docType.trim().isEmpty()) {
sb.append(docType.trim());
sb.append(lineBreakChar);
}
sb.append(getMixer2Engine().saveToString(renderedHtml).trim());
writer.write(sb.toString());
}
/**
* Need implementation.
*
* @param html
* {@link org.mixer2.jaxb.xhtml.Html Html} instance of xhtml
* template that is loaded by {@link Mixer2XhtmlViewResolver}.
* @param model
* @param request
* @param response
* @return
* @throws Exception
* @see {@link Mixer2XhtmlViewResolver}
*/
protected abstract Html renderHtml(Html html, Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
| src/main/java/org/mixer2/spring/webmvc/AbstractMixer2XhtmlView.java | package org.mixer2.spring.webmvc;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mixer2.Mixer2Engine;
import org.mixer2.jaxb.xhtml.Html;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Abstract class to create view class for Spring MVC.
* <p>
* use this class with {@link Mixer2XhtmlViewResolver}
* </p>
*
* <h4>implementation sample</h4>
*
* <pre><code>
* public class HelloWorldView extends AbstractMixer2XhtmlView {
*
* {@literal @}Autowired
* private FooBar fooBar;
*
* {@literal @}Override
* protected Html renderHtml(Html html, Map<String, Object> model, HttpServletRequest request,
* HttpServletResponse response) throws TagTypeUnmatchException {
*
* {@literal @}SuppressWarnings("unchecked")
* String message = (String) model.get("helloMessage");
* Div div = html.getById("message", Div.class);
* div.unsetContent();
* div.getContent().add(message);
*
* return html;
* }
* </code></pre>
*
* <p>
* You NEED NOT to add "@Component" annotation because
* {@link Mixer2XhtmlViewResolver} instantiate the view class
* through AutowireCapableBeanFactory.
* </p>
*
* @see {@link http://mixer2.org/site/helloworld.html}
* @see {@link http://mixer2.org/site/springmvcsample.html}
* @see {@link https://github.com/nabedge/mixer2-sample/tree/master/mixer2-fruitshop-springmvc}
* @author kazuki43zoo
* @author nabedge
*
*/
public abstract class AbstractMixer2XhtmlView extends AbstractUrlBasedView {
private static String lineBreakChar = System.getProperty("line.separator");
private ResourceLoader resourceLoader;
private String docType = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
private Mixer2Engine mixer2Engine;
public static final AbstractMixer2XhtmlView createDefaultView() {
return new AbstractMixer2XhtmlView() {
@Override
protected Html renderHtml(Html templateHtml,
Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
return templateHtml;
};
};
}
public AbstractMixer2XhtmlView() {
setContentType("text/html; charset=UTF-8");
}
public void setDocType(String docType) {
this.docType = docType;
}
public void setMixer2Engine(Mixer2Engine mixer2Engine) {
this.mixer2Engine = mixer2Engine;
}
protected Mixer2Engine getMixer2Engine() {
return mixer2Engine;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
Assert.notNull(mixer2Engine, "Property 'mixer2Engine' is required.");
Assert.notNull(resourceLoader, "Property 'resourceLoader' is required.");
}
@Override
protected final void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Html templateHtml = mixer2Engine
.checkAndLoadHtmlTemplate(resourceLoader.getResource(getUrl())
.getInputStream());
Html renderedHtml = renderHtml(templateHtml, model, request, response);
response.setContentType(getContentType());
responseHtml(renderedHtml, response);
}
protected void responseHtml(Html renderedHtml, HttpServletResponse response)
throws IOException {
PrintWriter writer = response.getWriter();
StringBuilder sb = new StringBuilder();
if (docType != null && !docType.trim().isEmpty()) {
sb.append(docType.trim());
sb.append(lineBreakChar);
}
sb.append(getMixer2Engine().saveToString(renderedHtml).trim());
writer.write(sb.toString());
}
/**
* Need implementation.
*
* @param html
* {@link org.mixer2.jaxb.xhtml.Html Html} instance of xhtml
* template that is loaded by {@link Mixer2XhtmlViewResolver}.
* @param model
* @param request
* @param response
* @return
* @throws Exception
* @see {@link Mixer2XhtmlViewResolver}
*/
protected abstract Html renderHtml(Html html, Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
| 拡張しやすいようにメソッドのシグネチャをfinalに変更 | src/main/java/org/mixer2/spring/webmvc/AbstractMixer2XhtmlView.java | 拡張しやすいようにメソッドのシグネチャをfinalに変更 |
|
Java | apache-2.0 | dc972e2db88a79cbe8303cf88723fa11143a3a78 | 0 | ominux/paco,h/paco,jaythaceo/paco,jaythaceo/paco,h/paco,h/paco,bowlofstew/paco,athoo/paco,hlecuanda/paco,h/paco,ominux/paco,google/paco,jaythaceo/paco,kehollin/paco,athoo/paco,google/paco,mtxs007/paco,mhadjimichael/paco,google/paco,hlecuanda/paco,jaythaceo/paco,google/paco,athoo/paco,kehollin/paco,bowlofstew/paco,h/paco,mhadjimichael/paco,mhadjimichael/paco,ominux/paco,mhadjimichael/paco,athoo/paco,hlecuanda/paco,kehollin/paco,h/paco,hlecuanda/paco,jaythaceo/paco,ominux/paco,google/paco,hlecuanda/paco,kehollin/paco,jaythaceo/paco,kehollin/paco,ominux/paco,bowlofstew/paco,mhadjimichael/paco,bowlofstew/paco,bowlofstew/paco,hlecuanda/paco,jaythaceo/paco,mtxs007/paco,mtxs007/paco,bowlofstew/paco,hlecuanda/paco,ominux/paco,google/paco,mtxs007/paco,athoo/paco,athoo/paco,h/paco,athoo/paco,kehollin/paco,google/paco,mhadjimichael/paco,mtxs007/paco,ominux/paco,mtxs007/paco,kehollin/paco,bowlofstew/paco,mtxs007/paco,mhadjimichael/paco | package com.google.android.apps.paco;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.google.common.collect.Lists;
import com.google.paco.shared.model.FeedbackDAO;
import com.google.paco.shared.model.SignalScheduleDAO;
import com.google.paco.shared.model.SignalTimeDAO;
/**
* This class helps open, create, and upgrade the database file.
*/
@SuppressLint("UseSparseArrays")
public class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
// Visible for testing
public DatabaseHelper(Context context/*, InputStream in*/) {
super(context, ExperimentProvider.DATABASE_NAME, null, ExperimentProvider.DATABASE_VERSION);
// this.sqlInput = in;
this.context = context;
}
// For testing
DatabaseHelper(Context context, String dbName, int dbVersion) {
super(context, dbName, null, dbVersion);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ("
+ ExperimentColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ExperimentColumns.SERVER_ID + " INTEGER,"
+ ExperimentColumns.TITLE + " TEXT, "
+ ExperimentColumns.VERSION + " INTEGER,"
+ ExperimentColumns.DESCRIPTION + " TEXT, "
+ ExperimentColumns.CREATOR + " TEXT, "
+ ExperimentColumns.INFORMED_CONSENT + " TEXT, "
+ ExperimentColumns.HASH + " TEXT, "
+ ExperimentColumns.FIXED_DURATION + " INTEGER, "
+ ExperimentColumns.START_DATE + " TEXT, "
+ ExperimentColumns.END_DATE + " TEXT, "
+ ExperimentColumns.JOIN_DATE + " TEXT, "
+ ExperimentColumns.QUESTIONS_CHANGE + " INTEGER, "
+ ExperimentColumns.ICON + " BLOB, "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER, "
+ ExperimentColumns.JSON + " TEXT "
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ("
+ SignalScheduleColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ SignalScheduleColumns.SERVER_ID + " INTEGER, "
+ SignalScheduleColumns.EXPERIMENT_ID + " INTEGER, "
+ SignalScheduleColumns.SCHEDULE_TYPE + " INTEGER, "
+ SignalScheduleColumns.ESM_FREQUENCY + " INTEGER, "
+ SignalScheduleColumns.ESM_PERIOD + " INTEGER, "
+ SignalScheduleColumns.ESM_START_HOUR + " INTEGER, "
+ SignalScheduleColumns.ESM_END_HOUR + " INTEGER, "
+ SignalScheduleColumns.ESM_WEEKENDS + " INTEGER, "
+ SignalScheduleColumns.TIMES_CSV + " TEXT, "
+ SignalScheduleColumns.REPEAT_RATE + " INTEGER, "
+ SignalScheduleColumns.WEEKDAYS_SCHEDULED + " INTEGER, "
+ SignalScheduleColumns.NTH_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.BY_DAY_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.DAY_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.BEGIN_DATE + " INTEGER, "
+ SignalScheduleColumns.USER_EDITABLE + " INTEGER, "
+ SignalScheduleColumns.TIME_OUT + " INTEGER, "
+ SignalScheduleColumns.MINIMUM_BUFFER + " INTEGER, "
+ SignalScheduleColumns.SNOOZE_COUNT + " INTEGER, "
+ SignalScheduleColumns.SNOOZE_TIME + " INTEGER, "
+ SignalScheduleColumns.SIGNAL_TIMES + " INTEGER "
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " ("
+ InputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ InputColumns.EXPERIMENT_ID + " INTEGER, "
+ InputColumns.SERVER_ID + " INTEGER, "
+ InputColumns.NAME + " TEXT,"
+ InputColumns.TEXT + " TEXT,"
+ InputColumns.MANDATORY + " INTEGER,"
+ InputColumns.SCHEDULED_DATE + " INTEGER,"
+ InputColumns.QUESTION_TYPE + " INTEGER,"
+ InputColumns.RESPONSE_TYPE + " INTEGER,"
+ InputColumns.LIKERT_STEPS + " INTEGER,"
+ InputColumns.LEFT_SIDE_LABEL + " TEXT,"
+ InputColumns.RIGHT_SIDE_LABEL + " TEXT,"
+ InputColumns.LIST_CHOICES_JSON + " TEXT,"
+ InputColumns.CONDITIONAL + " INTEGER,"
+ InputColumns.CONDITIONAL_EXPRESSION + " TEXT,"
+ InputColumns.MULTISELECT + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " ("
+ EventColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EventColumns.EXPERIMENT_ID + " INTEGER, "
+ EventColumns.EXPERIMENT_SERVER_ID + " INTEGER, "
+ EventColumns.EXPERIMENT_NAME + " TEXT, "
+ EventColumns.EXPERIMENT_VERSION + " INTEGER, "
+ EventColumns.SCHEDULE_TIME + " INTEGER, "
+ EventColumns.RESPONSE_TIME + " INTEGER,"
+ EventColumns.UPLOADED + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.OUTPUTS_TABLE_NAME + " ("
+ OutputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ OutputColumns.EVENT_ID + " INTEGER, "
+ OutputColumns.INPUT_SERVER_ID + " INTEGER, "
+ OutputColumns.NAME + " TEXT,"
+ OutputColumns.ANSWER + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.FEEDBACK_TABLE_NAME + " ("
+ FeedbackColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ FeedbackColumns.EXPERIMENT_ID + " INTEGER, "
+ FeedbackColumns.SERVER_ID + " INTEGER, "
+ FeedbackColumns.TEXT + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.NOTIFICATION_TABLE_NAME + " ("
+ NotificationHolderColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NotificationHolderColumns.ALARM_TIME + " INTEGER, "
+ NotificationHolderColumns.EXPERIMENT_ID + " INTEGER, "
+ NotificationHolderColumns.NOTICE_COUNT + " INTEGER, "
+ NotificationHolderColumns.TIMEOUT_MILLIS + " INTEGER"
+ ");");
// insertValues(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(ExperimentProvider.TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ".");
if (oldVersion <= 8) {
db.execSQL("ALTER TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " ADD "
+ InputColumns.MULTISELECT + " INTEGER default 0"
+ ";");
}
if (oldVersion <= 9) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.USER_EDITABLE + " INTEGER default 1"
+ ";");
}
if (oldVersion <= 10) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER default 0"
+ ";");
}
if (oldVersion <= 11) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.VERSION + " INTEGER default 0"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " ADD "
+ EventColumns.EXPERIMENT_VERSION + " INTEGER default 0"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.TIME_OUT + " INTEGER"
+ ";");
}
if (oldVersion <= 12) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.JSON + " TEXT "
+ ";");
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<Experiment> joined = eu.getJoinedExperiments();
for (Experiment experiment : joined) {
eu.updateJoinedExperiment(experiment);
}
}
if (oldVersion <= 13) {
HashMap<Integer, String> startDatePairs = convertDateLongsToStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.START_DATE, ExperimentColumns._ID);
HashMap<Integer, String> endDatePairs = convertDateLongsToStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.END_DATE, ExperimentColumns._ID);
HashMap<Integer, String> joinDatePairs = convertDateLongsToTzStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.JOIN_DATE, ExperimentColumns._ID);
createTruncatedExperimentsTable(db);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, startDatePairs,
ExperimentColumns.START_DATE, ExperimentColumns._ID);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, endDatePairs,
ExperimentColumns.END_DATE, ExperimentColumns._ID);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, joinDatePairs,
ExperimentColumns.JOIN_DATE, ExperimentColumns._ID);
}
if (oldVersion <= 14) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.MINIMUM_BUFFER + " INTEGER"
+ ";");
}
if (oldVersion <= 15) {
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<Experiment> joined = eu.getJoinedExperiments();
for (Experiment experiment : joined) {
//verify that feedbackType is correct
if (experiment.getFeedbackType() == null || experiment.getFeedbackType() == FeedbackDAO.FEEDBACK_TYPE_RETROSPECTIVE) { // the default
eu.loadFeedbackForExperiment(experiment);
// if it is our default value make sure that it is not actually custom code.
if (!FeedbackDAO.DEFAULT_FEEDBACK_MSG.equals(experiment.getFeedback().get(0).getText())) {
experiment.setFeedbackType(FeedbackDAO.FEEDBACK_TYPE_CUSTOM);
eu.updateJoinedExperiment(experiment);
}
}
}
eu.deleteExperimentCachesOnDisk();
}
if (oldVersion <= 16) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SNOOZE_COUNT + " INTEGER"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SNOOZE_TIME + " INTEGER"
+ ";");
}
if (oldVersion <= 17) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SIGNAL_TIMES + " INTEGER"
+ ";");
migrateExistingLongTimeValuesToSignalTimeValues();
}
}
private void migrateExistingLongTimeValuesToSignalTimeValues() {
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<Experiment> experiments = eu.getJoinedExperiments();
for (Experiment experiment : experiments) {
SignalSchedule schedule = experiment.getSchedule();
if (schedule.getScheduleType() != SignalScheduleDAO.SELF_REPORT
&& schedule.getScheduleType() != SignalScheduleDAO.ESM) {
List<SignalTime> signalTimes = Lists.newArrayList();
List<Long> times = schedule.getTimes();
for (Long time : times) {
signalTimes.add(new SignalTime(SignalTimeDAO.FIXED_TIME, SignalTimeDAO.OFFSET_BASIS_SCHEDULED_TIME,
(int) time.longValue(), SignalTimeDAO.MISSED_BEHAVIOR_USE_SCHEDULED_TIME, 0,
""));
}
schedule.setSignalTimes(signalTimes);
}
}
eu.updateExistingExperiments(experiments);
}
private static HashMap<Integer, String> convertDateLongsToStrings(SQLiteDatabase db,
String tableName,
String dateCol, String refCol) {
String[] columns = {dateCol, refCol};
HashMap<Integer, String> data = new HashMap<Integer, String>();
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol));
if (longVal != null) {
String dateStr = TimeUtil.formatDate(longVal);
Integer id = cursor.getInt(cursor.getColumnIndex(refCol));
data.put(id, dateStr);
}
}
}
} finally {
cursor.close();
}
return data;
}
private static HashMap<Integer, String> convertDateLongsToTzStrings(SQLiteDatabase db,
String tableName,
String dateCol, String refCol) {
String[] columns = {dateCol, refCol};
HashMap<Integer, String> data = new HashMap<Integer, String>();
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol));
if (longVal != null) {
String dateStr = TimeUtil.formatDateWithZone(longVal);
Integer id = cursor.getInt(cursor.getColumnIndex(refCol));
data.put(id, dateStr);
}
}
}
} finally {
cursor.close();
}
return data;
}
private static void createTruncatedExperimentsTable(SQLiteDatabase db) {
String tempTable = "tempTable";
db.execSQL("CREATE TABLE " + tempTable + " ("
+ ExperimentColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ExperimentColumns.SERVER_ID + " INTEGER,"
+ ExperimentColumns.TITLE + " TEXT, "
+ ExperimentColumns.VERSION + " INTEGER,"
+ ExperimentColumns.DESCRIPTION + " TEXT, "
+ ExperimentColumns.CREATOR + " TEXT, "
+ ExperimentColumns.INFORMED_CONSENT + " TEXT, "
+ ExperimentColumns.HASH + " TEXT, "
+ ExperimentColumns.FIXED_DURATION + " INTEGER, "
+ ExperimentColumns.QUESTIONS_CHANGE + " INTEGER, "
+ ExperimentColumns.ICON + " BLOB, "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER, "
+ ExperimentColumns.JSON + " TEXT "
+ ");");
db.execSQL("INSERT INTO " + tempTable + " (" +
ExperimentColumns._ID + ", " +
ExperimentColumns.SERVER_ID + ", " +
ExperimentColumns.TITLE + ", " +
ExperimentColumns.VERSION + ", " +
ExperimentColumns.DESCRIPTION + ", " +
ExperimentColumns.CREATOR + ", " +
ExperimentColumns.INFORMED_CONSENT + ", " +
ExperimentColumns.HASH + ", " +
ExperimentColumns.FIXED_DURATION + ", " +
ExperimentColumns.QUESTIONS_CHANGE + ", " +
ExperimentColumns.ICON + ", " +
ExperimentColumns.WEB_RECOMMENDED + ", " +
ExperimentColumns.JSON +
") " + "SELECT " +
ExperimentColumns._ID + ", " +
ExperimentColumns.SERVER_ID + ", " +
ExperimentColumns.TITLE + ", " +
ExperimentColumns.VERSION + ", " +
ExperimentColumns.DESCRIPTION + ", " +
ExperimentColumns.CREATOR + ", " +
ExperimentColumns.INFORMED_CONSENT + ", " +
ExperimentColumns.HASH + ", " +
ExperimentColumns.FIXED_DURATION + ", " +
ExperimentColumns.QUESTIONS_CHANGE + ", " +
ExperimentColumns.ICON + ", " +
ExperimentColumns.WEB_RECOMMENDED + ", " +
ExperimentColumns.JSON +
" FROM " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + ";");
db.execSQL("DROP TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME);
db.execSQL("ALTER TABLE " + tempTable + " RENAME TO " + ExperimentProvider.EXPERIMENTS_TABLE_NAME);
}
private static void insertNewDateColumnWithData(SQLiteDatabase db, String tableName,
HashMap<Integer,String> data,
String dateCol, String refCol) {
db.execSQL("ALTER TABLE " + tableName + " ADD " + dateCol + " TEXT " + ";");
for (Map.Entry<Integer, String> entry : data.entrySet()) {
db.execSQL("UPDATE " + tableName +
" SET " + dateCol + " = " + "\'" + entry.getValue() + "\'" +
" WHERE " + refCol + " = " + entry.getKey() + ";");
}
}
}
| Paco/src/com/google/android/apps/paco/DatabaseHelper.java | package com.google.android.apps.paco;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.google.common.collect.Lists;
import com.google.paco.shared.model.FeedbackDAO;
import com.google.paco.shared.model.SignalScheduleDAO;
import com.google.paco.shared.model.SignalTimeDAO;
/**
* This class helps open, create, and upgrade the database file.
*/
@SuppressLint("UseSparseArrays")
public class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
// Visible for testing
public DatabaseHelper(Context context/*, InputStream in*/) {
super(context, ExperimentProvider.DATABASE_NAME, null, ExperimentProvider.DATABASE_VERSION);
// this.sqlInput = in;
this.context = context;
}
// For testing
DatabaseHelper(Context context, String dbName, int dbVersion) {
super(context, dbName, null, dbVersion);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ("
+ ExperimentColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ExperimentColumns.SERVER_ID + " INTEGER,"
+ ExperimentColumns.TITLE + " TEXT, "
+ ExperimentColumns.VERSION + " INTEGER,"
+ ExperimentColumns.DESCRIPTION + " TEXT, "
+ ExperimentColumns.CREATOR + " TEXT, "
+ ExperimentColumns.INFORMED_CONSENT + " TEXT, "
+ ExperimentColumns.HASH + " TEXT, "
+ ExperimentColumns.FIXED_DURATION + " INTEGER, "
+ ExperimentColumns.START_DATE + " TEXT, "
+ ExperimentColumns.END_DATE + " TEXT, "
+ ExperimentColumns.JOIN_DATE + " TEXT, "
+ ExperimentColumns.QUESTIONS_CHANGE + " INTEGER, "
+ ExperimentColumns.ICON + " BLOB, "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER, "
+ ExperimentColumns.JSON + " TEXT "
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ("
+ SignalScheduleColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ SignalScheduleColumns.SERVER_ID + " INTEGER, "
+ SignalScheduleColumns.EXPERIMENT_ID + " INTEGER, "
+ SignalScheduleColumns.SCHEDULE_TYPE + " INTEGER, "
+ SignalScheduleColumns.ESM_FREQUENCY + " INTEGER, "
+ SignalScheduleColumns.ESM_PERIOD + " INTEGER, "
+ SignalScheduleColumns.ESM_START_HOUR + " INTEGER, "
+ SignalScheduleColumns.ESM_END_HOUR + " INTEGER, "
+ SignalScheduleColumns.ESM_WEEKENDS + " INTEGER, "
+ SignalScheduleColumns.TIMES_CSV + " TEXT, "
+ SignalScheduleColumns.REPEAT_RATE + " INTEGER, "
+ SignalScheduleColumns.WEEKDAYS_SCHEDULED + " INTEGER, "
+ SignalScheduleColumns.NTH_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.BY_DAY_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.DAY_OF_MONTH + " INTEGER, "
+ SignalScheduleColumns.BEGIN_DATE + " INTEGER, "
+ SignalScheduleColumns.USER_EDITABLE + " INTEGER, "
+ SignalScheduleColumns.TIME_OUT + " INTEGER, "
+ SignalScheduleColumns.MINIMUM_BUFFER + " INTEGER, "
+ SignalScheduleColumns.SNOOZE_COUNT + " INTEGER, "
+ SignalScheduleColumns.SNOOZE_TIME + " INTEGER, "
+ SignalScheduleColumns.SIGNAL_TIMES + " INTEGER "
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " ("
+ InputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ InputColumns.EXPERIMENT_ID + " INTEGER, "
+ InputColumns.SERVER_ID + " INTEGER, "
+ InputColumns.NAME + " TEXT,"
+ InputColumns.TEXT + " TEXT,"
+ InputColumns.MANDATORY + " INTEGER,"
+ InputColumns.SCHEDULED_DATE + " INTEGER,"
+ InputColumns.QUESTION_TYPE + " INTEGER,"
+ InputColumns.RESPONSE_TYPE + " INTEGER,"
+ InputColumns.LIKERT_STEPS + " INTEGER,"
+ InputColumns.LEFT_SIDE_LABEL + " TEXT,"
+ InputColumns.RIGHT_SIDE_LABEL + " TEXT,"
+ InputColumns.LIST_CHOICES_JSON + " TEXT,"
+ InputColumns.CONDITIONAL + " INTEGER,"
+ InputColumns.CONDITIONAL_EXPRESSION + " TEXT,"
+ InputColumns.MULTISELECT + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " ("
+ EventColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ EventColumns.EXPERIMENT_ID + " INTEGER, "
+ EventColumns.EXPERIMENT_SERVER_ID + " INTEGER, "
+ EventColumns.EXPERIMENT_NAME + " TEXT, "
+ EventColumns.EXPERIMENT_VERSION + " INTEGER, "
+ EventColumns.SCHEDULE_TIME + " INTEGER, "
+ EventColumns.RESPONSE_TIME + " INTEGER,"
+ EventColumns.UPLOADED + " INTEGER"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.OUTPUTS_TABLE_NAME + " ("
+ OutputColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ OutputColumns.EVENT_ID + " INTEGER, "
+ OutputColumns.INPUT_SERVER_ID + " INTEGER, "
+ OutputColumns.NAME + " TEXT,"
+ OutputColumns.ANSWER + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.FEEDBACK_TABLE_NAME + " ("
+ FeedbackColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ FeedbackColumns.EXPERIMENT_ID + " INTEGER, "
+ FeedbackColumns.SERVER_ID + " INTEGER, "
+ FeedbackColumns.TEXT + " TEXT"
+ ");");
db.execSQL("CREATE TABLE " + ExperimentProvider.NOTIFICATION_TABLE_NAME + " ("
+ NotificationHolderColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NotificationHolderColumns.ALARM_TIME + " INTEGER, "
+ NotificationHolderColumns.EXPERIMENT_ID + " INTEGER, "
+ NotificationHolderColumns.NOTICE_COUNT + " INTEGER, "
+ NotificationHolderColumns.TIMEOUT_MILLIS + " INTEGER"
+ ");");
// insertValues(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(ExperimentProvider.TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ".");
if (oldVersion <= 8) {
db.execSQL("ALTER TABLE " + ExperimentProvider.INPUTS_TABLE_NAME + " ADD "
+ InputColumns.MULTISELECT + " INTEGER default 0"
+ ";");
}
if (oldVersion <= 9) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.USER_EDITABLE + " INTEGER default 1"
+ ";");
}
if (oldVersion <= 10) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER default 0"
+ ";");
}
if (oldVersion <= 11) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.VERSION + " INTEGER default 0"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.EVENTS_TABLE_NAME + " ADD "
+ EventColumns.EXPERIMENT_VERSION + " INTEGER default 0"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.TIME_OUT + " INTEGER"
+ ";");
}
if (oldVersion <= 12) {
db.execSQL("ALTER TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + " ADD "
+ ExperimentColumns.JSON + " TEXT "
+ ";");
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<Experiment> joined = eu.getJoinedExperiments();
for (Experiment experiment : joined) {
eu.updateJoinedExperiment(experiment);
}
}
if (oldVersion <= 13) {
HashMap<Integer, String> startDatePairs = convertDateLongsToStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.START_DATE, ExperimentColumns._ID);
HashMap<Integer, String> endDatePairs = convertDateLongsToStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.END_DATE, ExperimentColumns._ID);
HashMap<Integer, String> joinDatePairs = convertDateLongsToTzStrings(db,
ExperimentProvider.EXPERIMENTS_TABLE_NAME,
ExperimentColumns.JOIN_DATE, ExperimentColumns._ID);
createTruncatedExperimentsTable(db);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, startDatePairs,
ExperimentColumns.START_DATE, ExperimentColumns._ID);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, endDatePairs,
ExperimentColumns.END_DATE, ExperimentColumns._ID);
insertNewDateColumnWithData(db, ExperimentProvider.EXPERIMENTS_TABLE_NAME, joinDatePairs,
ExperimentColumns.JOIN_DATE, ExperimentColumns._ID);
}
if (oldVersion <= 14) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.MINIMUM_BUFFER + " INTEGER"
+ ";");
}
if (oldVersion <= 15) {
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<Experiment> joined = eu.getJoinedExperiments();
for (Experiment experiment : joined) {
//verify that feedbackType is correct
if (experiment.getFeedbackType() == null || experiment.getFeedbackType() == FeedbackDAO.FEEDBACK_TYPE_RETROSPECTIVE) { // the default
eu.loadFeedbackForExperiment(experiment);
// if it is our default value make sure that it is not actually custom code.
if (!FeedbackDAO.DEFAULT_FEEDBACK_MSG.equals(experiment.getFeedback().get(0).getText())) {
experiment.setFeedbackType(FeedbackDAO.FEEDBACK_TYPE_CUSTOM);
eu.updateJoinedExperiment(experiment);
}
}
}
eu.deleteExperimentCachesOnDisk();
}
if (oldVersion <= 16) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SNOOZE_COUNT + " INTEGER"
+ ";");
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SNOOZE_TIME + " INTEGER"
+ ";");
}
if (oldVersion <= 17) {
db.execSQL("ALTER TABLE " + ExperimentProvider.SCHEDULES_TABLE_NAME + " ADD "
+ SignalScheduleColumns.SIGNAL_TIMES + " INTEGER"
+ ";");
migrateExistingLongTimeValuesToSignalTimeValues();
}
}
private void migrateExistingLongTimeValuesToSignalTimeValues() {
ExperimentProviderUtil eu = new ExperimentProviderUtil(context);
List<SignalSchedule> schedules = eu.getAllSchedules();
for (SignalSchedule schedule : schedules) {
if (schedule.getScheduleType() != SignalScheduleDAO.SELF_REPORT &&
schedule.getScheduleType() != SignalScheduleDAO.ESM ) {
List<SignalTime> signalTimes = Lists.newArrayList();
List<Long> times = schedule.getTimes();
for (Long time : times) {
signalTimes.add(new SignalTime(SignalTimeDAO.FIXED_TIME,
SignalTimeDAO.OFFSET_BASIS_SCHEDULED_TIME,
(int)time.longValue(),
SignalTimeDAO.MISSED_BEHAVIOR_USE_SCHEDULED_TIME,
0, ""));
}
schedule.setSignalTimes(signalTimes);
eu.updateSchedule(schedule);
}
}
}
private static HashMap<Integer, String> convertDateLongsToStrings(SQLiteDatabase db,
String tableName,
String dateCol, String refCol) {
String[] columns = {dateCol, refCol};
HashMap<Integer, String> data = new HashMap<Integer, String>();
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol));
if (longVal != null) {
String dateStr = TimeUtil.formatDate(longVal);
Integer id = cursor.getInt(cursor.getColumnIndex(refCol));
data.put(id, dateStr);
}
}
}
} finally {
cursor.close();
}
return data;
}
private static HashMap<Integer, String> convertDateLongsToTzStrings(SQLiteDatabase db,
String tableName,
String dateCol, String refCol) {
String[] columns = {dateCol, refCol};
HashMap<Integer, String> data = new HashMap<Integer, String>();
Cursor cursor = db.query(tableName, columns, null, null, null, null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
Long longVal = cursor.getLong(cursor.getColumnIndex(dateCol));
if (longVal != null) {
String dateStr = TimeUtil.formatDateWithZone(longVal);
Integer id = cursor.getInt(cursor.getColumnIndex(refCol));
data.put(id, dateStr);
}
}
}
} finally {
cursor.close();
}
return data;
}
private static void createTruncatedExperimentsTable(SQLiteDatabase db) {
String tempTable = "tempTable";
db.execSQL("CREATE TABLE " + tempTable + " ("
+ ExperimentColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ExperimentColumns.SERVER_ID + " INTEGER,"
+ ExperimentColumns.TITLE + " TEXT, "
+ ExperimentColumns.VERSION + " INTEGER,"
+ ExperimentColumns.DESCRIPTION + " TEXT, "
+ ExperimentColumns.CREATOR + " TEXT, "
+ ExperimentColumns.INFORMED_CONSENT + " TEXT, "
+ ExperimentColumns.HASH + " TEXT, "
+ ExperimentColumns.FIXED_DURATION + " INTEGER, "
+ ExperimentColumns.QUESTIONS_CHANGE + " INTEGER, "
+ ExperimentColumns.ICON + " BLOB, "
+ ExperimentColumns.WEB_RECOMMENDED + " INTEGER, "
+ ExperimentColumns.JSON + " TEXT "
+ ");");
db.execSQL("INSERT INTO " + tempTable + " (" +
ExperimentColumns._ID + ", " +
ExperimentColumns.SERVER_ID + ", " +
ExperimentColumns.TITLE + ", " +
ExperimentColumns.VERSION + ", " +
ExperimentColumns.DESCRIPTION + ", " +
ExperimentColumns.CREATOR + ", " +
ExperimentColumns.INFORMED_CONSENT + ", " +
ExperimentColumns.HASH + ", " +
ExperimentColumns.FIXED_DURATION + ", " +
ExperimentColumns.QUESTIONS_CHANGE + ", " +
ExperimentColumns.ICON + ", " +
ExperimentColumns.WEB_RECOMMENDED + ", " +
ExperimentColumns.JSON +
") " + "SELECT " +
ExperimentColumns._ID + ", " +
ExperimentColumns.SERVER_ID + ", " +
ExperimentColumns.TITLE + ", " +
ExperimentColumns.VERSION + ", " +
ExperimentColumns.DESCRIPTION + ", " +
ExperimentColumns.CREATOR + ", " +
ExperimentColumns.INFORMED_CONSENT + ", " +
ExperimentColumns.HASH + ", " +
ExperimentColumns.FIXED_DURATION + ", " +
ExperimentColumns.QUESTIONS_CHANGE + ", " +
ExperimentColumns.ICON + ", " +
ExperimentColumns.WEB_RECOMMENDED + ", " +
ExperimentColumns.JSON +
" FROM " + ExperimentProvider.EXPERIMENTS_TABLE_NAME + ";");
db.execSQL("DROP TABLE " + ExperimentProvider.EXPERIMENTS_TABLE_NAME);
db.execSQL("ALTER TABLE " + tempTable + " RENAME TO " + ExperimentProvider.EXPERIMENTS_TABLE_NAME);
}
private static void insertNewDateColumnWithData(SQLiteDatabase db, String tableName,
HashMap<Integer,String> data,
String dateCol, String refCol) {
db.execSQL("ALTER TABLE " + tableName + " ADD " + dateCol + " TEXT " + ";");
for (Map.Entry<Integer, String> entry : data.entrySet()) {
db.execSQL("UPDATE " + tableName +
" SET " + dateCol + " = " + "\'" + entry.getValue() + "\'" +
" WHERE " + refCol + " = " + entry.getKey() + ";");
}
}
}
| fix for Android migrate db problem with schedule.times vs schedule.signalTimes
| Paco/src/com/google/android/apps/paco/DatabaseHelper.java | fix for Android migrate db problem with schedule.times vs schedule.signalTimes |
|
Java | apache-2.0 | 3e8c4a39fdcecdc4776245c101364d4cb20f9c06 | 0 | ummels/vavr,amygithub/vavr,ummels/vavr,dx-pbuckley/vavr,amygithub/vavr,dx-pbuckley/vavr | /* / \____ _ ______ _____ / \____ ____ _____
* / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang
* _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich
* /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.control.None;
import javaslang.control.Option;
import javaslang.control.Some;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.*;
import java.util.stream.Collector;
/**
* A {@code Queue} stores elements allowing a first-in-first-out (FIFO) retrieval.
* <p>
* Queue API:
*
* <ul>
* <li>{@link #dequeue()}</li>
* <li>{@link #dequeueOption()}</li>
* <li>{@link #enqueue(Object)}</li>
* <li>{@link #enqueue(Object[])}</li>
* <li>{@link #enqueueAll(Iterable)}</li>
* <li>{@link #peek()}</li>
* <li>{@link #peekOption()}</li>
* </ul>
*
* A Queue internally consists of a front List containing the front elements of the Queue in the correct order and a
* rear List containing the rear elements of the Queue in reverse order.
* <p>
* See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 42 ff.). Cambridge, 2003.
*
* @param <T> Component type of the Queue
* @since 1.3.0
*/
public class Queue<T> implements Seq<T>implements Serializable {
private static final long serialVersionUID = 1L;
private static final Queue<?> EMPTY = new Queue<>(List.nil(), List.nil());
private final List<T> front;
private final List<T> rear;
/**
* Creates a Queue consisting of a front List and a rear List.
* <p>
* For a {@code Queue(front, rear)} the following invariant holds: {@code Queue is empty <=> front is empty}.
* In other words: If the Queue is not empty, the front List contains at least one element.
*
* @param front A List of front elements, in correct order.
* @param rear A List of rear elements, in reverse order.
*/
private Queue(List<T> front, List<T> rear) {
final boolean isFrontEmpty = front.isEmpty();
this.front = isFrontEmpty ? rear.reverse() : front;
this.rear = isFrontEmpty ? front : rear;
}
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.Queue}
* .
*
* @param <T> Component type of the Queue.
* @return A javaslang.collection.Queue Collector.
*/
public static <T> Collector<T, ArrayList<T>, Queue<T>> collector() {
final Supplier<ArrayList<T>> supplier = ArrayList::new;
final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<T>, Queue<T>> finisher = Queue::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns the empty Queue.
*
* @param <T> Component type
* @return The empty Queue.
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> empty() {
return (Queue<T>) EMPTY;
}
/**
* Returns a singleton {@code Queue}, i.e. a {@code Queue} of one element.
*
* @param element An element.
* @param <T> The component type
* @return A new Queue instance containing the given element
*/
public static <T> Queue<T> of(T element) {
return new Queue<>(List.of(element), List.nil());
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements Zero or more elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SafeVarargs
@SuppressWarnings({"unchecked", "varargs"})
public static <T> Queue<T> of(T... elements) {
Objects.requireNonNull(elements, "elements is null");
return new Queue<>(List.of(elements), List.nil());
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements An Iterable of elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> ofAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (elements instanceof Queue) {
return (Queue<T>) elements;
} else if (elements instanceof List) {
return new Queue<>((List<T>) elements, List.nil());
} else {
return new Queue<>(List.ofAll(elements), List.nil());
}
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of int values as specified or {@code Nil} if {@code from >= toExclusive}
*/
public static Queue<Integer> range(int from, int toExclusive) {
return new Queue<>(List.range(from, toExclusive), List.nil());
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive}.
*
* @param from the first number
* @param toInclusive the last number
* @return a range of int values as specified or {@code Nil} if {@code from > toInclusive}
*/
public static Queue<Integer> rangeClosed(int from, int toInclusive) {
return new Queue<>(List.rangeClosed(from, toInclusive), List.nil());
}
/**
* Removes an element from this Queue.
*
* @return a tuple containing the first element and the remaining elements of this Queue
* @throws java.util.NoSuchElementException if this Queue is empty
*/
public Tuple2<T, Queue<T>> dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("dequeue of empty Queue");
} else {
return Tuple.of(head(), tail());
}
}
/**
* Removes an element from this Queue.
*
* @return {@code None} if this Queue is empty, otherwise {@code Some} {@code Tuple} containing the first element and the remaining elements of this Queue
*/
public Option<Tuple2<T, Queue<T>>> dequeueOption() {
return isEmpty() ? None.instance() : new Some<>(dequeue());
}
/**
* Enqueues a new element.
*
* @param element The new element
* @return a new {@code Queue} instance, containing the new element
*/
public Queue<T> enqueue(T element) {
return new Queue<>(front, rear.prepend(element));
}
/**
* Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
* the first which will be retrieved.
*
* @param elements Elements, may be empty
* @return a new {@code Queue} instance, containing the new elements
* @throws NullPointerException if elements is null
*/
public Queue<T> enqueue(T... elements) {
List<T> temp = rear;
for (T element : elements) {
temp = temp.prepend(element);
}
return new Queue<>(front, temp);
}
/**
* Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
* the first which will be retrieved.
*
* @param elements An Iterable of elements, may be empty
* @return a new {@code Queue} instance, containing the new elements
* @throws NullPointerException if elements is null
*/
public Queue<T> enqueueAll(Iterable<? extends T> elements) {
List<T> temp = rear;
for (T element : elements) {
temp = temp.prepend(element);
}
return new Queue<>(front, temp);
}
/**
* Returns the first element without modifying the Queue.
*
* @return the first element
* @throws java.util.NoSuchElementException if this Queue is empty
*/
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("peek of empty Queue");
} else {
return front.head();
}
}
/**
* Returns the first element without modifying the Queue.
*
* @return {@code None} if this Queue is empty, otherwise a {@code Some} containing the first element
*/
public Option<T> peekOption() {
return isEmpty() ? None.instance() : new Some<>(front.head());
}
// -- Adjusted return types of Seq methods
@Override
public Queue<T> append(T element) {
return enqueue(element);
}
@Override
public Queue<T> appendAll(Iterable<? extends T> elements) {
return enqueueAll(elements);
}
@Override
public Queue<T> clear() {
return Queue.empty();
}
@Override
public Queue<Queue<T>> combinations() {
return toList().combinations().map(Queue::ofAll).toQueue();
}
@Override
public Queue<Queue<T>> combinations(int k) {
return toList().combinations(k).map(Queue::ofAll).toQueue();
}
@Override
public Queue<T> distinct() {
return toList().distinct().toQueue();
}
@Override
public <U> Queue<T> distinct(Function<? super T, ? extends U> keyExtractor) {
return toList().distinct(keyExtractor).toQueue();
}
@Override
public Queue<T> drop(int n) {
return new Queue<>(front.drop(n), rear.dropRight(n - front.length()));
}
@Override
public Queue<T> dropRight(int n) {
return new Queue<>(front.dropRight(n), rear.drop(n - front.length()));
}
@Override
public Queue<T> dropWhile(Predicate<? super T> predicate) {
return toList().dropWhile(predicate).toQueue();
}
@Override
public Queue<T> filter(Predicate<? super T> predicate) {
return toList().filter(predicate).toQueue();
}
@Override
public Queue<T> findAll(Predicate<? super T> predicate) {
return toList().findAll(predicate).toQueue();
}
@Override
public <U> Queue<U> flatMap(Function<? super T, ? extends Iterable<U>> mapper) {
}
@Override
public <U> Queue<U> flatten(Function<? super T, ? extends Iterable<U>> f) {
}
@Override
public T get(int index) {
final int length = front.length();
if (index < length) {
return front.get(index);
} else {
final int rearIndex = index - length;
final int rearLength = rear.length();
if (rearIndex < rearLength) {
final int reverseRearIndex = rearLength - rearIndex - 1;
return rear.get(reverseRearIndex);
} else {
throw new IndexOutOfBoundsException(String.format("get(%s) on Queue of length %s", index, length()));
}
}
}
@Override
public Queue<Queue<T>> grouped(int size) {
return toList().grouped(size).map(Queue::ofAll).toQueue();
}
@Override
public T head() {
if (isEmpty()) {
throw new NoSuchElementException("head of empty queue");
} else {
return front.head();
}
}
@Override
public int indexOf(T element) {
final int frontIndex = front.indexOf(element);
if (frontIndex != -1) {
return frontIndex;
} else {
// we need to reverse because we search the first occurrence
final int rearIndex = rear.reverse().indexOf(element);
return (rearIndex == -1) ? -1 : rearIndex + front.length();
}
}
@Override
public Queue<T> init() {
if (isEmpty()) {
throw new NoSuchElementException("init of empty Queue");
} else if (rear.isEmpty()) {
return new Queue<>(front.init(), rear);
} else {
return new Queue<>(front, rear.tail());
}
}
@Override
public Option<Queue<T>> initOption() {
return isEmpty() ? None.instance() : new Some<>(init());
}
@Override
public Queue<T> insert(int index, T element) {
}
@Override
public Queue<T> insertAll(int index, Iterable<? extends T> elements) {
}
@Override
public Queue<T> intersperse(T element) {
}
@Override
public int lastIndexOf(T element) {
}
@Override
public <U> Queue<U> map(Function<? super T, ? extends U> mapper) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> partition(Predicate<? super T> predicate) {
}
@Override
public Queue<T> peek(Consumer<? super T> action) {
}
@Override
public Queue<Queue<T>> permutations() {
}
@Override
public Queue<T> prepend(T element) {
}
@Override
public Queue<T> prependAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> remove(T element) {
}
@Override
public Queue<T> removeAll(T element) {
}
@Override
public Queue<T> removeAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> replace(T currentElement, T newElement) {
}
@Override
public Queue<T> replaceAll(T currentElement, T newElement) {
}
@Override
public Queue<T> replaceAll(UnaryOperator<T> operator) {
}
@Override
public Queue<T> retainAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> reverse() {
}
@Override
public Queue<T> set(int index, T element) {
}
@Override
public Queue<Queue<T>> sliding(int size) {
}
@Override
public Queue<Queue<T>> sliding(int size, int step) {
}
@Override
public Queue<T> sort() {
}
@Override
public Queue<T> sort(Comparator<? super T> comparator) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> span(Predicate<? super T> predicate) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> splitAt(int n) {
}
@Override
public Queue<T> subsequence(int beginIndex) {
}
@Override
public Queue<T> subsequence(int beginIndex, int endIndex) {
}
@Override
public Queue<T> tail() {
}
@Override
public Option<Queue<T>> tailOption() {
return isEmpty() ? None.instance() : new Some<>(tail());
}
@Override
public Queue<T> take(int n) {
final int frontLength = front.length();
if (n < frontLength) {
return new Queue<>(front.take(n), List.nil());
} else if (n == frontLength) {
return new Queue<>(front, List.nil());
} else {
return new Queue<>(front, rear.takeRight(n - frontLength));
}
}
@Override
public Queue<T> takeRight(int n) {
final int rearLength = rear.length();
if (n < rearLength) {
return new Queue<>(rear.take(n).reverse(), List.nil());
} else if (n == rearLength) {
return new Queue<>(rear.reverse(), List.nil());
} else {
return new Queue<>(front.takeRight(n - rearLength), rear);
}
}
@Override
public Queue<T> takeWhile(Predicate<? super T> predicate) {
}
@Override
public <T1, T2> Tuple2<Queue<T1>, Queue<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
}
@Override
public <U> Queue<Tuple2<T, U>> zip(Iterable<U> that) {
}
@Override
public <U> Queue<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem) {
}
@Override
public Queue<Tuple2<T, Integer>> zipWithIndex() {
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Queue) {
List<?> list1 = this.toList();
List<?> list2 = ((Queue<?>) o).toList();
while (!list1.isEmpty() && !list2.isEmpty()) {
final boolean isEqual = Objects.equals(list1.head(), list2.head());
if (!isEqual) {
return false;
}
list1 = list1.tail();
list2 = list2.tail();
}
return list1.isEmpty() && list2.isEmpty();
} else {
return false;
}
}
@Override
public int hashCode() {
int hashCode = 1;
for (T element : this) {
hashCode = 31 * hashCode + Objects.hashCode(element);
}
return hashCode;
}
@Override
public String toString() {
return map(String::valueOf).join(", ", "Queue(", ")");
}
}
| src/main/java/javaslang/collection/Queue.java | /* / \____ _ ______ _____ / \____ ____ _____
* / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang
* _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich
* /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.Tuple;
import javaslang.Tuple2;
import javaslang.control.None;
import javaslang.control.Option;
import javaslang.control.Some;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.*;
import java.util.stream.Collector;
/**
* A {@code Queue} stores elements allowing a first-in-first-out (FIFO) retrieval.
* <p>
* Queue API:
*
* <ul>
* <li>{@link #dequeue()}</li>
* <li>{@link #dequeueOption()}</li>
* <li>{@link #enqueue(Object)}</li>
* <li>{@link #enqueue(Object[])}</li>
* <li>{@link #enqueueAll(Iterable)}</li>
* <li>{@link #peek()}</li>
* <li>{@link #peekOption()}</li>
* </ul>
*
* A Queue internally consists of a front List containing the front elements of the Queue in the correct order and a
* rear List containing the rear elements of the Queue in reverse order.
* <p>
* See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 42 ff.). Cambridge, 2003.
*
* @param <T> Component type of the Queue
* @since 1.3.0
*/
public class Queue<T> implements Seq<T>implements Serializable {
private static final long serialVersionUID = 1L;
private static final Queue<?> EMPTY = new Queue<>(List.nil(), List.nil());
private final List<T> front;
private final List<T> rear;
/**
* Creates a Queue consisting of a front List and a rear List.
* <p>
* For a {@code Queue(front, rear)} the following invariant holds: {@code Queue is empty <=> front is empty}.
* In other words: If the Queue is not empty, the front List contains at least one element.
*
* @param front A List of front elements, in correct order.
* @param rear A List of rear elements, in reverse order.
*/
private Queue(List<T> front, List<T> rear) {
final boolean isFrontEmpty = front.isEmpty();
this.front = isFrontEmpty ? rear.reverse() : front;
this.rear = isFrontEmpty ? front : rear;
}
/**
* Returns a {@link java.util.stream.Collector} which may be used in conjunction with
* {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.Queue}
* .
*
* @param <T> Component type of the Queue.
* @return A javaslang.collection.Queue Collector.
*/
public static <T> Collector<T, ArrayList<T>, Queue<T>> collector() {
final Supplier<ArrayList<T>> supplier = ArrayList::new;
final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
final BinaryOperator<ArrayList<T>> combiner = (left, right) -> {
left.addAll(right);
return left;
};
final Function<ArrayList<T>, Queue<T>> finisher = Queue::ofAll;
return Collector.of(supplier, accumulator, combiner, finisher);
}
/**
* Returns the empty Queue.
*
* @param <T> Component type
* @return The empty Queue.
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> empty() {
return (Queue<T>) EMPTY;
}
/**
* Returns a singleton {@code Queue}, i.e. a {@code Queue} of one element.
*
* @param element An element.
* @param <T> The component type
* @return A new Queue instance containing the given element
*/
public static <T> Queue<T> of(T element) {
return new Queue<>(List.of(element), List.nil());
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements Zero or more elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SafeVarargs
@SuppressWarnings({"unchecked", "varargs"})
public static <T> Queue<T> of(T... elements) {
Objects.requireNonNull(elements, "elements is null");
return new Queue<>(List.of(elements), List.nil());
}
/**
* Creates a Queue of the given elements.
*
* @param <T> Component type of the Queue.
* @param elements An Iterable of elements.
* @return A queue containing the given elements in the same order.
* @throws NullPointerException if {@code elements} is null
*/
@SuppressWarnings("unchecked")
public static <T> Queue<T> ofAll(Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
if (elements instanceof Queue) {
return (Queue<T>) elements;
} else if (elements instanceof List) {
return new Queue<>((List<T>) elements, List.nil());
} else {
return new Queue<>(List.ofAll(elements), List.nil());
}
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1}.
*
* @param from the first number
* @param toExclusive the last number + 1
* @return a range of int values as specified or {@code Nil} if {@code from >= toExclusive}
*/
public static Queue<Integer> range(int from, int toExclusive) {
return new Queue<>(List.range(from, toExclusive), List.nil());
}
/**
* Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive}.
*
* @param from the first number
* @param toInclusive the last number
* @return a range of int values as specified or {@code Nil} if {@code from > toInclusive}
*/
public static Queue<Integer> rangeClosed(int from, int toInclusive) {
return new Queue<>(List.rangeClosed(from, toInclusive), List.nil());
}
/**
* Removes an element from this Queue.
*
* @return a tuple containing the first element and the remaining elements of this Queue
* @throws java.util.NoSuchElementException if this Queue is empty
*/
public Tuple2<T, Queue<T>> dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("dequeue of empty Queue");
} else {
return Tuple.of(head(), tail());
}
}
/**
* Removes an element from this Queue.
*
* @return {@code None} if this Queue is empty, otherwise {@code Some} {@code Tuple} containing the first element and the remaining elements of this Queue
*/
public Option<Tuple2<T, Queue<T>>> dequeueOption() {
return isEmpty() ? None.instance() : new Some<>(dequeue());
}
/**
* Enqueues a new element.
*
* @param element The new element
* @return a new {@code Queue} instance, containing the new element
*/
public Queue<T> enqueue(T element) {
return new Queue<>(front, rear.prepend(element));
}
/**
* Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
* the first which will be retrieved.
*
* @param elements Elements, may be empty
* @return a new {@code Queue} instance, containing the new elements
* @throws NullPointerException if elements is null
*/
public Queue<T> enqueue(T... elements) {
List<T> temp = rear;
for (T element : elements) {
temp = temp.prepend(element);
}
return new Queue<>(front, temp);
}
/**
* Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is
* the first which will be retrieved.
*
* @param elements An Iterable of elements, may be empty
* @return a new {@code Queue} instance, containing the new elements
* @throws NullPointerException if elements is null
*/
public Queue<T> enqueueAll(Iterable<? extends T> elements) {
List<T> temp = rear;
for (T element : elements) {
temp = temp.prepend(element);
}
return new Queue<>(front, temp);
}
/**
* Returns the first element without modifying the Queue.
*
* @return the first element
* @throws java.util.NoSuchElementException if this Queue is empty
*/
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("peek of empty Queue");
} else {
return front.head();
}
}
/**
* Returns the first element without modifying the Queue.
*
* @return {@code None} if this Queue is empty, otherwise a {@code Some} containing the first element
*/
public Option<T> peekOption() {
return isEmpty() ? None.instance() : new Some<>(front.head());
}
// -- Adjusted return types of Seq methods
@Override
public Queue<T> append(T element) {
return enqueue(element);
}
@Override
public Queue<T> appendAll(Iterable<? extends T> elements) {
return enqueueAll(elements);
}
@Override
public Queue<T> clear() {
return Queue.empty();
}
@Override
public Queue<Queue<T>> combinations() {
return toList().combinations().map(Queue::ofAll).toQueue();
}
@Override
public Queue<Queue<T>> combinations(int k) {
return toList().combinations(k).map(Queue::ofAll).toQueue();
}
@Override
public Queue<T> distinct() {
return toList().distinct().toQueue();
}
@Override
public <U> Queue<T> distinct(Function<? super T, ? extends U> keyExtractor) {
return toList().distinct(keyExtractor).toQueue();
}
@Override
public Queue<T> drop(int n) {
return new Queue<>(front.drop(n), rear.dropRight(n - front.length()));
}
@Override
public Queue<T> dropRight(int n) {
return new Queue<>(front.dropRight(n), rear.drop(n - front.length()));
}
@Override
public Queue<T> dropWhile(Predicate<? super T> predicate) {
return toList().dropWhile(predicate).toQueue();
}
@Override
public Queue<T> filter(Predicate<? super T> predicate) {
return toList().filter(predicate).toQueue();
}
@Override
public Queue<T> findAll(Predicate<? super T> predicate) {
return toList().findAll(predicate).toQueue();
}
@Override
public <U> Queue<U> flatMap(Function<? super T, ? extends Iterable<U>> mapper) {
}
@Override
public <U> Queue<U> flatten(Function<? super T, ? extends Iterable<U>> f) {
}
@Override
public T get(int index) {
final int length = front.length();
if (index < length) {
return front.get(index);
} else {
final int rearIndex = index - length;
final int rearLength = rear.length();
if (rearIndex < rearLength) {
final int reverseRearIndex = rearLength - rearIndex - 1;
return rear.get(reverseRearIndex);
} else {
throw new IndexOutOfBoundsException(String.format("get(%s) on Queue of length %s", index, length()));
}
}
}
@Override
public Queue<Queue<T>> grouped(int size) {
}
@Override
public T head() {
if (isEmpty()) {
throw new NoSuchElementException("head of empty queue");
} else {
return front.head();
}
}
@Override
public int indexOf(T element) {
}
@Override
public Queue<T> init() {
if (isEmpty()) {
throw new NoSuchElementException("init of empty Queue");
} else if (rear.isEmpty()) {
return new Queue<>(front.init(), rear);
} else {
return new Queue<>(front, rear.tail());
}
}
@Override
public Option<Queue<T>> initOption() {
return isEmpty() ? None.instance() : new Some<>(init());
}
@Override
public Queue<T> insert(int index, T element) {
}
@Override
public Queue<T> insertAll(int index, Iterable<? extends T> elements) {
}
@Override
public Queue<T> intersperse(T element) {
}
@Override
public int lastIndexOf(T element) {
}
@Override
public <U> Queue<U> map(Function<? super T, ? extends U> mapper) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> partition(Predicate<? super T> predicate) {
}
@Override
public Queue<T> peek(Consumer<? super T> action) {
}
@Override
public Queue<Queue<T>> permutations() {
}
@Override
public Queue<T> prepend(T element) {
}
@Override
public Queue<T> prependAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> remove(T element) {
}
@Override
public Queue<T> removeAll(T element) {
}
@Override
public Queue<T> removeAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> replace(T currentElement, T newElement) {
}
@Override
public Queue<T> replaceAll(T currentElement, T newElement) {
}
@Override
public Queue<T> replaceAll(UnaryOperator<T> operator) {
}
@Override
public Queue<T> retainAll(Iterable<? extends T> elements) {
}
@Override
public Queue<T> reverse() {
}
@Override
public Queue<T> set(int index, T element) {
}
@Override
public Queue<Queue<T>> sliding(int size) {
}
@Override
public Queue<Queue<T>> sliding(int size, int step) {
}
@Override
public Queue<T> sort() {
}
@Override
public Queue<T> sort(Comparator<? super T> comparator) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> span(Predicate<? super T> predicate) {
}
@Override
public Tuple2<Queue<T>, Queue<T>> splitAt(int n) {
}
@Override
public Queue<T> subsequence(int beginIndex) {
}
@Override
public Queue<T> subsequence(int beginIndex, int endIndex) {
}
@Override
public Queue<T> tail() {
}
@Override
public Option<Queue<T>> tailOption() {
return isEmpty() ? None.instance() : new Some<>(tail());
}
@Override
public Queue<T> take(int n) {
}
@Override
public Queue<T> takeRight(int n) {
}
@Override
public Queue<T> takeWhile(Predicate<? super T> predicate) {
}
@Override
public <T1, T2> Tuple2<Queue<T1>, Queue<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) {
}
@Override
public <U> Queue<Tuple2<T, U>> zip(Iterable<U> that) {
}
@Override
public <U> Queue<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem) {
}
@Override
public Queue<Tuple2<T, Integer>> zipWithIndex() {
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof Queue) {
List<?> list1 = this.toList();
List<?> list2 = ((Queue<?>) o).toList();
while (!list1.isEmpty() && !list2.isEmpty()) {
final boolean isEqual = Objects.equals(list1.head(), list2.head());
if (!isEqual) {
return false;
}
list1 = list1.tail();
list2 = list2.tail();
}
return list1.isEmpty() && list2.isEmpty();
} else {
return false;
}
}
@Override
public int hashCode() {
int hashCode = 1;
for (T element : this) {
hashCode = 31 * hashCode + Objects.hashCode(element);
}
return hashCode;
}
@Override
public String toString() {
return map(String::valueOf).join(", ", "Queue(", ")");
}
}
| implemented grouped, indexOf, take and takeRight
| src/main/java/javaslang/collection/Queue.java | implemented grouped, indexOf, take and takeRight |
|
Java | apache-2.0 | fe6e7bc1aea49139a83979f1854ce8a38b679f2d | 0 | Mobicents/sipunit,AndreasMager/sipunit,RestComm/sipunit | /*
* Created on April 21, 2005
*
* Copyright 2005 CafeSip.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.cafesip.sipunit.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Properties;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.TimeoutEvent;
import javax.sip.address.Address;
import javax.sip.address.AddressFactory;
import javax.sip.address.URI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.ContentLengthHeader;
import javax.sip.header.ContentTypeHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.PriorityHeader;
import javax.sip.header.ReasonHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipMessage;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipResponse;
import org.cafesip.sipunit.SipSession;
import org.cafesip.sipunit.SipStack;
import org.cafesip.sipunit.SipTestCase;
import org.cafesip.sipunit.SipTransaction;
/**
* This class tests SipUnit API methods.
*
* Tests in this class do not require a proxy/registrar server. Messaging
* between UACs is direct.
*
* @author Becky McElroy
*
*/
public class TestNoProxy extends SipTestCase
{
private SipStack sipStack;
private SipPhone ua;
private int myPort;
private String testProtocol;
private static final Properties defaultProperties = new Properties();
static
{
String host = null;
try
{
host = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
host = "localhost";
}
defaultProperties.setProperty("javax.sip.IP_ADDRESS", host);
defaultProperties.setProperty("javax.sip.STACK_NAME", "testAgent");
defaultProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
defaultProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
"testAgent_debug.txt");
defaultProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
"testAgent_log.txt");
defaultProperties
.setProperty("gov.nist.javax.sip.READ_TIMEOUT", "1000");
defaultProperties.setProperty(
"gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS", "false");
defaultProperties.setProperty("sipunit.trace", "true");
defaultProperties.setProperty("sipunit.test.port", "5060");
defaultProperties.setProperty("sipunit.test.protocol", "udp");
}
private Properties properties = new Properties(defaultProperties);
public TestNoProxy(String arg0)
{
super(arg0);
properties.putAll(System.getProperties());
try
{
myPort = Integer.parseInt(properties
.getProperty("sipunit.test.port"));
}
catch (NumberFormatException e)
{
myPort = 5060;
}
testProtocol = properties.getProperty("sipunit.test.protocol");
}
/*
* @see SipTestCase#setUp()
*/
public void setUp() throws Exception
{
try
{
sipStack = new SipStack(testProtocol, myPort, properties);
SipStack.setTraceEnabled(properties.getProperty("sipunit.trace")
.equalsIgnoreCase("true")
|| properties.getProperty("sipunit.trace")
.equalsIgnoreCase("on"));
}
catch (Exception ex)
{
fail("Exception: " + ex.getClass().getName() + ": "
+ ex.getMessage());
throw ex;
}
try
{
ua = sipStack.createSipPhone("sip:[email protected]");
}
catch (Exception ex)
{
fail("Exception creating SipPhone: " + ex.getClass().getName()
+ ": " + ex.getMessage());
throw ex;
}
}
/*
* @see SipTestCase#tearDown()
*/
public void tearDown() throws Exception
{
ua.dispose();
sipStack.dispose();
}
public void testSendInviteWithRouteHeader() // add a Route Header to the
// INVITE myself
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
AddressFactory addr_factory = ua.getParent().getAddressFactory();
HeaderFactory hdr_factory = ua.getParent().getHeaderFactory();
Request invite = ua.getParent().getMessageFactory().createRequest(
"INVITE sip:[email protected] SIP/2.0 ");
invite.addHeader(ua.getParent().getSipProvider().getNewCallId());
invite.addHeader(hdr_factory.createCSeqHeader((long)1, Request.INVITE));
invite.addHeader(hdr_factory.createFromHeader(ua.getAddress(), ua
.generateNewTag()));
Address to_address = addr_factory.createAddress(addr_factory
.createURI("sip:[email protected]"));
invite.addHeader(hdr_factory.createToHeader(to_address, null));
Address contact_address = addr_factory.createAddress("sip:amit@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort);
invite.addHeader(hdr_factory.createContactHeader(contact_address));
invite.addHeader(hdr_factory.createMaxForwardsHeader(5));
ArrayList via_headers = ua.getViaHeaders();
invite.addHeader((ViaHeader) via_headers.get(0));
// create and add the Route Header
Address route_address = addr_factory.createAddress("sip:becky@"
+ ub.getStackAddress() + ':'
+ myPort + '/' + testProtocol);
invite.addHeader(hdr_factory.createRouteHeader(route_address));
SipTransaction trans = ua.sendRequestWithTransaction(invite, false,
null);
assertNotNull(ua.format(), trans);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(500);
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1);
assertLastOperationSuccess(ub.format(), ub);
// ringing response sent
Thread.sleep(500);
response = ub.getParent().getMessageFactory().createResponse(
Response.OK, inc_req.getRequest());
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// answer response sent
Thread.sleep(500);
EventObject response_event = ua.waitResponse(trans, 10000);
// wait for trying
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received TRYING", Response.TRYING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// response(s) received, we're done
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testBothSides() // test initiateOugoingCall(), passing routing
// string
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall a = ua.createSipCall();
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
Thread.sleep(10);
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess("a initiate call - " + a.format(), a);
b.waitForIncomingCall(10000);
assertLastOperationSuccess("b wait incoming call - " + b.format(),
b);
b.sendIncomingCallResponse(Response.RINGING, null, -1);
assertLastOperationSuccess("b send RINGING - " + b.format(), b);
Thread.sleep(1000);
b.sendIncomingCallResponse(Response.OK, "Answer - Hello world", 0);
assertLastOperationSuccess("b send OK - " + b.format(), b);
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.RINGING,
a.getReturnCode());
assertNotNull("Default response reason not sent", a
.getLastReceivedResponse().getReasonPhrase());
assertEquals("Unexpected default reason", "Ringing", a
.getLastReceivedResponse().getReasonPhrase());
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 2nd response - " + a.format(), a);
assertEquals("Unexpected 2nd response received", Response.OK, a
.getReturnCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(1000);
a.listenForDisconnect();
assertLastOperationSuccess("a listen disc - " + a.format(), a);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(5000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
assertLastOperationSuccess("a respond to disc - " + a.format(), a);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testSipTestCaseMisc()
// in this test, user a is handled at the SipCall level and user b at the
// SipSession level (we send a body in the response)
{
try
{
SipCall a = ua.createSipCall();
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(50);
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess("a initiate call - " + a.format(), a);
RequestEvent inc_req = ub.waitRequest(10000);
assertNotNull(ub.format(), inc_req);
// call received
SipRequest req = new SipRequest(inc_req.getRequest());
/*******************************************************************
* Incoming request - header/body asserts
******************************************************************/
assertHeaderPresent(req, "Max-Forwards");
assertHeaderNotPresent(req, "Max-Forwardss");
assertHeaderNotContains(req, "Max-Forwards", "71");
assertHeaderContains(req, "Max-Forwards", "70");
assertBodyNotPresent(req);
assertBodyNotContains(req, "e");
/** ************************************************************* */
// send TRYING
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(100);
// send message with a body
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
response = ub.getParent().getMessageFactory().createResponse(
Response.RINGING, inc_req.getRequest()); // why OK
// doesn't
// work here?
response.setReasonPhrase("Hello World");
((ToHeader) response.getHeader(ToHeader.NAME)).setTag(to_tag);
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ContentTypeHeader ct = ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "sdp");
response.setContent("This is a test body", ct);
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// message with body sent
Thread.sleep(100);
a.waitOutgoingCallResponse(4000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
while (a.getReturnCode() == Response.TRYING)
{
a.waitOutgoingCallResponse(4000);
assertLastOperationSuccess("a wait nth response - "
+ a.format(), a);
}
/*******************************************************************
* Incoming response - header/body asserts
******************************************************************/
assertBodyPresent(a.getLastReceivedResponse());
assertBodyContains(a.getLastReceivedResponse(),
"his is a test body");
SipResponse resp = a.getLastReceivedResponse();
assertHeaderPresent(resp, "Contact");
assertHeaderNotPresent(resp, "Contacts");
assertHeaderNotContains(resp, "Contact", "amit");
assertHeaderContains(resp, "Contact", "becky");
/** **************************************************************** */
// ub needs to send BYE, so SipCall gets a request and can verify
// higher
// level request/response asserts
Request invite = inc_req.getRequest();
ContactHeader caller_contact = (ContactHeader) invite
.getHeader(ContactHeader.NAME);
FromHeader a_party = (FromHeader) invite.getHeader(FromHeader.NAME);
ToHeader b_party = (ToHeader) response.getHeader(ToHeader.NAME);
CSeqHeader cseq = ub.getParent().getHeaderFactory()
.createCSeqHeader(
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber(), Request.BYE);
Request bye = ub.getParent().getMessageFactory().createRequest(
caller_contact.getAddress().getURI(),
Request.BYE,
(CallIdHeader) invite.getHeader(CallIdHeader.NAME),
cseq,
ub.getParent().getHeaderFactory().createFromHeader(
b_party.getAddress(), b_party.getTag()),
ub.getParent().getHeaderFactory().createToHeader(
a_party.getAddress(), a_party.getTag()),
ub.getViaHeaders(),
ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(5));
bye.addHeader(ub.getParent().getHeaderFactory().createRouteHeader(
caller_contact.getAddress()));
assertTrue(a.listenForDisconnect());
assertTrue(ub.sendUnidirectionalRequest(bye, false));
assertTrue(a.waitForDisconnect(2000));
/*******************************************************************
* MessageListener level - methods, request/response assertions
******************************************************************/
SipRequest received_bye = a.getLastReceivedRequest();
assertNotNull(received_bye);
ArrayList received_requests = a.getAllReceivedRequests();
assertEquals(1, received_requests.size());
assertEquals(received_bye, received_requests.get(0));
SipResponse received_response = a.getLastReceivedResponse();
assertNotNull(received_response);
ArrayList received_responses = a.getAllReceivedResponses();
int num_responses = received_responses.size();
assertTrue(num_responses >= 2);
assertEquals(received_response, received_responses
.get(num_responses - 1));
assertResponseReceived(SipResponse.TRYING, a);
assertResponseReceived("Expected RINGING", SipResponse.RINGING, a);
assertResponseNotReceived(SipResponse.OK, a);
assertResponseNotReceived("Didn't expect OK", SipResponse.OK, a);
assertResponseReceived(SipResponse.RINGING, SipRequest.INVITE,
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
assertResponseReceived("Expected RINGING", SipResponse.RINGING,
SipRequest.INVITE, ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
assertResponseNotReceived(SipResponse.RINGING, SipRequest.INVITE,
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber() + 1, a);
assertResponseNotReceived("Didn't expect this",
SipResponse.RINGING, SipRequest.ACK, ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
long received_cseq_seqnum = ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME)).getSeqNumber();
assertRequestReceived(SipRequest.BYE, a);
assertRequestReceived(SipRequest.BYE, received_cseq_seqnum, a);
assertRequestReceived("Expected a BYE", SipRequest.BYE, a);
assertRequestReceived("Wrong CSEQ sequence number", SipRequest.BYE,
received_cseq_seqnum, a);
assertRequestNotReceived(SipRequest.INVITE, a);
assertRequestNotReceived("Didn't expect a NOTIFY",
SipRequest.NOTIFY, a);
assertRequestNotReceived(SipRequest.BYE, received_cseq_seqnum + 1,
a);
assertRequestNotReceived("Didn't expect a SUBSCRIBE",
SipRequest.SUBSCRIBE, received_cseq_seqnum, a);
/** ************************************************************* */
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallFail()
{
try
{
ua.makeCall("sip:[email protected]", SipResponse.RINGING, 1000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
assertLastOperationFail(ua.format(), ua);
assertEquals(ua.getReturnCode(), SipSession.TIMEOUT_OCCURRED);
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
/**
* Test: asynchronous SipPhone.makeCall() callee disc
*/
public void testMakeCallCalleeDisconnect() // test the nonblocking version
// of
// SipPhone.makeCall() - A CALLS B
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
// or assertNotNull(a)
assertTrue(b.waitForIncomingCall(5000));
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(400);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
b.sendIncomingCallResponse(Response.OK, "Answer - Hello world", 0);
Thread.sleep(500);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
a.listenForDisconnect();
Thread.sleep(100);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(3000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
/**
* Test: asynchronous SipPhone.makeCall() caller disc
*/
public void testMakeCallCallerDisconnect() // test the nonblocking version
// of
// SipPhone.makeCall() - A CALLS B
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testBothSidesCallerDisc() // test the blocking version of
// SipPhone.makeCall()
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallExtraJainsipParms() // test the blocking version of
// SipPhone.makeCall() with extra JAIN SIP parameters
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createPriorityHeader("5"));
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createContentTypeHeader("applicationn", "texxt"));
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ua.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ua.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createMaxForwardsHeader(62));
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol, addnl_hdrs,
replace_hdrs, "my body");
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallExtraStringParms() // test the blocking version of
// SipPhone.makeCall() with extra String parameters
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(new String("Priority: 5"));
ArrayList replace_hdrs = new ArrayList();
replace_hdrs.add(new String("Contact: <sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '>'));
replace_hdrs.add(new String("Max-Forwards: 62"));
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol, "my body",
"applicationn", "texxt", addnl_hdrs, replace_hdrs);
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testNonblockingMakeCallExtraJainsipParms() // test the
// nonblocking
// SipPhone.makeCall() with extra JAIN SIP parameters
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createPriorityHeader("5"));
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createContentTypeHeader("applicationn", "texxt"));
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ua.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ua.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createMaxForwardsHeader(62));
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol, addnl_hdrs,
replace_hdrs, "my body");
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testNonblockingMakeCallExtraStringParms() // test the
// nonblocking
// version of SipPhone.makeCall() with extra String parameters
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(new String("Priority: 5"));
ArrayList replace_hdrs = new ArrayList();
replace_hdrs.add(new String("Contact: <sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '>'));
replace_hdrs.add(new String("Max-Forwards: 62"));
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol, "my body",
"applicationn", "texxt", addnl_hdrs, replace_hdrs);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMultipleReplies()
{
// test: sendRequestWithTrans(Request invite),
// sendReply(Response Trying, no toTag, no contact, ...),
// sendReply(statusCode Ringing, toTag, contact, ...),
// sendReply(Response OK, no toTag, contact, ...),
// waitResponse()
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
AddressFactory addr_factory = ua.getParent().getAddressFactory();
HeaderFactory hdr_factory = ua.getParent().getHeaderFactory();
Request invite = ua.getParent().getMessageFactory().createRequest(
"INVITE sip:[email protected] SIP/2.0 ");
invite.addHeader(ua.getParent().getSipProvider().getNewCallId());
invite.addHeader(hdr_factory.createCSeqHeader((long)1, Request.INVITE));
invite.addHeader(hdr_factory.createFromHeader(ua.getAddress(), ua
.generateNewTag()));
Address to_address = addr_factory.createAddress(addr_factory
.createURI("sip:[email protected]"));
invite.addHeader(hdr_factory.createToHeader(to_address, null));
Address contact_address = addr_factory.createAddress("sip:amit@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort);
invite.addHeader(hdr_factory.createContactHeader(contact_address));
invite.addHeader(hdr_factory.createMaxForwardsHeader(5));
ArrayList via_headers = ua.getViaHeaders();
invite.addHeader((ViaHeader) via_headers.get(0));
Address route_address = addr_factory.createAddress("sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
invite.addHeader(hdr_factory.createRouteHeader(route_address));
SipTransaction trans = ua.sendRequestWithTransaction(invite, false,
null);
assertNotNull(ua.format(), trans);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(500);
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1);
assertLastOperationSuccess(ub.format(), ub);
// ringing response sent
Thread.sleep(500);
response = ub.getParent().getMessageFactory().createResponse(
Response.OK, inc_req.getRequest());
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// answer response sent
Thread.sleep(500);
EventObject response_event = ua.waitResponse(trans, 10000);
// wait for trying
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received TRYING", Response.TRYING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// trying received
response_event = ua.waitResponse(trans, 10000);
// wait for ringing
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received RINGING", Response.RINGING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// ringing received
response_event = ua.waitResponse(trans, 10000);
// wait for answer
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received OK", Response.OK,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// answer received
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
// this method tests re-invite from b to a,
// TestWithProxyAuthentication does the other direction
public void testReinvite()
{
SipStack.trace("testAdditionalMessageParms"); // using reinvite
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
// establish a call
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
Thread.sleep(20);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 600));
Thread.sleep(200);
assertResponseReceived(SipResponse.OK, a);
assertTrue(a.sendInviteOkAck());
Thread.sleep(300);
// send request - test reinvite with no specific parameters
// _____________________________________________
a.listenForReinvite();
SipTransaction siptrans_b = b.sendReinvite(null, null,
(String) null, null, null);
assertNotNull(siptrans_b);
SipTransaction siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
SipMessage req = a.getLastReceivedRequest();
String b_orig_contact_uri = ((ContactHeader) req.getMessage()
.getHeader(ContactHeader.NAME)).getAddress().getURI()
.toString();
// check contact info
assertEquals(ub.getContactInfo().getURI(), b_orig_contact_uri);
assertHeaderNotContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderNotPresent(req, ContentTypeHeader.NAME);
assertBodyNotPresent(req);
// check additional headers
assertHeaderNotPresent(req, PriorityHeader.NAME);
assertHeaderNotPresent(req, ReasonHeader.NAME);
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "10");
// send response - test new contact only
// _____________________________________________
String a_orig_contact_uri = ua.getContactInfo().getURI();
String a_contact_no_lr = a_orig_contact_uri.substring(0,
a_orig_contact_uri.lastIndexOf("lr") - 1);
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite response", -1, a_contact_no_lr, null, null,
(String) null, null));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
SipResponse response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite response", response.getReasonPhrase());
// check contact info
assertEquals(ua.getContactInfo().getURI(), a_contact_no_lr); // changed
assertFalse(a_orig_contact_uri.equals(a_contact_no_lr));
assertHeaderNotContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME, a_contact_no_lr);
assertHeaderNotContains(response, ContactHeader.NAME,
"My DisplayName");
// check body
assertHeaderNotPresent(response, ContentTypeHeader.NAME);
assertBodyNotPresent(response);
// check additional headers
assertHeaderNotPresent(response, PriorityHeader.NAME);
assertHeaderNotPresent(response, ReasonHeader.NAME);
// check override headers
assertHeaderContains(response, ContentLengthHeader.NAME, "0");
// send ACK
assertTrue(b.sendReinviteOkAck(siptrans_b));
assertTrue(a.waitForAck(1000));
Thread.sleep(100); //
// send request - test contact and body
// _____________________________________________
a.listenForReinvite();
String b_contact_no_lr = b_orig_contact_uri.substring(0,
b_orig_contact_uri.lastIndexOf("lr") - 1);
siptrans_b = b.sendReinvite(b_contact_no_lr, "My DisplayName",
"my reinvite", "app", "subapp");
assertNotNull(siptrans_b);
siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
req = a.getLastReceivedRequest();
// check contact info
assertEquals(ub.getContactInfo().getURI(), b_contact_no_lr); // changed
assertFalse(b_orig_contact_uri.equals(b_contact_no_lr));
assertHeaderNotContains(req, ContactHeader.NAME, ";lr");
assertHeaderContains(req, ContactHeader.NAME, b_contact_no_lr);
assertHeaderContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderContains(req, ContentTypeHeader.NAME, "subapp");
assertBodyContains(req, "my reinvite");
// check additional headers
assertHeaderNotPresent(req, PriorityHeader.NAME);
assertHeaderNotPresent(req, ReasonHeader.NAME);
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "10");
// send response - test body only
// _____________________________________________
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite response", -1, null, null, "DooDah",
"application", "text"));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite response", response.getReasonPhrase());
// check contact info
assertHeaderNotContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME, a_contact_no_lr);
assertHeaderNotContains(response, ContactHeader.NAME,
"My DisplayName");
// check body
assertHeaderPresent(response, ContentTypeHeader.NAME);
ContentTypeHeader ct_hdr = (ContentTypeHeader) response
.getMessage().getHeader(ContentTypeHeader.NAME);
assertEquals("application", ct_hdr.getContentType());
assertEquals("text", ct_hdr.getContentSubType());
assertBodyContains(response, "DooDah");
// check additional headers
assertHeaderNotPresent(response, PriorityHeader.NAME);
assertHeaderNotPresent(response, ReasonHeader.NAME);
// check override headers
// done, content sub type not overidden
// send ACK
// with JSIP additional, replacement headers, and body
ArrayList addnl_hdrs = new ArrayList(2);
ReasonHeader reason_hdr = ub.getParent().getHeaderFactory()
.createReasonHeader("SIP", 44, "dummy");
addnl_hdrs.add(reason_hdr);
ct_hdr = ub.getParent().getHeaderFactory().createContentTypeHeader(
"mytype", "mysubtype");
addnl_hdrs.add(ct_hdr);
ArrayList replace_hdrs = new ArrayList(2);
MaxForwardsHeader hdr = ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(29);
replace_hdrs.add(hdr);
PriorityHeader pri_hdr = ub.getParent().getHeaderFactory()
.createPriorityHeader(PriorityHeader.URGENT);
replace_hdrs.add(pri_hdr);
assertTrue(b.sendReinviteOkAck(siptrans_b, addnl_hdrs,
replace_hdrs, "ack body"));
assertTrue(a.waitForAck(1000));
SipRequest req_ack = a.getLastReceivedRequest();
assertHeaderContains(req_ack, ReasonHeader.NAME, "dummy");
assertHeaderContains(req_ack, MaxForwardsHeader.NAME, "29");
assertHeaderContains(req_ack, PriorityHeader.NAME, "gent");
assertHeaderContains(req_ack, ContentTypeHeader.NAME, "mysubtype");
assertBodyContains(req_ack, "ack body");
Thread.sleep(100);
// send request - test additional and replace headers (JAIN SIP)
// _____________________________________________
a.listenForReinvite();
addnl_hdrs = new ArrayList(2);
pri_hdr = ub.getParent().getHeaderFactory().createPriorityHeader(
PriorityHeader.URGENT);
reason_hdr = ub.getParent().getHeaderFactory().createReasonHeader(
"SIP", 41, "I made it up");
addnl_hdrs.add(pri_hdr);
addnl_hdrs.add(reason_hdr);
replace_hdrs = new ArrayList(1);
hdr = ub.getParent().getHeaderFactory().createMaxForwardsHeader(21);
replace_hdrs.add(hdr);
siptrans_b = b.sendReinvite(null, null, addnl_hdrs, replace_hdrs,
"no body");
assertNotNull(siptrans_b);
siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
req = a.getLastReceivedRequest();
// check contact info
assertHeaderNotContains(req, ContactHeader.NAME, ";lr");
assertHeaderContains(req, ContactHeader.NAME, b_contact_no_lr);
assertHeaderContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderNotPresent(req, ContentTypeHeader.NAME);
assertBodyNotPresent(req);
// check additional headers
assertHeaderContains(req, PriorityHeader.NAME,
PriorityHeader.URGENT);
assertHeaderContains(req, ReasonHeader.NAME, "41");
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "21");
// test everything
// _____________________________________________
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add("Priority: Normal");
addnl_hdrs.add("Reason: SIP; cause=42; text=\"I made it up\"");
replace_hdrs.add("Content-Length: 4");
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite last response", -1, a_orig_contact_uri,
"Original info", "DooDahDay", "applicationn", "sdp",
addnl_hdrs, replace_hdrs));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite last response", response
.getReasonPhrase());
// check contact info
assertEquals(ua.getContactInfo().getURI(), a_orig_contact_uri); // changed
assertFalse(a_orig_contact_uri.equals(a_contact_no_lr));
assertHeaderContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME,
a_orig_contact_uri);
assertHeaderContains(response, ContactHeader.NAME, "Original info");
// check body
assertHeaderPresent(response, ContentTypeHeader.NAME);
ct_hdr = (ContentTypeHeader) response.getMessage().getHeader(
ContentTypeHeader.NAME);
assertEquals("applicationn", ct_hdr.getContentType());
assertEquals("sdp", ct_hdr.getContentSubType());
assertBodyContains(response, "DooD");
// check additional headers
assertHeaderContains(response, PriorityHeader.NAME,
PriorityHeader.NORMAL);
assertHeaderContains(response, ReasonHeader.NAME, "42");
// check override headers
assertHeaderContains(response, ContentLengthHeader.NAME, "4");
// send ACK
assertTrue(b.sendReinviteOkAck(siptrans_b));
assertTrue(a.waitForAck(1000));
Thread.sleep(100); //
// done, finish up
a.listenForDisconnect();
Thread.sleep(100);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(5000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
Thread.sleep(100);
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testSendReplySipTransactionExtraInfo()
{
// test sendReply(SipTransaction, ....) options
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
SipCall a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response); // sendReply(RequestEvent)
assertNotNull(ub.format(), transb);
// initial trying response sent
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.TRYING, a
.getReturnCode());
// (a) send reply with additional JSIP Headers but no body
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12));
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("app", "subtype"));
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
SipMessage resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b) send reply with additional JSIP Header (ContentTypeHeader)
// and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("bapp", "subtype"));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c) send reply with other additional JSIP Header (not
// ContentTypeHeader) and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d) send reply with replace JSIP Header (test replacement),
// ignored body
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ub.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ub.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e) send reply with replace JSIP Header (test addition)
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f) send reply with all - additional,replace JSIP Headers & body
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag")); // verify ignored
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "text"));// for
// body
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60)); // verify addition
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, replace_hdrs, "my new body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
;
// now for the String header version:
// (a') send reply with additional String Headers & content type
// info but no body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12).toString());
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, "app", "subtype", addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b') send reply with ContentTypeHeader info
// and body
addnl_hdrs.clear();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", "bapp", "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c') send reply with other additional String Header (not
// ContentType info) and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11).toString());
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d') send reply with replace String Header (test replacement),
// ignored body
replace_hdrs.clear();
replace_hdrs.add("Contact: <sip:[email protected]:5060>");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e') send reply with replace String Header (test addition)
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50).toString());
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f') send reply with all - additional,replace String Headers,
// CTinfo & body
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag").toString()); // verify ignored
replace_hdrs.add("Contact: <sip:[email protected]:5060>"); // verify
// replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60).toString()); // verify
// addition
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my new body", "application", "text", addnl_hdrs,
replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// (g') send reply with bad String headers
replace_hdrs.clear();
replace_hdrs.add("Max-Forwards");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationFail(ub);
assertTrue(ub.format().indexOf("no HCOLON") != -1);
// (h') send reply with partial content type parms and body, no
// addnl hdrs
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
// (i') send reply with partial content type parms and body, other
// addnl hdrs
addnl_hdrs.clear();
addnl_hdrs.add("Max-Forwards: 66");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", "app", null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "66");
// (j') send reply with nothing
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ToHeader.NAME, to_tag);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
public void testSendReplyRequestEventExtraInfo()
{
// test sendReply(RequestEvent, ....) options
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
SipCall a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response); // sendReply(RequestEvent)
assertNotNull(ub.format(), transb);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.TRYING, a
.getReturnCode());
// (a) send reply with additional JSIP Headers but no body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12));
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("app", "subtype"));
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
SipMessage resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b) send reply with additional JSIP Header (ContentTypeHeader)
// and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("bapp", "subtype"));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c) send reply with other additional JSIP Header (not
// ContentTypeHeader) and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d) send reply with replace JSIP Header (test replacement),
// ignored body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ub.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ub.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e) send reply with replace JSIP Header (test addition)
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f) send reply with all - additional,replace JSIP Headers & body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag")); // verify ignored
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "text"));// for
// body
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60)); // verify addition
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, replace_hdrs, "my new body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// now for the String header version:
// (a') send reply with additional String Headers & content type
// info but no body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12).toString());
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, "app", "subtype", addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b') send reply with ContentTypeHeader info
// and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", "bapp", "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c') send reply with other additional String Header (not
// ContentType info) and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11).toString());
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d') send reply with replace String Header (test replacement),
// ignored body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add("Contact: <sip:[email protected]:5060>");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e') send reply with replace String Header (test addition)
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50).toString());
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f') send reply with all - additional,replace String Headers,
// CTinfo & body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag").toString()); // verify ignored
replace_hdrs.add("Contact: <sip:[email protected]:5060>"); // verify
// replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60).toString()); // verify
// addition
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my new body", "application", "text", addnl_hdrs,
replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// (g') send reply with bad String headers
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add("Max-Forwards");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationFail(ub);
assertTrue(ub.format().indexOf("no HCOLON") != -1);
// (h') send reply with partial content type parms and body, no
// addnl hdrs
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
// (i') send reply with partial content type parms and body, other
// addnl hdrs
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add("Max-Forwards: 66");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", "app", null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "66");
// (j') send reply with nothing
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ToHeader.NAME, to_tag);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
} | src/org/cafesip/sipunit/test/TestNoProxy.java | /*
* Created on April 21, 2005
*
* Copyright 2005 CafeSip.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.cafesip.sipunit.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Properties;
import javax.sip.RequestEvent;
import javax.sip.ResponseEvent;
import javax.sip.TimeoutEvent;
import javax.sip.address.Address;
import javax.sip.address.AddressFactory;
import javax.sip.address.URI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.ContentLengthHeader;
import javax.sip.header.ContentTypeHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.PriorityHeader;
import javax.sip.header.ReasonHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipMessage;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipResponse;
import org.cafesip.sipunit.SipSession;
import org.cafesip.sipunit.SipStack;
import org.cafesip.sipunit.SipTestCase;
import org.cafesip.sipunit.SipTransaction;
/**
* This class tests SipUnit API methods.
*
* Tests in this class do not require a proxy/registrar server. Messaging
* between UACs is direct.
*
* @author Becky McElroy
*
*/
public class TestNoProxy extends SipTestCase
{
private SipStack sipStack;
private SipPhone ua;
private int myPort;
private String testProtocol;
private static final Properties defaultProperties = new Properties();
static
{
String host = null;
try
{
host = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
host = "localhost";
}
defaultProperties.setProperty("javax.sip.IP_ADDRESS", host);
defaultProperties.setProperty("javax.sip.STACK_NAME", "testAgent");
defaultProperties.setProperty("gov.nist.javax.sip.TRACE_LEVEL", "32");
defaultProperties.setProperty("gov.nist.javax.sip.DEBUG_LOG",
"testAgent_debug.txt");
defaultProperties.setProperty("gov.nist.javax.sip.SERVER_LOG",
"testAgent_log.txt");
defaultProperties
.setProperty("gov.nist.javax.sip.READ_TIMEOUT", "1000");
defaultProperties.setProperty(
"gov.nist.javax.sip.CACHE_SERVER_CONNECTIONS", "false");
defaultProperties.setProperty("sipunit.trace", "true");
defaultProperties.setProperty("sipunit.test.port", "5060");
defaultProperties.setProperty("sipunit.test.protocol", "udp");
}
private Properties properties = new Properties(defaultProperties);
public TestNoProxy(String arg0)
{
super(arg0);
properties.putAll(System.getProperties());
try
{
myPort = Integer.parseInt(properties
.getProperty("sipunit.test.port"));
}
catch (NumberFormatException e)
{
myPort = 5060;
}
testProtocol = properties.getProperty("sipunit.test.protocol");
}
/*
* @see SipTestCase#setUp()
*/
public void setUp() throws Exception
{
try
{
sipStack = new SipStack(testProtocol, myPort, properties);
SipStack.setTraceEnabled(properties.getProperty("sipunit.trace")
.equalsIgnoreCase("true")
|| properties.getProperty("sipunit.trace")
.equalsIgnoreCase("on"));
}
catch (Exception ex)
{
fail("Exception: " + ex.getClass().getName() + ": "
+ ex.getMessage());
throw ex;
}
try
{
ua = sipStack.createSipPhone("sip:[email protected]");
}
catch (Exception ex)
{
fail("Exception creating SipPhone: " + ex.getClass().getName()
+ ": " + ex.getMessage());
throw ex;
}
}
/*
* @see SipTestCase#tearDown()
*/
public void tearDown() throws Exception
{
ua.dispose();
sipStack.dispose();
}
public void testSendInviteWithRouteHeader() // add a Route Header to the
// INVITE myself
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
AddressFactory addr_factory = ua.getParent().getAddressFactory();
HeaderFactory hdr_factory = ua.getParent().getHeaderFactory();
Request invite = ua.getParent().getMessageFactory().createRequest(
"INVITE sip:[email protected] SIP/2.0 ");
invite.addHeader(ua.getParent().getSipProvider().getNewCallId());
invite.addHeader(hdr_factory.createCSeqHeader((long)1, Request.INVITE));
invite.addHeader(hdr_factory.createFromHeader(ua.getAddress(), ua
.generateNewTag()));
Address to_address = addr_factory.createAddress(addr_factory
.createURI("sip:[email protected]"));
invite.addHeader(hdr_factory.createToHeader(to_address, null));
Address contact_address = addr_factory.createAddress("sip:amit@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort);
invite.addHeader(hdr_factory.createContactHeader(contact_address));
invite.addHeader(hdr_factory.createMaxForwardsHeader(5));
ArrayList via_headers = ua.getViaHeaders();
invite.addHeader((ViaHeader) via_headers.get(0));
// create and add the Route Header
Address route_address = addr_factory.createAddress("sip:becky@"
+ ub.getStackAddress() + ':'
+ myPort + '/' + testProtocol);
invite.addHeader(hdr_factory.createRouteHeader(route_address));
SipTransaction trans = ua.sendRequestWithTransaction(invite, false,
null);
assertNotNull(ua.format(), trans);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(500);
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1);
assertLastOperationSuccess(ub.format(), ub);
// ringing response sent
Thread.sleep(500);
response = ub.getParent().getMessageFactory().createResponse(
Response.OK, inc_req.getRequest());
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// answer response sent
Thread.sleep(500);
EventObject response_event = ua.waitResponse(trans, 10000);
// wait for trying
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received TRYING", Response.TRYING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// response(s) received, we're done
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testBothSides() // test initiateOugoingCall(), passing routing
// string
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall a = ua.createSipCall();
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
Thread.sleep(10);
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess("a initiate call - " + a.format(), a);
b.waitForIncomingCall(10000);
assertLastOperationSuccess("b wait incoming call - " + b.format(),
b);
b.sendIncomingCallResponse(Response.RINGING, null, -1);
assertLastOperationSuccess("b send RINGING - " + b.format(), b);
Thread.sleep(1000);
b.sendIncomingCallResponse(Response.OK, "Answer - Hello world", 0);
assertLastOperationSuccess("b send OK - " + b.format(), b);
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.RINGING,
a.getReturnCode());
assertNotNull("Default response reason not sent", a
.getLastReceivedResponse().getReasonPhrase());
assertEquals("Unexpected default reason", "Ringing", a
.getLastReceivedResponse().getReasonPhrase());
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 2nd response - " + a.format(), a);
assertEquals("Unexpected 2nd response received", Response.OK, a
.getReturnCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(1000);
a.listenForDisconnect();
assertLastOperationSuccess("a listen disc - " + a.format(), a);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(5000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
assertLastOperationSuccess("a respond to disc - " + a.format(), a);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testSipTestCaseMisc()
// in this test, user a is handled at the SipCall level and user b at the
// SipSession level (we send a body in the response)
{
try
{
SipCall a = ua.createSipCall();
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(50);
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess("a initiate call - " + a.format(), a);
RequestEvent inc_req = ub.waitRequest(10000);
assertNotNull(ub.format(), inc_req);
// call received
SipRequest req = new SipRequest(inc_req.getRequest());
/*******************************************************************
* Incoming request - header/body asserts
******************************************************************/
assertHeaderPresent(req, "Max-Forwards");
assertHeaderNotPresent(req, "Max-Forwardss");
assertHeaderNotContains(req, "Max-Forwards", "71");
assertHeaderContains(req, "Max-Forwards", "70");
assertBodyNotPresent(req);
assertBodyNotContains(req, "e");
/** ************************************************************* */
// send TRYING
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(100);
// send message with a body
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
response = ub.getParent().getMessageFactory().createResponse(
Response.RINGING, inc_req.getRequest()); // why OK
// doesn't
// work here?
response.setReasonPhrase("Hello World");
((ToHeader) response.getHeader(ToHeader.NAME)).setTag(to_tag);
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ContentTypeHeader ct = ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "sdp");
response.setContent("This is a test body", ct);
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// message with body sent
Thread.sleep(100);
a.waitOutgoingCallResponse(4000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
while (a.getReturnCode() == Response.TRYING)
{
a.waitOutgoingCallResponse(4000);
assertLastOperationSuccess("a wait nth response - "
+ a.format(), a);
}
/*******************************************************************
* Incoming response - header/body asserts
******************************************************************/
assertBodyPresent(a.getLastReceivedResponse());
assertBodyContains(a.getLastReceivedResponse(),
"his is a test body");
SipResponse resp = a.getLastReceivedResponse();
assertHeaderPresent(resp, "Contact");
assertHeaderNotPresent(resp, "Contacts");
assertHeaderNotContains(resp, "Contact", "amit");
assertHeaderContains(resp, "Contact", "becky");
/** **************************************************************** */
// ub needs to send BYE, so SipCall gets a request and can verify
// higher
// level request/response asserts
Request invite = inc_req.getRequest();
ContactHeader caller_contact = (ContactHeader) invite
.getHeader(ContactHeader.NAME);
FromHeader a_party = (FromHeader) invite.getHeader(FromHeader.NAME);
ToHeader b_party = (ToHeader) response.getHeader(ToHeader.NAME);
CSeqHeader cseq = ub.getParent().getHeaderFactory()
.createCSeqHeader(
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber(), Request.BYE);
Request bye = ub.getParent().getMessageFactory().createRequest(
caller_contact.getAddress().getURI(),
Request.BYE,
(CallIdHeader) invite.getHeader(CallIdHeader.NAME),
cseq,
ub.getParent().getHeaderFactory().createFromHeader(
b_party.getAddress(), b_party.getTag()),
ub.getParent().getHeaderFactory().createToHeader(
a_party.getAddress(), a_party.getTag()),
ub.getViaHeaders(),
ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(5));
bye.addHeader(ub.getParent().getHeaderFactory().createRouteHeader(
caller_contact.getAddress()));
assertTrue(a.listenForDisconnect());
assertTrue(ub.sendUnidirectionalRequest(bye, false));
assertTrue(a.waitForDisconnect(2000));
/*******************************************************************
* MessageListener level - methods, request/response assertions
******************************************************************/
SipRequest received_bye = a.getLastReceivedRequest();
assertNotNull(received_bye);
ArrayList received_requests = a.getAllReceivedRequests();
assertEquals(1, received_requests.size());
assertEquals(received_bye, received_requests.get(0));
SipResponse received_response = a.getLastReceivedResponse();
assertNotNull(received_response);
ArrayList received_responses = a.getAllReceivedResponses();
int num_responses = received_responses.size();
assertTrue(num_responses >= 2);
assertEquals(received_response, received_responses
.get(num_responses - 1));
assertResponseReceived(SipResponse.TRYING, a);
assertResponseReceived("Expected RINGING", SipResponse.RINGING, a);
assertResponseNotReceived(SipResponse.OK, a);
assertResponseNotReceived("Didn't expect OK", SipResponse.OK, a);
assertResponseReceived(SipResponse.RINGING, SipRequest.INVITE,
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
assertResponseReceived("Expected RINGING", SipResponse.RINGING,
SipRequest.INVITE, ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
assertResponseNotReceived(SipResponse.RINGING, SipRequest.INVITE,
((CSeqHeader) invite.getHeader(CSeqHeader.NAME))
.getSeqNumber() + 1, a);
assertResponseNotReceived("Didn't expect this",
SipResponse.RINGING, SipRequest.ACK, ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME))
.getSeqNumber(), a);
long received_cseq_seqnum = ((CSeqHeader) invite
.getHeader(CSeqHeader.NAME)).getSeqNumber();
assertRequestReceived(SipRequest.BYE, a);
assertRequestReceived(SipRequest.BYE, received_cseq_seqnum, a);
assertRequestReceived("Expected a BYE", SipRequest.BYE, a);
assertRequestReceived("Wrong CSEQ sequence number", SipRequest.BYE,
received_cseq_seqnum, a);
assertRequestNotReceived(SipRequest.INVITE, a);
assertRequestNotReceived("Didn't expect a NOTIFY",
SipRequest.NOTIFY, a);
assertRequestNotReceived(SipRequest.BYE, received_cseq_seqnum + 1,
a);
assertRequestNotReceived("Didn't expect a SUBSCRIBE",
SipRequest.SUBSCRIBE, received_cseq_seqnum, a);
/** ************************************************************* */
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallFail()
{
try
{
ua.makeCall("sip:[email protected]", SipResponse.RINGING, 1000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
assertLastOperationFail(ua.format(), ua);
assertEquals(ua.getReturnCode(), SipSession.TIMEOUT_OCCURRED);
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
/**
* Test: asynchronous SipPhone.makeCall() callee disc
*/
public void testMakeCallCalleeDisconnect() // test the nonblocking version
// of
// SipPhone.makeCall() - A CALLS B
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
// or assertNotNull(a)
assertTrue(b.waitForIncomingCall(5000));
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(400);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
b.sendIncomingCallResponse(Response.OK, "Answer - Hello world", 0);
Thread.sleep(500);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
a.listenForDisconnect();
Thread.sleep(100);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(3000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
/**
* Test: asynchronous SipPhone.makeCall() caller disc
*/
public void testMakeCallCallerDisconnect() // test the nonblocking version
// of
// SipPhone.makeCall() - A CALLS B
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testBothSidesCallerDisc() // test the blocking version of
// SipPhone.makeCall()
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallExtraJainsipParms() // test the blocking version of
// SipPhone.makeCall() with extra JAIN SIP parameters
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createPriorityHeader("5"));
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createContentTypeHeader("applicationn", "texxt"));
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ua.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ua.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createMaxForwardsHeader(62));
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol, addnl_hdrs,
replace_hdrs, "my body");
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMakeCallExtraStringParms() // test the blocking version of
// SipPhone.makeCall() with extra String parameters
{
final class PhoneB extends Thread
{
public void run()
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
b.waitForIncomingCall(5000);
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
b.sendIncomingCallResponse(Response.RINGING, "Ringing", 0);
Thread.sleep(600);
b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0);
assertAnswered(b);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
b.listenForDisconnect();
b.waitForDisconnect(30000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
Thread.sleep(1000);
ub.dispose();
return;
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
}
try
{
PhoneB b = new PhoneB();
b.start();
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(new String("Priority: 5"));
ArrayList replace_hdrs = new ArrayList();
replace_hdrs.add(new String("Contact: <sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '>'));
replace_hdrs.add(new String("Max-Forwards: 62"));
SipCall a = ua.makeCall("sip:[email protected]", SipResponse.OK, 5000,
properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol, "my body",
"applicationn", "texxt", addnl_hdrs, replace_hdrs);
assertLastOperationSuccess(ua.format(), ua);
assertAnswered("Outgoing call leg not answered", a);
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
Thread.sleep(2000);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.join();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testNonblockingMakeCallExtraJainsipParms() // test the
// nonblocking
// SipPhone.makeCall() with extra JAIN SIP parameters
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createPriorityHeader("5"));
addnl_hdrs.add(ua.getParent().getHeaderFactory()
.createContentTypeHeader("applicationn", "texxt"));
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ua.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ua.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ua.getParent().getHeaderFactory()
.createMaxForwardsHeader(62));
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol, addnl_hdrs,
replace_hdrs, "my body");
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testNonblockingMakeCallExtraStringParms() // test the
// nonblocking
// version of SipPhone.makeCall() with extra String parameters
{
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
SipCall b = ub.createSipCall(); // incoming call
b.listenForIncomingCall();
Thread.sleep(50);
// set up outbound INVITE contents
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(new String("Priority: 5"));
ArrayList replace_hdrs = new ArrayList();
replace_hdrs.add(new String("Contact: <sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '>'));
replace_hdrs.add(new String("Max-Forwards: 62"));
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol, "my body",
"applicationn", "texxt", addnl_hdrs, replace_hdrs);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertHeaderContains(b.getLastReceivedRequest(),
PriorityHeader.NAME, "5");
assertHeaderContains(b.getLastReceivedRequest(),
ContentTypeHeader.NAME, "applicationn/texxt");
assertHeaderContains(b.getLastReceivedRequest(),
ContactHeader.NAME, "doodah");
assertHeaderContains(b.getLastReceivedRequest(),
MaxForwardsHeader.NAME, "62");
assertBodyContains(b.getLastReceivedRequest(), "my body");
assertTrue(b.sendIncomingCallResponse(Response.RINGING, "Ringing",
0));
Thread.sleep(100);
assertNotAnswered("Call leg shouldn't be answered yet", a);
assertNotAnswered(b);
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 0));
Thread.sleep(100);
assertAnswered("Outgoing call leg not answered", a);
assertAnswered(b);
assertFalse("Outgoing call leg error status wrong", a
.callTimeoutOrError());
assertTrue("Wrong number of responses received", a
.getAllReceivedResponses().size() == 2);
assertTrue(
"Shouldn't have received anything at the called party side",
b.getAllReceivedResponses().size() == 0);
// verify RINGING was received
assertResponseReceived("Should have gotten RINGING response",
SipResponse.RINGING, a);
// verify OK was received
assertResponseReceived(SipResponse.OK, a);
// check negative
assertResponseNotReceived("Unexpected response",
SipResponse.NOT_FOUND, a);
assertResponseNotReceived(SipResponse.ADDRESS_INCOMPLETE, a);
// verify getLastReceivedResponse() method
assertEquals("Last response received wasn't answer",
SipResponse.OK, a.getLastReceivedResponse().getStatusCode());
a.sendInviteOkAck();
assertLastOperationSuccess("Failure sending ACK - " + a.format(), a);
b.listenForDisconnect();
Thread.sleep(100);
a.disconnect();
assertLastOperationSuccess("a disc - " + a.format(), a);
b.waitForDisconnect(3000);
assertLastOperationSuccess("b wait disc - " + b.format(), b);
b.respondToDisconnect();
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testMultipleReplies()
{
// test: sendRequestWithTrans(Request invite),
// sendReply(Response Trying, no toTag, no contact, ...),
// sendReply(statusCode Ringing, toTag, contact, ...),
// sendReply(Response OK, no toTag, contact, ...),
// waitResponse()
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
AddressFactory addr_factory = ua.getParent().getAddressFactory();
HeaderFactory hdr_factory = ua.getParent().getHeaderFactory();
Request invite = ua.getParent().getMessageFactory().createRequest(
"INVITE sip:[email protected] SIP/2.0 ");
invite.addHeader(ua.getParent().getSipProvider().getNewCallId());
invite.addHeader(hdr_factory.createCSeqHeader((long)1, Request.INVITE));
invite.addHeader(hdr_factory.createFromHeader(ua.getAddress(), ua
.generateNewTag()));
Address to_address = addr_factory.createAddress(addr_factory
.createURI("sip:[email protected]"));
invite.addHeader(hdr_factory.createToHeader(to_address, null));
Address contact_address = addr_factory.createAddress("sip:amit@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort);
invite.addHeader(hdr_factory.createContactHeader(contact_address));
invite.addHeader(hdr_factory.createMaxForwardsHeader(5));
ArrayList via_headers = ua.getViaHeaders();
invite.addHeader((ViaHeader) via_headers.get(0));
Address route_address = addr_factory.createAddress("sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS") + ':'
+ myPort + '/' + testProtocol);
invite.addHeader(hdr_factory.createRouteHeader(route_address));
SipTransaction trans = ua.sendRequestWithTransaction(invite, false,
null);
assertNotNull(ua.format(), trans);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response);
assertNotNull(ub.format(), transb);
// trying response sent
Thread.sleep(500);
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1);
assertLastOperationSuccess(ub.format(), ub);
// ringing response sent
Thread.sleep(500);
response = ub.getParent().getMessageFactory().createResponse(
Response.OK, inc_req.getRequest());
response.addHeader(ub.getParent().getHeaderFactory()
.createContactHeader(contact));
ub.sendReply(transb, response);
assertLastOperationSuccess(ub.format(), ub);
// answer response sent
Thread.sleep(500);
EventObject response_event = ua.waitResponse(trans, 10000);
// wait for trying
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received TRYING", Response.TRYING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// trying received
response_event = ua.waitResponse(trans, 10000);
// wait for ringing
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received RINGING", Response.RINGING,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// ringing received
response_event = ua.waitResponse(trans, 10000);
// wait for answer
assertNotNull(ua.format(), response_event);
assertFalse("Operation timed out",
response_event instanceof TimeoutEvent);
assertEquals("Should have received OK", Response.OK,
((ResponseEvent) response_event).getResponse()
.getStatusCode());
// answer received
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
// this method tests re-invite from b to a,
// TestWithProxyAuthentication does the other direction
public void testReinvite()
{
SipStack.trace("testAdditionalMessageParms"); // using reinvite
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
// establish a call
SipCall b = ub.createSipCall();
b.listenForIncomingCall();
Thread.sleep(20);
SipCall a = ua.makeCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(ua.format(), ua);
assertTrue(b.waitForIncomingCall(5000));
assertTrue(b.sendIncomingCallResponse(Response.OK,
"Answer - Hello world", 600));
Thread.sleep(200);
assertResponseReceived(SipResponse.OK, a);
assertTrue(a.sendInviteOkAck());
Thread.sleep(300);
// send request - test reinvite with no specific parameters
// _____________________________________________
a.listenForReinvite();
SipTransaction siptrans_b = b.sendReinvite(null, null,
(String) null, null, null);
assertNotNull(siptrans_b);
SipTransaction siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
SipMessage req = a.getLastReceivedRequest();
String b_orig_contact_uri = ((ContactHeader) req.getMessage()
.getHeader(ContactHeader.NAME)).getAddress().getURI()
.toString();
// check contact info
assertEquals(ub.getContactInfo().getURI(), b_orig_contact_uri);
assertHeaderNotContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderNotPresent(req, ContentTypeHeader.NAME);
assertBodyNotPresent(req);
// check additional headers
assertHeaderNotPresent(req, PriorityHeader.NAME);
assertHeaderNotPresent(req, ReasonHeader.NAME);
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "10");
// send response - test new contact only
// _____________________________________________
String a_orig_contact_uri = ua.getContactInfo().getURI();
String a_contact_no_lr = a_orig_contact_uri.substring(0,
a_orig_contact_uri.lastIndexOf("lr") - 1);
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite response", -1, a_contact_no_lr, null, null,
(String) null, null));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
SipResponse response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite response", response.getReasonPhrase());
// check contact info
assertEquals(ua.getContactInfo().getURI(), a_contact_no_lr); // changed
assertFalse(a_orig_contact_uri.equals(a_contact_no_lr));
assertHeaderNotContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME, a_contact_no_lr);
assertHeaderNotContains(response, ContactHeader.NAME,
"My DisplayName");
// check body
assertHeaderNotPresent(response, ContentTypeHeader.NAME);
assertBodyNotPresent(response);
// check additional headers
assertHeaderNotPresent(response, PriorityHeader.NAME);
assertHeaderNotPresent(response, ReasonHeader.NAME);
// check override headers
assertHeaderContains(response, ContentLengthHeader.NAME, "0");
// send ACK
assertTrue(b.sendReinviteOkAck(siptrans_b));
assertTrue(a.waitForAck(1000));
Thread.sleep(100); //
// send request - test contact and body
// _____________________________________________
a.listenForReinvite();
String b_contact_no_lr = b_orig_contact_uri.substring(0,
b_orig_contact_uri.lastIndexOf("lr") - 1);
siptrans_b = b.sendReinvite(b_contact_no_lr, "My DisplayName",
"my reinvite", "app", "subapp");
assertNotNull(siptrans_b);
siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
req = a.getLastReceivedRequest();
// check contact info
assertEquals(ub.getContactInfo().getURI(), b_contact_no_lr); // changed
assertFalse(b_orig_contact_uri.equals(b_contact_no_lr));
assertHeaderNotContains(req, ContactHeader.NAME, ";lr");
assertHeaderContains(req, ContactHeader.NAME, b_contact_no_lr);
assertHeaderContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderContains(req, ContentTypeHeader.NAME, "subapp");
assertBodyContains(req, "my reinvite");
// check additional headers
assertHeaderNotPresent(req, PriorityHeader.NAME);
assertHeaderNotPresent(req, ReasonHeader.NAME);
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "10");
// send response - test body only
// _____________________________________________
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite response", -1, null, null, "DooDah",
"application", "text"));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite response", response.getReasonPhrase());
// check contact info
assertHeaderNotContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME, a_contact_no_lr);
assertHeaderNotContains(response, ContactHeader.NAME,
"My DisplayName");
// check body
assertHeaderPresent(response, ContentTypeHeader.NAME);
ContentTypeHeader ct_hdr = (ContentTypeHeader) response
.getMessage().getHeader(ContentTypeHeader.NAME);
assertEquals("application", ct_hdr.getContentType());
assertEquals("text", ct_hdr.getContentSubType());
assertBodyContains(response, "DooDah");
// check additional headers
assertHeaderNotPresent(response, PriorityHeader.NAME);
assertHeaderNotPresent(response, ReasonHeader.NAME);
// check override headers
// done, content sub type not overidden
// send ACK
// with JSIP additional, replacement headers, and body
ArrayList addnl_hdrs = new ArrayList(2);
ReasonHeader reason_hdr = ub.getParent().getHeaderFactory()
.createReasonHeader("SIP", 44, "dummy");
addnl_hdrs.add(reason_hdr);
ct_hdr = ub.getParent().getHeaderFactory().createContentTypeHeader(
"mytype", "mysubtype");
addnl_hdrs.add(ct_hdr);
ArrayList replace_hdrs = new ArrayList(2);
MaxForwardsHeader hdr = ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(29);
replace_hdrs.add(hdr);
PriorityHeader pri_hdr = ub.getParent().getHeaderFactory()
.createPriorityHeader(PriorityHeader.URGENT);
replace_hdrs.add(pri_hdr);
assertTrue(b.sendReinviteOkAck(siptrans_b, addnl_hdrs,
replace_hdrs, "ack body"));
assertTrue(a.waitForAck(1000));
SipRequest req_ack = a.getLastReceivedRequest();
assertHeaderContains(req_ack, ReasonHeader.NAME, "dummy");
assertHeaderContains(req_ack, MaxForwardsHeader.NAME, "29");
assertHeaderContains(req_ack, PriorityHeader.NAME, "gent");
assertHeaderContains(req_ack, ContentTypeHeader.NAME, "mysubtype");
assertBodyContains(req_ack, "ack body");
Thread.sleep(100);
// send request - test additional and replace headers (JAIN SIP)
// _____________________________________________
a.listenForReinvite();
addnl_hdrs = new ArrayList(2);
pri_hdr = ub.getParent().getHeaderFactory().createPriorityHeader(
PriorityHeader.URGENT);
reason_hdr = ub.getParent().getHeaderFactory().createReasonHeader(
"SIP", 41, "I made it up");
addnl_hdrs.add(pri_hdr);
addnl_hdrs.add(reason_hdr);
replace_hdrs = new ArrayList(1);
hdr = ub.getParent().getHeaderFactory().createMaxForwardsHeader(21);
replace_hdrs.add(hdr);
siptrans_b = b.sendReinvite(null, null, addnl_hdrs, replace_hdrs,
"no body");
assertNotNull(siptrans_b);
siptrans_a = a.waitForReinvite(1000);
assertNotNull(siptrans_a);
req = a.getLastReceivedRequest();
// check contact info
assertHeaderNotContains(req, ContactHeader.NAME, ";lr");
assertHeaderContains(req, ContactHeader.NAME, b_contact_no_lr);
assertHeaderContains(req, ContactHeader.NAME, "My DisplayName");
// check body
assertHeaderNotPresent(req, ContentTypeHeader.NAME);
assertBodyNotPresent(req);
// check additional headers
assertHeaderContains(req, PriorityHeader.NAME,
PriorityHeader.URGENT);
assertHeaderContains(req, ReasonHeader.NAME, "41");
// check override headers
assertHeaderContains(req, MaxForwardsHeader.NAME, "21");
// test everything
// _____________________________________________
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add("Priority: Normal");
addnl_hdrs.add("Reason: SIP; cause=42; text=\"I made it up\"");
replace_hdrs.add("Content-Length: 4");
assertTrue(a.respondToReinvite(siptrans_a, SipResponse.OK,
"ok reinvite last response", -1, a_orig_contact_uri,
"Original info", "DooDahDay", "applicationn", "sdp",
addnl_hdrs, replace_hdrs));
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
while (b.getLastReceivedResponse().getStatusCode() == Response.TRYING)
{
assertTrue(b.waitReinviteResponse(siptrans_b, 2000));
}
// check response code
response = b.getLastReceivedResponse();
assertEquals(Response.OK, response.getStatusCode());
assertEquals("ok reinvite last response", response
.getReasonPhrase());
// check contact info
assertEquals(ua.getContactInfo().getURI(), a_orig_contact_uri); // changed
assertFalse(a_orig_contact_uri.equals(a_contact_no_lr));
assertHeaderContains(response, ContactHeader.NAME, ";lr");
assertHeaderContains(response, ContactHeader.NAME,
a_orig_contact_uri);
assertHeaderContains(response, ContactHeader.NAME, "Original info");
// check body
assertHeaderPresent(response, ContentTypeHeader.NAME);
ct_hdr = (ContentTypeHeader) response.getMessage().getHeader(
ContentTypeHeader.NAME);
assertEquals("applicationn", ct_hdr.getContentType());
assertEquals("sdp", ct_hdr.getContentSubType());
assertBodyContains(response, "DooD");
// check additional headers
assertHeaderContains(response, PriorityHeader.NAME,
PriorityHeader.NORMAL);
assertHeaderContains(response, ReasonHeader.NAME, "42");
// check override headers
assertHeaderContains(response, ContentLengthHeader.NAME, "4");
// send ACK
assertTrue(b.sendReinviteOkAck(siptrans_b));
assertTrue(a.waitForAck(1000));
Thread.sleep(100); //
// done, finish up
a.listenForDisconnect();
Thread.sleep(100);
b.disconnect();
assertLastOperationSuccess("b disc - " + b.format(), b);
a.waitForDisconnect(5000);
assertLastOperationSuccess("a wait disc - " + a.format(), a);
a.respondToDisconnect();
Thread.sleep(100);
ub.dispose();
}
catch (Exception e)
{
e.printStackTrace();
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
}
public void testSendReplySipTransactionExtraInfo()
{
// test sendReply(SipTransaction, ....) options
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
SipCall a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response); // sendReply(RequestEvent)
assertNotNull(ub.format(), transb);
// initial trying response sent
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.TRYING, a
.getReturnCode());
// (a) send reply with additional JSIP Headers but no body
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12));
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("app", "subtype"));
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
SipMessage resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b) send reply with additional JSIP Header (ContentTypeHeader)
// and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("bapp", "subtype"));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c) send reply with other additional JSIP Header (not
// ContentTypeHeader) and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d) send reply with replace JSIP Header (test replacement),
// ignored body
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ub.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ub.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e) send reply with replace JSIP Header (test addition)
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50));
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f) send reply with all - additional,replace JSIP Headers & body
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag")); // verify ignored
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "text"));// for
// body
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60)); // verify addition
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, replace_hdrs, "my new body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
;
// now for the String header version:
// (a') send reply with additional String Headers & content type
// info but no body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12).toString());
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, "app", "subtype", addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b') send reply with ContentTypeHeader info
// and body
addnl_hdrs.clear();
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", "bapp", "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c') send reply with other additional String Header (not
// ContentType info) and body
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11).toString());
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d') send reply with replace String Header (test replacement),
// ignored body
replace_hdrs.clear();
replace_hdrs.add("Contact: <sip:[email protected]:5060>");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e') send reply with replace String Header (test addition)
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50).toString());
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f') send reply with all - additional,replace String Headers,
// CTinfo & body
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag").toString()); // verify ignored
replace_hdrs.add("Contact: <sip:[email protected]:5060>"); // verify
// replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60).toString()); // verify
// addition
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my new body", "application", "text", addnl_hdrs,
replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// (g') send reply with bad String headers
replace_hdrs.clear();
replace_hdrs.add("Max-Forwards");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationFail(ub);
assertTrue(ub.format().indexOf("no HCOLON") != -1);
// (h') send reply with partial content type parms and body, no
// addnl hdrs
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", null, "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
// (i') send reply with partial content type parms and body, other
// addnl hdrs
addnl_hdrs.clear();
addnl_hdrs.add("Max-Forwards: 66");
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
"my body", "app", null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "66");
// (j') send reply with nothing
ub.sendReply(transb, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ToHeader.NAME, to_tag);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
public void testSendReplyRequestEventExtraInfo()
{
// test sendReply(RequestEvent, ....) options
try
{
SipPhone ub = sipStack.createSipPhone("sip:[email protected]");
ub.listenRequestMessage();
Thread.sleep(100);
SipCall a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
RequestEvent inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
Response response = ub.getParent().getMessageFactory()
.createResponse(Response.TRYING, inc_req.getRequest());
SipTransaction transb = ub.sendReply(inc_req, response); // sendReply(RequestEvent)
assertNotNull(ub.format(), transb);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait 1st response - " + a.format(), a);
assertEquals("Unexpected 1st response received", Response.TRYING, a
.getReturnCode());
// (a) send reply with additional JSIP Headers but no body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
URI callee_contact = ub.getParent().getAddressFactory().createURI(
"sip:becky@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address contact = ub.getParent().getAddressFactory().createAddress(
callee_contact);
String to_tag = ub.generateNewTag();
ArrayList addnl_hdrs = new ArrayList();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12));
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("app", "subtype"));
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
SipMessage resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b) send reply with additional JSIP Header (ContentTypeHeader)
// and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("bapp", "subtype"));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c) send reply with other additional JSIP Header (not
// ContentTypeHeader) and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, null, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d) send reply with replace JSIP Header (test replacement),
// ignored body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ArrayList replace_hdrs = new ArrayList();
URI bogus_contact = ub.getParent().getAddressFactory().createURI(
"sip:doodah@"
+ properties.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort);
Address bogus_addr = ub.getParent().getAddressFactory()
.createAddress(bogus_contact);
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, "my body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e) send reply with replace JSIP Header (test addition)
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50));
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, replace_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f) send reply with all - additional,replace JSIP Headers & body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag")); // verify ignored
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createContentTypeHeader("application", "text"));// for
// body
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createContactHeader(bogus_addr)); // verify replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60)); // verify addition
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
addnl_hdrs, replace_hdrs, "my new body");
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// now for the String header version:
// (a') send reply with additional String Headers & content type
// info but no body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(12).toString());
// no body - should receive msg with body length 0 and with content
// type header
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, "app", "subtype", addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "app");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContentLengthHeader.NAME, "0");
// (b') send reply with ContentTypeHeader info
// and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", "bapp", "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, MaxForwardsHeader.NAME, "12");
assertHeaderContains(resp, ContentTypeHeader.NAME, "bapp");
assertHeaderContains(resp, ContentTypeHeader.NAME, "subtype");
assertBodyContains(resp, "my body");
// (c') send reply with other additional String Header (not
// ContentType info) and body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(11).toString());
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "11");
assertBodyNotPresent(resp);
// (d') send reply with replace String Header (test replacement),
// ignored body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add("Contact: <sip:[email protected]:5060>");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderNotContains(resp, ContactHeader.NAME, "becky");
assertHeaderNotPresent(resp, MaxForwardsHeader.NAME);
// (e') send reply with replace String Header (test addition)
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(50).toString());
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ContactHeader.NAME, "becky");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "50");
// (f') send reply with all - additional,replace String Headers,
// CTinfo & body
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
replace_hdrs.clear();
addnl_hdrs.add(ub.getParent().getHeaderFactory().createToHeader(
bogus_addr, "mytag").toString()); // verify ignored
replace_hdrs.add("Contact: <sip:[email protected]:5060>"); // verify
// replacement
replace_hdrs.add(ub.getParent().getHeaderFactory()
.createMaxForwardsHeader(60).toString()); // verify
// addition
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my new body", "application", "text", addnl_hdrs,
replace_hdrs);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotContains(resp, ToHeader.NAME, "doodah");
assertHeaderNotContains(resp, ToHeader.NAME, "mytag");
assertHeaderContains(resp, ContentTypeHeader.NAME, "application");
assertHeaderContains(resp, ContentTypeHeader.NAME, "text");
assertBodyContains(resp, "my new body");
assertHeaderContains(resp, ContactHeader.NAME, "doodah");
assertHeaderContains(resp, MaxForwardsHeader.NAME, "60");
// (g') send reply with bad String headers
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
replace_hdrs.clear();
replace_hdrs.add("Max-Forwards");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, replace_hdrs);
assertLastOperationFail(ub);
assertTrue(ub.format().indexOf("no HCOLON") != -1);
// (h') send reply with partial content type parms and body, no
// addnl hdrs
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", null, "subtype", null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
// (i') send reply with partial content type parms and body, other
// addnl hdrs
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
addnl_hdrs.clear();
addnl_hdrs.add("Max-Forwards: 66");
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
"my body", "app", null, addnl_hdrs, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, MaxForwardsHeader.NAME, "66");
// (j') send reply with nothing
a.dispose(); // recreate the call, can only call
// sendReply(RequestEvent,..) once for the same request.
a = ua.createSipCall();
a.initiateOutgoingCall("sip:[email protected]", properties
.getProperty("javax.sip.IP_ADDRESS")
+ ':' + myPort + '/' + testProtocol);
assertLastOperationSuccess(a.format(), a);
// call sent
inc_req = ub.waitRequest(30000);
assertNotNull(ub.format(), inc_req);
// call received
ub.sendReply(inc_req, Response.RINGING, null, to_tag, contact, -1,
null, null, null, null, null);
assertLastOperationSuccess(ub.format(), ub);
Thread.sleep(100);
// receive it on the 'a' side
a.waitOutgoingCallResponse(10000);
assertLastOperationSuccess("a wait response - " + a.format(), a);
assertEquals("Unexpected response received", Response.RINGING, a
.getReturnCode());
// check parms in reply
resp = a.getLastReceivedResponse();
assertHeaderNotPresent(resp, ContentTypeHeader.NAME);
assertBodyNotPresent(resp);
assertHeaderContains(resp, ToHeader.NAME, to_tag);
ub.dispose();
}
catch (Exception e)
{
fail("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
return;
}
} | svn check-in test
git-svn-id: 496c9b949fd35c6ba9ba668326ada2c6a79e6257@169 464103e8-6c2c-0410-8156-f9cf65a0535e
| src/org/cafesip/sipunit/test/TestNoProxy.java | svn check-in test |
|
Java | apache-2.0 | c6dcc8daa5ad141f42fcfb95b8d929eefe1d59e0 | 0 | mhmdfy/autopsy,APriestman/autopsy,narfindustries/autopsy,eXcomm/autopsy,sidheshenator/autopsy,eXcomm/autopsy,rcordovano/autopsy,maxrp/autopsy,wschaeferB/autopsy,rcordovano/autopsy,APriestman/autopsy,dgrove727/autopsy,rcordovano/autopsy,eXcomm/autopsy,rcordovano/autopsy,mhmdfy/autopsy,karlmortensen/autopsy,sidheshenator/autopsy,eXcomm/autopsy,wschaeferB/autopsy,esaunders/autopsy,mhmdfy/autopsy,karlmortensen/autopsy,rcordovano/autopsy,millmanorama/autopsy,dgrove727/autopsy,APriestman/autopsy,maxrp/autopsy,wschaeferB/autopsy,rcordovano/autopsy,narfindustries/autopsy,APriestman/autopsy,maxrp/autopsy,millmanorama/autopsy,esaunders/autopsy,esaunders/autopsy,millmanorama/autopsy,wschaeferB/autopsy,narfindustries/autopsy,esaunders/autopsy,esaunders/autopsy,sidheshenator/autopsy,wschaeferB/autopsy,sidheshenator/autopsy,karlmortensen/autopsy,APriestman/autopsy,APriestman/autopsy,dgrove727/autopsy,mhmdfy/autopsy,APriestman/autopsy,maxrp/autopsy,karlmortensen/autopsy,millmanorama/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.StringExtract.StringExtractUnicodeTable.SCRIPT;
import org.sleuthkit.autopsy.keywordsearch.Ingester.IngesterException;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.ReadContentInputStream;
/**
* Extractor of text from HTML supported AbstractFile content. Extracted text is
* divided into chunks and indexed with Solr. If HTML extraction succeeds,
* chunks are indexed with Solr.
*/
public class AbstractFileHtmlExtract implements AbstractFileExtract {
private static final Logger logger = Logger.getLogger(AbstractFileHtmlExtract.class.getName());
static final Charset outCharset = Server.DEFAULT_INDEXED_TEXT_CHARSET;
static final int MAX_EXTR_TEXT_CHARS = 512 * 1024;
private static final int SINGLE_READ_CHARS = 1024;
private static final int EXTRA_CHARS = 128; //for whitespace
private static final char[] TEXT_CHUNK_BUF = new char[MAX_EXTR_TEXT_CHARS];
private static final int MAX_SIZE = 10000000;
private KeywordSearchIngestModule module;
private Ingester ingester;
private AbstractFile sourceFile;
private int numChunks = 0;
//private static final String UTF16BOM = "\uFEFF"; disabled prepending of BOM
static final List<String> WEB_MIME_TYPES = Arrays.asList(
"application/javascript",
"application/xhtml+xml",
"application/json",
"text/css",
"text/html",
"text/javascript" //"application/xml",
//"application/xml-dtd",
);
private final TikaLanguageIdentifier tikaLanguageIdentifier;
AbstractFileHtmlExtract() {
tikaLanguageIdentifier = new TikaLanguageIdentifier();
this.module = KeywordSearchIngestModule.getDefault();
ingester = Server.getIngester();
}
@Override
public boolean setScripts(List<SCRIPT> extractScripts) {
return false;
}
@Override
public List<SCRIPT> getScripts() {
return null;
}
@Override
public Map<String, String> getOptions() {
return null;
}
@Override
public void setOptions(Map<String, String> options) {
}
@Override
public int getNumChunks() {
return numChunks;
}
@Override
public AbstractFile getSourceFile() {
return sourceFile;
}
@Override
public boolean index(AbstractFile sourceFile) throws IngesterException {
this.sourceFile = sourceFile;
this.numChunks = 0; //unknown until indexing is done
boolean success = false;
Reader reader = null;
final InputStream stream = new ReadContentInputStream(sourceFile);
try {
// Parse the stream with Jericho
JerichoParserWrapper jpw = new JerichoParserWrapper(stream);
jpw.parse();
reader = jpw.getReader();
// In case there is an exception or parse() isn't called
if (reader == null) {
logger.log(Level.WARNING, "No reader available from HTML parser");
return false;
}
success = true;
long readSize;
long totalRead = 0;
boolean eof = false;
//we read max 1024 chars at time, this seems to max what this Reader would return
while (!eof && (readSize = reader.read(TEXT_CHUNK_BUF, 0, SINGLE_READ_CHARS)) != -1) {
totalRead += readSize;
//consume more bytes to fill entire chunk (leave EXTRA_CHARS to end the word)
while ((totalRead < MAX_EXTR_TEXT_CHARS - SINGLE_READ_CHARS - EXTRA_CHARS)
&& (readSize = reader.read(TEXT_CHUNK_BUF, (int) totalRead, SINGLE_READ_CHARS)) != -1) {
totalRead += readSize;
}
if (readSize == -1) {
//this is the last chunk
eof = true;
} else {
//try to read until whitespace to not break words
while ((totalRead < MAX_EXTR_TEXT_CHARS - 1)
&& !Character.isWhitespace(TEXT_CHUNK_BUF[(int) totalRead - 1])
&& (readSize = reader.read(TEXT_CHUNK_BUF, (int) totalRead, 1)) != -1) {
totalRead += readSize;
}
if (readSize == -1) {
//this is the last chunk
eof = true;
}
}
//logger.log(Level.INFO, "TOTAL READ SIZE: " + totalRead + " file: " + sourceFile.getName());
//encode to bytes to index as byte stream
String extracted;
//add BOM and trim the 0 bytes
//set initial size to chars read + bom - try to prevent from resizing
StringBuilder sb = new StringBuilder((int) totalRead + 1000);
//inject BOM here (saves byte buffer realloc later), will be converted to specific encoding BOM
//sb.append(UTF16BOM); disabled BOM, not needing as bypassing Tika
if (totalRead < MAX_EXTR_TEXT_CHARS) {
sb.append(TEXT_CHUNK_BUF, 0, (int) totalRead);
} else {
sb.append(TEXT_CHUNK_BUF);
}
//reset for next chunk
totalRead = 0;
extracted = sb.toString();
//attempt to identify language of extracted text and post it to the blackboard
tikaLanguageIdentifier.addLanguageToBlackBoard(extracted, sourceFile);
//converts BOM automatically to charSet encoding
byte[] encodedBytes = extracted.getBytes(outCharset);
AbstractFileChunk chunk = new AbstractFileChunk(this, this.numChunks + 1);
try {
chunk.index(ingester, encodedBytes, encodedBytes.length, outCharset);
++this.numChunks;
} catch (Ingester.IngesterException ingEx) {
success = false;
logger.log(Level.WARNING, "Ingester had a problem with extracted HTML from file '"
+ sourceFile.getName() + "' (id: " + sourceFile.getId() + ").", ingEx);
throw ingEx; //need to rethrow/return to signal error and move on
}
//check if need invoke commit/search between chunks
//not to delay commit if timer has gone off
module.checkRunCommitSearch();
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to read content stream from " + sourceFile.getId() + ": " + sourceFile.getName(), ex);
success = false;
} catch (Exception ex) {
logger.log(Level.WARNING, "Unexpected error, can't read content stream from " + sourceFile.getId() + ": " + sourceFile.getName(), ex);
success = false;
} finally {
try {
stream.close();
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to close content stream from " + sourceFile.getId(), ex);
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to close content reader from " + sourceFile.getId(), ex);
}
}
//after all chunks, ingest the parent file without content itself, and store numChunks
ingester.ingest(this);
return success;
}
@Override
public boolean isContentTypeSpecific() {
return true;
}
@Override
public boolean isSupported(AbstractFile file, String detectedFormat) {
if (detectedFormat == null) {
return false;
} else if (WEB_MIME_TYPES.contains(detectedFormat) && file.getSize() <= MAX_SIZE) {
return true;
} else {
return false;
}
}
}
| KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/AbstractFileHtmlExtract.java | /*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.StringExtract.StringExtractUnicodeTable.SCRIPT;
import org.sleuthkit.autopsy.keywordsearch.Ingester.IngesterException;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.ReadContentInputStream;
/**
* Extractor of text from HTML supported AbstractFile content. Extracted text is
* divided into chunks and indexed with Solr. If HTML extraction succeeds,
* chunks are indexed with Solr.
*/
public class AbstractFileHtmlExtract implements AbstractFileExtract {
private static final Logger logger = Logger.getLogger(AbstractFileHtmlExtract.class.getName());
static final Charset outCharset = Server.DEFAULT_INDEXED_TEXT_CHARSET;
static final int MAX_EXTR_TEXT_CHARS = 512 * 1024;
private static final int SINGLE_READ_CHARS = 1024;
private static final int EXTRA_CHARS = 128; //for whitespace
private static final char[] TEXT_CHUNK_BUF = new char[MAX_EXTR_TEXT_CHARS];
private KeywordSearchIngestModule module;
private Ingester ingester;
private AbstractFile sourceFile;
private int numChunks = 0;
//private static final String UTF16BOM = "\uFEFF"; disabled prepending of BOM
static final List<String> WEB_MIME_TYPES = Arrays.asList(
"application/javascript",
"application/xhtml+xml",
"application/json",
"text/css",
"text/html",
"text/javascript" //"application/xml",
//"application/xml-dtd",
);
private final TikaLanguageIdentifier tikaLanguageIdentifier;
AbstractFileHtmlExtract() {
tikaLanguageIdentifier = new TikaLanguageIdentifier();
this.module = KeywordSearchIngestModule.getDefault();
ingester = Server.getIngester();
}
@Override
public boolean setScripts(List<SCRIPT> extractScripts) {
return false;
}
@Override
public List<SCRIPT> getScripts() {
return null;
}
@Override
public Map<String, String> getOptions() {
return null;
}
@Override
public void setOptions(Map<String, String> options) {
}
@Override
public int getNumChunks() {
return numChunks;
}
@Override
public AbstractFile getSourceFile() {
return sourceFile;
}
@Override
public boolean index(AbstractFile sourceFile) throws IngesterException {
this.sourceFile = sourceFile;
this.numChunks = 0; //unknown until indexing is done
boolean success = false;
Reader reader = null;
final InputStream stream = new ReadContentInputStream(sourceFile);
try {
// Parse the stream with Jericho
JerichoParserWrapper jpw = new JerichoParserWrapper(stream);
jpw.parse();
reader = jpw.getReader();
// In case there is an exception or parse() isn't called
if (reader == null) {
logger.log(Level.WARNING, "No reader available from HTML parser");
return false;
}
success = true;
long readSize;
long totalRead = 0;
boolean eof = false;
//we read max 1024 chars at time, this seems to max what this Reader would return
while (!eof && (readSize = reader.read(TEXT_CHUNK_BUF, 0, SINGLE_READ_CHARS)) != -1) {
totalRead += readSize;
//consume more bytes to fill entire chunk (leave EXTRA_CHARS to end the word)
while ((totalRead < MAX_EXTR_TEXT_CHARS - SINGLE_READ_CHARS - EXTRA_CHARS)
&& (readSize = reader.read(TEXT_CHUNK_BUF, (int) totalRead, SINGLE_READ_CHARS)) != -1) {
totalRead += readSize;
}
if (readSize == -1) {
//this is the last chunk
eof = true;
} else {
//try to read until whitespace to not break words
while ((totalRead < MAX_EXTR_TEXT_CHARS - 1)
&& !Character.isWhitespace(TEXT_CHUNK_BUF[(int) totalRead - 1])
&& (readSize = reader.read(TEXT_CHUNK_BUF, (int) totalRead, 1)) != -1) {
totalRead += readSize;
}
if (readSize == -1) {
//this is the last chunk
eof = true;
}
}
//logger.log(Level.INFO, "TOTAL READ SIZE: " + totalRead + " file: " + sourceFile.getName());
//encode to bytes to index as byte stream
String extracted;
//add BOM and trim the 0 bytes
//set initial size to chars read + bom - try to prevent from resizing
StringBuilder sb = new StringBuilder((int) totalRead + 1000);
//inject BOM here (saves byte buffer realloc later), will be converted to specific encoding BOM
//sb.append(UTF16BOM); disabled BOM, not needing as bypassing Tika
if (totalRead < MAX_EXTR_TEXT_CHARS) {
sb.append(TEXT_CHUNK_BUF, 0, (int) totalRead);
} else {
sb.append(TEXT_CHUNK_BUF);
}
//reset for next chunk
totalRead = 0;
extracted = sb.toString();
//attempt to identify language of extracted text and post it to the blackboard
tikaLanguageIdentifier.addLanguageToBlackBoard(extracted, sourceFile);
//converts BOM automatically to charSet encoding
byte[] encodedBytes = extracted.getBytes(outCharset);
AbstractFileChunk chunk = new AbstractFileChunk(this, this.numChunks + 1);
try {
chunk.index(ingester, encodedBytes, encodedBytes.length, outCharset);
++this.numChunks;
} catch (Ingester.IngesterException ingEx) {
success = false;
logger.log(Level.WARNING, "Ingester had a problem with extracted HTML from file '"
+ sourceFile.getName() + "' (id: " + sourceFile.getId() + ").", ingEx);
throw ingEx; //need to rethrow/return to signal error and move on
}
//check if need invoke commit/search between chunks
//not to delay commit if timer has gone off
module.checkRunCommitSearch();
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to read content stream from " + sourceFile.getId() + ": " + sourceFile.getName(), ex);
success = false;
} catch (Exception ex) {
logger.log(Level.WARNING, "Unexpected error, can't read content stream from " + sourceFile.getId() + ": " + sourceFile.getName(), ex);
success = false;
} finally {
try {
stream.close();
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to close content stream from " + sourceFile.getId(), ex);
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Unable to close content reader from " + sourceFile.getId(), ex);
}
}
//after all chunks, ingest the parent file without content itself, and store numChunks
ingester.ingest(this);
return success;
}
@Override
public boolean isContentTypeSpecific() {
return true;
}
@Override
public boolean isSupported(AbstractFile file, String detectedFormat) {
if (detectedFormat == null) {
return false;
} else if (WEB_MIME_TYPES.contains(detectedFormat)) {
return true;
} else {
return false;
}
}
}
| Bypass jericho on files larger than 10 mb
| KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/AbstractFileHtmlExtract.java | Bypass jericho on files larger than 10 mb |
|
Java | apache-2.0 | aea6d7da2737d1c8845ca936a8dff20d86dd1927 | 0 | raehalme/keycloak,stianst/keycloak,mhajas/keycloak,mhajas/keycloak,raehalme/keycloak,jpkrohling/keycloak,stianst/keycloak,keycloak/keycloak,jpkrohling/keycloak,hmlnarik/keycloak,abstractj/keycloak,srose/keycloak,stianst/keycloak,keycloak/keycloak,mhajas/keycloak,abstractj/keycloak,jpkrohling/keycloak,mhajas/keycloak,abstractj/keycloak,srose/keycloak,reneploetz/keycloak,srose/keycloak,hmlnarik/keycloak,raehalme/keycloak,keycloak/keycloak,stianst/keycloak,hmlnarik/keycloak,reneploetz/keycloak,srose/keycloak,hmlnarik/keycloak,keycloak/keycloak,stianst/keycloak,reneploetz/keycloak,abstractj/keycloak,hmlnarik/keycloak,hmlnarik/keycloak,abstractj/keycloak,reneploetz/keycloak,srose/keycloak,reneploetz/keycloak,raehalme/keycloak,jpkrohling/keycloak,keycloak/keycloak,raehalme/keycloak,jpkrohling/keycloak,raehalme/keycloak,mhajas/keycloak | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.sessions.infinispan;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.context.Flag;
import org.infinispan.stream.CacheCollectors;
import org.jboss.logging.Logger;
import org.keycloak.cluster.ClusterProvider;
import org.keycloak.common.util.Retry;
import org.keycloak.common.util.Time;
import org.keycloak.device.DeviceActivityManager;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelException;
import org.keycloak.models.OfflineUserSessionModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.UserSessionSpi;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.sessions.infinispan.changes.Tasks;
import org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore;
import org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore;
import org.keycloak.models.sessions.infinispan.entities.SessionEntity;
import org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker;
import org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper;
import org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction;
import org.keycloak.models.sessions.infinispan.changes.SessionUpdateTask;
import org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity;
import org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore;
import org.keycloak.models.sessions.infinispan.entities.UserSessionEntity;
import org.keycloak.models.sessions.infinispan.events.RealmRemovedSessionEvent;
import org.keycloak.models.sessions.infinispan.events.RemoveUserSessionsEvent;
import org.keycloak.models.sessions.infinispan.events.SessionEventsSenderTransaction;
import org.keycloak.models.sessions.infinispan.stream.Comparators;
import org.keycloak.models.sessions.infinispan.stream.Mappers;
import org.keycloak.models.sessions.infinispan.stream.SessionPredicate;
import org.keycloak.models.sessions.infinispan.stream.UserSessionPredicate;
import org.keycloak.models.sessions.infinispan.util.FuturesHelper;
import org.keycloak.models.sessions.infinispan.util.InfinispanKeyGenerator;
import org.keycloak.connections.infinispan.InfinispanUtil;
import org.keycloak.models.sessions.infinispan.util.SessionTimeouts;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.keycloak.utils.StreamsUtil.paginatedStream;
/**
* @author <a href="mailto:[email protected]">Stian Thorgersen</a>
*/
public class InfinispanUserSessionProvider implements UserSessionProvider {
private static final Logger log = Logger.getLogger(InfinispanUserSessionProvider.class);
protected final KeycloakSession session;
protected final Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionCache;
protected final Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionCache;
protected final Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache;
protected final Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionCache;
protected final InfinispanChangelogBasedTransaction<String, UserSessionEntity> sessionTx;
protected final InfinispanChangelogBasedTransaction<String, UserSessionEntity> offlineSessionTx;
protected final InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionTx;
protected final InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> offlineClientSessionTx;
protected final SessionEventsSenderTransaction clusterEventsSenderTx;
protected final CrossDCLastSessionRefreshStore lastSessionRefreshStore;
protected final CrossDCLastSessionRefreshStore offlineLastSessionRefreshStore;
protected final PersisterLastSessionRefreshStore persisterLastSessionRefreshStore;
protected final RemoteCacheInvoker remoteCacheInvoker;
protected final InfinispanKeyGenerator keyGenerator;
protected final boolean loadOfflineSessionsFromDatabase;
public InfinispanUserSessionProvider(KeycloakSession session,
RemoteCacheInvoker remoteCacheInvoker,
CrossDCLastSessionRefreshStore lastSessionRefreshStore,
CrossDCLastSessionRefreshStore offlineLastSessionRefreshStore,
PersisterLastSessionRefreshStore persisterLastSessionRefreshStore,
InfinispanKeyGenerator keyGenerator,
Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionCache,
Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionCache,
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache,
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionCache,
boolean loadOfflineSessionsFromDatabase) {
this.session = session;
this.sessionCache = sessionCache;
this.clientSessionCache = clientSessionCache;
this.offlineSessionCache = offlineSessionCache;
this.offlineClientSessionCache = offlineClientSessionCache;
this.sessionTx = new InfinispanChangelogBasedTransaction<>(session, sessionCache, remoteCacheInvoker, SessionTimeouts::getUserSessionLifespanMs, SessionTimeouts::getUserSessionMaxIdleMs);
this.offlineSessionTx = new InfinispanChangelogBasedTransaction<>(session, offlineSessionCache, remoteCacheInvoker, SessionTimeouts::getOfflineSessionLifespanMs, SessionTimeouts::getOfflineSessionMaxIdleMs);
this.clientSessionTx = new InfinispanChangelogBasedTransaction<>(session, clientSessionCache, remoteCacheInvoker, SessionTimeouts::getClientSessionLifespanMs, SessionTimeouts::getClientSessionMaxIdleMs);
this.offlineClientSessionTx = new InfinispanChangelogBasedTransaction<>(session, offlineClientSessionCache, remoteCacheInvoker, SessionTimeouts::getOfflineClientSessionLifespanMs, SessionTimeouts::getOfflineClientSessionMaxIdleMs);
this.clusterEventsSenderTx = new SessionEventsSenderTransaction(session);
this.lastSessionRefreshStore = lastSessionRefreshStore;
this.offlineLastSessionRefreshStore = offlineLastSessionRefreshStore;
this.persisterLastSessionRefreshStore = persisterLastSessionRefreshStore;
this.remoteCacheInvoker = remoteCacheInvoker;
this.keyGenerator = keyGenerator;
this.loadOfflineSessionsFromDatabase = loadOfflineSessionsFromDatabase;
session.getTransactionManager().enlistAfterCompletion(clusterEventsSenderTx);
session.getTransactionManager().enlistAfterCompletion(sessionTx);
session.getTransactionManager().enlistAfterCompletion(offlineSessionTx);
session.getTransactionManager().enlistAfterCompletion(clientSessionTx);
session.getTransactionManager().enlistAfterCompletion(offlineClientSessionTx);
}
protected Cache<String, SessionEntityWrapper<UserSessionEntity>> getCache(boolean offline) {
return offline ? offlineSessionCache : sessionCache;
}
protected InfinispanChangelogBasedTransaction<String, UserSessionEntity> getTransaction(boolean offline) {
return offline ? offlineSessionTx : sessionTx;
}
protected Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> getClientSessionCache(boolean offline) {
return offline ? offlineClientSessionCache : clientSessionCache;
}
protected InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> getClientSessionTransaction(boolean offline) {
return offline ? offlineClientSessionTx : clientSessionTx;
}
protected CrossDCLastSessionRefreshStore getLastSessionRefreshStore() {
return lastSessionRefreshStore;
}
protected CrossDCLastSessionRefreshStore getOfflineLastSessionRefreshStore() {
return offlineLastSessionRefreshStore;
}
protected PersisterLastSessionRefreshStore getPersisterLastSessionRefreshStore() {
return persisterLastSessionRefreshStore;
}
@Override
public KeycloakSession getKeycloakSession() {
return session;
}
@Override
public AuthenticatedClientSessionModel createClientSession(RealmModel realm, ClientModel client, UserSessionModel userSession) {
final UUID clientSessionId = keyGenerator.generateKeyUUID(session, clientSessionCache);
AuthenticatedClientSessionEntity entity = new AuthenticatedClientSessionEntity(clientSessionId);
entity.setRealmId(realm.getId());
entity.setTimestamp(Time.currentTime());
entity.getNotes().put(AuthenticatedClientSessionModel.STARTED_AT_NOTE, String.valueOf(entity.getTimestamp()));
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(false);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(false);
AuthenticatedClientSessionAdapter adapter = new AuthenticatedClientSessionAdapter(session, this, entity, client, userSession, clientSessionUpdateTx, false);
// For now, the clientSession is considered transient in case that userSession was transient
UserSessionModel.SessionPersistenceState persistenceState = (userSession instanceof UserSessionAdapter && ((UserSessionAdapter) userSession).getPersistenceState() != null) ?
((UserSessionAdapter) userSession).getPersistenceState() : UserSessionModel.SessionPersistenceState.PERSISTENT;
SessionUpdateTask<AuthenticatedClientSessionEntity> createClientSessionTask = Tasks.addIfAbsentSync();
clientSessionUpdateTx.addTask(clientSessionId, createClientSessionTask, entity, persistenceState);
SessionUpdateTask registerClientSessionTask = new RegisterClientSessionTask(client.getId(), clientSessionId);
userSessionUpdateTx.addTask(userSession.getId(), registerClientSessionTask);
return adapter;
}
@Override
public UserSessionModel createUserSession(RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
final String userSessionId = keyGenerator.generateKeyString(session, sessionCache);
return createUserSession(userSessionId, realm, user, loginUsername, ipAddress, authMethod, rememberMe, brokerSessionId, brokerUserId, UserSessionModel.SessionPersistenceState.PERSISTENT);
}
@Override
public UserSessionModel createUserSession(String id, RealmModel realm, UserModel user, String loginUsername, String ipAddress,
String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId, UserSessionModel.SessionPersistenceState persistenceState) {
UserSessionEntity entity = new UserSessionEntity();
entity.setId(id);
updateSessionEntity(entity, realm, user, loginUsername, ipAddress, authMethod, rememberMe, brokerSessionId, brokerUserId);
SessionUpdateTask<UserSessionEntity> createSessionTask = Tasks.addIfAbsentSync();
sessionTx.addTask(id, createSessionTask, entity, persistenceState);
UserSessionAdapter adapter = wrap(realm, entity, false);
adapter.setPersistenceState(persistenceState);
if (adapter != null) {
DeviceActivityManager.attachDevice(adapter, session);
}
return adapter;
}
void updateSessionEntity(UserSessionEntity entity, RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
entity.setRealmId(realm.getId());
entity.setUser(user.getId());
entity.setLoginUsername(loginUsername);
entity.setIpAddress(ipAddress);
entity.setAuthMethod(authMethod);
entity.setRememberMe(rememberMe);
entity.setBrokerSessionId(brokerSessionId);
entity.setBrokerUserId(brokerUserId);
int currentTime = Time.currentTime();
entity.setStarted(currentTime);
entity.setLastSessionRefresh(currentTime);
}
@Override
public UserSessionModel getUserSession(RealmModel realm, String id) {
return getUserSession(realm, id, false);
}
protected UserSessionAdapter getUserSession(RealmModel realm, String id, boolean offline) {
UserSessionEntity userSessionEntityFromCache = getUserSessionEntity(realm, id, offline);
if (userSessionEntityFromCache != null) {
return wrap(realm, userSessionEntityFromCache, offline);
}
if (!offline) {
return null;
}
// Try to recover from potentially lost offline-sessions by attempting to fetch and re-import
// the offline session information from the PersistenceProvider.
UserSessionEntity userSessionEntityFromPersistenceProvider = getUserSessionEntityFromPersistenceProvider(realm, id, offline);
if (userSessionEntityFromPersistenceProvider != null) {
// we successfully recovered the offline session!
return wrap(realm, userSessionEntityFromPersistenceProvider, offline);
}
// no luck, the session is really not there anymore
return null;
}
private UserSessionEntity getUserSessionEntityFromPersistenceProvider(RealmModel realm, String sessionId, boolean offline) {
log.debugf("Offline user-session not found in infinispan, attempting UserSessionPersisterProvider lookup for sessionId=%s", sessionId);
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
UserSessionModel persistentUserSession = persister.loadUserSession(realm, sessionId, offline);
if (persistentUserSession == null) {
log.debugf("Offline user-session not found in UserSessionPersisterProvider for sessionId=%s", sessionId);
return null;
}
return importUserSession(realm, offline, persistentUserSession);
}
private UserSessionEntity getUserSessionEntityFromCacheOrImportIfNecessary(RealmModel realm, boolean offline, UserSessionModel persistentUserSession) {
UserSessionEntity userSessionEntity = getUserSessionEntity(realm, persistentUserSession.getId(), offline);
if (userSessionEntity != null) {
// user session present in cache, return existing session
return userSessionEntity;
}
return importUserSession(realm, offline, persistentUserSession);
}
private UserSessionEntity importUserSession(RealmModel realm, boolean offline, UserSessionModel persistentUserSession) {
String sessionId = persistentUserSession.getId();
log.debugf("Attempting to import user-session for sessionId=%s offline=%s", sessionId, offline);
session.sessions().importUserSessions(Collections.singleton(persistentUserSession), offline);
log.debugf("user-session imported, trying another lookup for sessionId=%s offline=%s", sessionId, offline);
UserSessionEntity ispnUserSessionEntity = getUserSessionEntity(realm, sessionId, offline);
if (ispnUserSessionEntity != null) {
log.debugf("user-session found after import for sessionId=%s offline=%s", sessionId, offline);
return ispnUserSessionEntity;
}
log.debugf("user-session could not be found after import for sessionId=%s offline=%s", sessionId, offline);
return null;
}
private UserSessionEntity getUserSessionEntity(RealmModel realm, String id, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> tx = getTransaction(offline);
SessionEntityWrapper<UserSessionEntity> entityWrapper = tx.get(id);
if (entityWrapper==null) return null;
UserSessionEntity entity = entityWrapper.getEntity();
if (!entity.getRealmId().equals(realm.getId())) return null;
return entity;
}
private Stream<UserSessionModel> getUserSessionsFromPersistenceProviderStream(RealmModel realm, UserModel user, boolean offline) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.loadUserSessionsStream(realm, user, offline, 0, null)
.map(persistentUserSession -> getUserSessionEntityFromCacheOrImportIfNecessary(realm, offline, persistentUserSession))
.filter(Objects::nonNull)
.map(userSessionEntity -> wrap(realm, userSessionEntity, offline));
}
protected Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserSessionPredicate predicate, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the offline user-sessions from the persistence provider
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
if (predicate.getUserId() != null) {
UserModel user = session.users().getUserById(realm, predicate.getUserId());
if (user != null) {
return persister.loadUserSessionsStream(realm, user, true, 0, null);
}
}
if (predicate.getBrokerUserId() != null) {
String[] idpAliasSessionId = predicate.getBrokerUserId().split("\\.");
Map<String, String> attributes = new HashMap<>();
attributes.put(UserModel.IDP_ALIAS, idpAliasSessionId[0]);
attributes.put(UserModel.IDP_USER_ID, idpAliasSessionId[1]);
UserProvider userProvider = session.getProvider(UserProvider.class);
UserModel userModel = userProvider.searchForUserStream(realm, attributes, 0, null).findFirst().orElse(null);
return userModel != null ?
persister.loadUserSessionsStream(realm, userModel, true, 0, null) :
Stream.empty();
}
if (predicate.getBrokerSessionId() != null) {
// TODO add support for offline user-session lookup by brokerSessionId
// currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way
throw new ModelException("Dynamic database lookup for offline user-sessions by broker session ID is currently only supported for preloaded sessions. " +
"Set preloadOfflineSessionsFromDatabase option to \"true\" in " + UserSessionSpi.NAME + " SPI in "
+ InfinispanUserSessionProviderFactory.PROVIDER_ID + " provider to enable the lookup.");
}
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
// return a stream that 'wraps' the infinispan cache stream so that the cache stream's elements are read one by one
// and then mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
return StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false)
.map(Mappers.userSessionEntity())
.map(entity -> this.wrap(realm, entity, offline));
}
@Override
public AuthenticatedClientSessionAdapter getClientSession(UserSessionModel userSession, ClientModel client, String clientSessionId, boolean offline) {
return getClientSession(userSession, client, clientSessionId == null ? null : UUID.fromString(clientSessionId), offline);
}
@Override
public AuthenticatedClientSessionAdapter getClientSession(UserSessionModel userSession, ClientModel client, UUID clientSessionId, boolean offline) {
AuthenticatedClientSessionEntity entity = getClientSessionEntity(clientSessionId, offline);
return wrap(userSession, client, entity, offline);
}
private AuthenticatedClientSessionEntity getClientSessionEntity(UUID id, boolean offline) {
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> tx = getClientSessionTransaction(offline);
SessionEntityWrapper<AuthenticatedClientSessionEntity> entityWrapper = tx.get(id);
return entityWrapper == null ? null : entityWrapper.getEntity();
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(final RealmModel realm, UserModel user) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).user(user.getId()), false);
}
@Override
public Stream<UserSessionModel> getUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerUserId(brokerUserId), false);
}
@Override
public UserSessionModel getUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId) {
return this.getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerSessionId(brokerSessionId), false)
.findFirst().orElse(null);
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client) {
return getUserSessionsStream(realm, client, -1, -1);
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults) {
return getUserSessionsStream(realm, client, firstResult, maxResults, false);
}
protected Stream<UserSessionModel> getUserSessionsStream(final RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults, final boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the actual offline user session count from the database
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.loadUserSessionsStream(realm, client, true, firstResult, maxResults);
}
final String clientUuid = client.getId();
UserSessionPredicate predicate = UserSessionPredicate.create(realm.getId()).client(clientUuid);
return getUserSessionModels(realm, firstResult, maxResults, offline, predicate);
}
protected Stream<UserSessionModel> getUserSessionModels(RealmModel realm, Integer firstResult, Integer maxResults, boolean offline, UserSessionPredicate predicate) {
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
// return a stream that 'wraps' the infinispan cache stream so that the cache stream's elements are read one by one
// and then filtered/mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
Stream<UserSessionEntity> stream = StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false)
.map(Mappers.userSessionEntity())
.sorted(Comparators.userSessionLastSessionRefresh());
return paginatedStream(stream, firstResult, maxResults).map(entity -> this.wrap(realm, entity, offline));
}
@Override
public UserSessionModel getUserSessionWithPredicate(RealmModel realm, String id, boolean offline, Predicate<UserSessionModel> predicate) {
UserSessionModel userSession = getUserSession(realm, id, offline);
if (userSession == null) {
return null;
}
// We have userSession, which passes predicate. No need for remote lookup.
if (predicate.test(userSession)) {
log.debugf("getUserSessionWithPredicate(%s): found in local cache", id);
return userSession;
}
// Try lookup userSession from remoteCache
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
if (remoteCache != null) {
SessionEntityWrapper<UserSessionEntity> remoteSessionEntityWrapper = (SessionEntityWrapper<UserSessionEntity>) remoteCache.get(id);
if (remoteSessionEntityWrapper != null) {
UserSessionEntity remoteSessionEntity = remoteSessionEntityWrapper.getEntity();
log.debugf("getUserSessionWithPredicate(%s): remote cache contains session entity %s", id, remoteSessionEntity);
UserSessionModel remoteSessionAdapter = wrap(realm, remoteSessionEntity, offline);
if (predicate.test(remoteSessionAdapter)) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> tx = getTransaction(offline);
// Remote entity contains our predicate. Update local cache with the remote entity
SessionEntityWrapper<UserSessionEntity> sessionWrapper = remoteSessionEntity.mergeRemoteEntityWithLocalEntity(tx.get(id));
// Replace entity just in ispn cache. Skip remoteStore
cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_STORE, Flag.SKIP_CACHE_LOAD, Flag.IGNORE_RETURN_VALUES)
.replace(id, sessionWrapper);
tx.reloadEntityInCurrentTransaction(realm, id, sessionWrapper);
// Recursion. We should have it locally now
return getUserSessionWithPredicate(realm, id, offline, predicate);
} else {
log.debugf("getUserSessionWithPredicate(%s): found, but predicate doesn't pass", id);
return null;
}
} else {
log.debugf("getUserSessionWithPredicate(%s): not found", id);
// Session not available on remoteCache. Was already removed there. So removing locally too.
// TODO: Can be optimized to skip calling remoteCache.remove
removeUserSession(realm, userSession);
return null;
}
} else {
log.debugf("getUserSessionWithPredicate(%s): remote cache not available", id);
return null;
}
}
@Override
public long getActiveUserSessions(RealmModel realm, ClientModel client) {
return getUserSessionsCount(realm, client, false);
}
@Override
public Map<String, Long> getActiveClientSessionStats(RealmModel realm, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.getUserSessionsCountsByClients(realm, true);
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
return cache.entrySet().stream()
.filter(UserSessionPredicate.create(realm.getId()))
.map(Mappers.authClientSessionSetMapper())
.flatMap((Serializable & Function<Set<String>, Stream<? extends String>>)Mappers::toStream)
.collect(
CacheCollectors.serializableCollector(
() -> Collectors.groupingBy(Function.identity(), Collectors.counting())
)
);
}
protected long getUserSessionsCount(RealmModel realm, ClientModel client, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the actual offline user session count from the database
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.getUserSessionsCount(realm, client, true);
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
final String clientUuid = client.getId();
return cache.entrySet().stream()
.filter(UserSessionPredicate.create(realm.getId()).client(clientUuid))
.count();
}
@Override
public void removeUserSession(RealmModel realm, UserSessionModel session) {
UserSessionEntity entity = getUserSessionEntity(realm, session, false);
if (entity != null) {
removeUserSession(entity, false);
}
}
@Override
public void removeUserSessions(RealmModel realm, UserModel user) {
removeUserSessions(realm, user, false);
}
protected void removeUserSessions(RealmModel realm, UserModel user, boolean offline) {
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
Iterator<UserSessionEntity> itr = cache.entrySet().stream().filter(UserSessionPredicate.create(realm.getId()).user(user.getId())).map(Mappers.userSessionEntity()).iterator();
while (itr.hasNext()) {
UserSessionEntity userSessionEntity = itr.next();
removeUserSession(userSessionEntity, offline);
}
}
public void removeAllExpired() {
// Rely on expiration of cache entries provided by infinispan. Just expire entries from persister is needed
// TODO: Avoid iteration over all realms here (Details in the KEYCLOAK-16802)
session.realms().getRealmsStream().forEach(this::removeExpired);
}
@Override
public void removeExpired(RealmModel realm) {
// Rely on expiration of cache entries provided by infinispan. Nothing needed here besides calling persister
session.getProvider(UserSessionPersisterProvider.class).removeExpired(realm);
}
@Override
public void removeUserSessions(RealmModel realm) {
// Don't send message to all DCs, just to all cluster nodes in current DC. The remoteCache will notify client listeners for removed userSessions.
clusterEventsSenderTx.addEvent(
RemoveUserSessionsEvent.createEvent(RemoveUserSessionsEvent.class, InfinispanUserSessionProviderFactory.REMOVE_USER_SESSIONS_EVENT, session, realm.getId(), true),
ClusterProvider.DCNotify.LOCAL_DC_ONLY);
}
protected void onRemoveUserSessionsEvent(String realmId) {
removeLocalUserSessions(realmId, false);
}
// public for usage in the testsuite
public void removeLocalUserSessions(String realmId, boolean offline) {
FuturesHelper futures = new FuturesHelper();
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
Cache<String, SessionEntityWrapper<UserSessionEntity>> localCache = CacheDecorators.localCache(cache);
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache = getClientSessionCache(offline);
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> localClientSessionCache = CacheDecorators.localCache(clientSessionCache);
Cache<String, SessionEntityWrapper<UserSessionEntity>> localCacheStoreIgnore = CacheDecorators.skipCacheLoaders(localCache);
final AtomicInteger userSessionsSize = new AtomicInteger();
localCacheStoreIgnore
.entrySet()
.stream()
.filter(SessionPredicate.create(realmId))
.map(Mappers.userSessionEntity())
.forEach(new Consumer<UserSessionEntity>() {
@Override
public void accept(UserSessionEntity userSessionEntity) {
userSessionsSize.incrementAndGet();
// Remove session from remoteCache too. Use removeAsync for better perf
Future future = localCache.removeAsync(userSessionEntity.getId());
futures.addTask(future);
userSessionEntity.getAuthenticatedClientSessions().forEach((clientUUID, clientSessionId) -> {
Future f = localClientSessionCache.removeAsync(clientSessionId);
futures.addTask(f);
});
}
});
futures.waitForAllToFinish();
log.debugf("Removed %d sessions in realm %s. Offline: %b", (Object) userSessionsSize.get(), realmId, offline);
}
@Override
public void onRealmRemoved(RealmModel realm) {
// Don't send message to all DCs, just to all cluster nodes in current DC. The remoteCache will notify client listeners for removed userSessions.
clusterEventsSenderTx.addEvent(
RealmRemovedSessionEvent.createEvent(RealmRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.REALM_REMOVED_SESSION_EVENT, session, realm.getId(), true),
ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onRealmRemoved(realm);
}
}
protected void onRealmRemovedEvent(String realmId) {
removeLocalUserSessions(realmId, true);
removeLocalUserSessions(realmId, false);
}
@Override
public void onClientRemoved(RealmModel realm, ClientModel client) {
// clusterEventsSenderTx.addEvent(
// ClientRemovedSessionEvent.createEvent(ClientRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.CLIENT_REMOVED_SESSION_EVENT, session, realm.getId(), true),
// ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onClientRemoved(realm, client);
}
}
protected void onClientRemovedEvent(String realmId, String clientUuid) {
// Nothing for now. userSession.getAuthenticatedClientSessions() will check lazily if particular client exists and update userSession on-the-fly.
}
protected void onUserRemoved(RealmModel realm, UserModel user) {
removeUserSessions(realm, user, true);
removeUserSessions(realm, user, false);
UserSessionPersisterProvider persisterProvider = session.getProvider(UserSessionPersisterProvider.class);
if (persisterProvider != null) {
persisterProvider.onUserRemoved(realm, user);
}
}
@Override
public void close() {
}
@Override
public int getStartupTime(RealmModel realm) {
// TODO: take realm.getNotBefore() into account?
return session.getProvider(ClusterProvider.class).getClusterStartupTime();
}
protected void removeUserSession(UserSessionEntity sessionEntity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
sessionEntity.getAuthenticatedClientSessions().forEach((clientUUID, clientSessionId) -> clientSessionUpdateTx.addTask(clientSessionId, Tasks.removeSync()));
SessionUpdateTask<UserSessionEntity> removeTask = Tasks.removeSync();
userSessionUpdateTx.addTask(sessionEntity.getId(), removeTask);
}
UserSessionAdapter wrap(RealmModel realm, UserSessionEntity entity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
return entity != null ? new UserSessionAdapter(session, this, userSessionUpdateTx, clientSessionUpdateTx, realm, entity, offline) : null;
}
AuthenticatedClientSessionAdapter wrap(UserSessionModel userSession, ClientModel client, AuthenticatedClientSessionEntity entity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
return entity != null ? new AuthenticatedClientSessionAdapter(session,this, entity, client, userSession, clientSessionUpdateTx, offline) : null;
}
UserSessionEntity getUserSessionEntity(RealmModel realm, UserSessionModel userSession, boolean offline) {
if (userSession instanceof UserSessionAdapter) {
if (!userSession.getRealm().equals(realm)) return null;
return ((UserSessionAdapter) userSession).getEntity();
} else {
return getUserSessionEntity(realm, userSession.getId(), offline);
}
}
@Override
public UserSessionModel createOfflineUserSession(UserSessionModel userSession) {
UserSessionAdapter offlineUserSession = importUserSession(userSession, true);
// started and lastSessionRefresh set to current time
int currentTime = Time.currentTime();
offlineUserSession.getEntity().setStarted(currentTime);
offlineUserSession.getEntity().setLastSessionRefresh(currentTime);
session.getProvider(UserSessionPersisterProvider.class).createUserSession(userSession, true);
return offlineUserSession;
}
@Override
public UserSessionAdapter getOfflineUserSession(RealmModel realm, String userSessionId) {
return getUserSession(realm, userSessionId, true);
}
@Override
public UserSessionModel getOfflineUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId) {
return this.getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerSessionId(brokerSessionId), true)
.findFirst().orElse(null);
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerUserId(brokerUserId), true);
}
@Override
public void removeOfflineUserSession(RealmModel realm, UserSessionModel userSession) {
UserSessionEntity userSessionEntity = getUserSessionEntity(realm, userSession, true);
if (userSessionEntity != null) {
removeUserSession(userSessionEntity, true);
}
session.getProvider(UserSessionPersisterProvider.class).removeUserSession(userSession.getId(), true);
}
@Override
public AuthenticatedClientSessionModel createOfflineClientSession(AuthenticatedClientSessionModel clientSession, UserSessionModel offlineUserSession) {
UserSessionAdapter userSessionAdapter = (offlineUserSession instanceof UserSessionAdapter) ? (UserSessionAdapter) offlineUserSession :
getOfflineUserSession(offlineUserSession.getRealm(), offlineUserSession.getId());
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(true);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(true);
AuthenticatedClientSessionAdapter offlineClientSession = importClientSession(userSessionAdapter, clientSession, userSessionUpdateTx, clientSessionUpdateTx, true);
// update timestamp to current time
offlineClientSession.setTimestamp(Time.currentTime());
offlineClientSession.getNotes().put(AuthenticatedClientSessionModel.STARTED_AT_NOTE, String.valueOf(offlineClientSession.getTimestamp()));
session.getProvider(UserSessionPersisterProvider.class).createClientSession(clientSession, true);
return offlineClientSession;
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, UserModel user) {
if (loadOfflineSessionsFromDatabase) {
return getUserSessionsFromPersistenceProviderStream(realm, user, true);
}
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).user(user.getId()), true);
}
@Override
public long getOfflineSessionsCount(RealmModel realm, ClientModel client) {
return getUserSessionsCount(realm, client, true);
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, ClientModel client, Integer first, Integer max) {
return getUserSessionsStream(realm, client, first, max, true);
}
@Override
public void importUserSessions(Collection<UserSessionModel> persistentUserSessions, boolean offline) {
if (persistentUserSessions == null || persistentUserSessions.isEmpty()) {
return;
}
Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionsById = new HashMap<>();
Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsById = persistentUserSessions.stream()
.map((UserSessionModel persistentUserSession) -> {
UserSessionEntity userSessionEntityToImport = createUserSessionEntityInstance(persistentUserSession);
for (Map.Entry<String, AuthenticatedClientSessionModel> entry : persistentUserSession.getAuthenticatedClientSessions().entrySet()) {
String clientUUID = entry.getKey();
AuthenticatedClientSessionModel clientSession = entry.getValue();
AuthenticatedClientSessionEntity clientSessionToImport = createAuthenticatedClientSessionInstance(clientSession, userSessionEntityToImport.getRealmId(), offline);
// Update timestamp to same value as userSession. LastSessionRefresh of userSession from DB will have correct value
clientSessionToImport.setTimestamp(userSessionEntityToImport.getLastSessionRefresh());
clientSessionsById.put(clientSessionToImport.getId(), new SessionEntityWrapper<>(clientSessionToImport));
// Update userSession entity with the clientSession
AuthenticatedClientSessionStore clientSessions = userSessionEntityToImport.getAuthenticatedClientSessions();
clientSessions.put(clientUUID, clientSessionToImport.getId());
}
return userSessionEntityToImport;
})
.map(SessionEntityWrapper::new)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
// Directly put all entities to the infinispan cache
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = CacheDecorators.skipCacheLoaders(getCache(offline));
boolean importWithExpiration = sessionsById.size() == 1;
if (importWithExpiration) {
importSessionsWithExpiration(sessionsById, cache,
offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,
offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
} else {
cache.putAll(sessionsById);
}
// put all entities to the remoteCache (if exists)
RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
if (remoteCache != null) {
Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsByIdForTransport = sessionsById.values().stream()
.map(SessionEntityWrapper::forTransport)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
if (importWithExpiration) {
importSessionsWithExpiration(sessionsByIdForTransport, remoteCache,
offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,
offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
} else {
Retry.executeWithBackoff((int iteration) -> {
try {
remoteCache.putAll(sessionsByIdForTransport);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsByIdForTransport.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
}
}
// Import client sessions
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessCache = offline ? offlineClientSessionCache : clientSessionCache;
clientSessCache = CacheDecorators.skipCacheLoaders(clientSessCache);
if (importWithExpiration) {
importSessionsWithExpiration(clientSessionsById, clientSessCache,
offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,
offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
} else {
clientSessCache.putAll(clientSessionsById);
}
// put all entities to the remoteCache (if exists)
RemoteCache remoteCacheClientSessions = InfinispanUtil.getRemoteCache(clientSessCache);
if (remoteCacheClientSessions != null) {
Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> sessionsByIdForTransport = clientSessionsById.values().stream()
.map(SessionEntityWrapper::forTransport)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
if (importWithExpiration) {
importSessionsWithExpiration(sessionsByIdForTransport, remoteCacheClientSessions,
offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,
offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
} else {
Retry.executeWithBackoff((int iteration) -> {
try {
remoteCacheClientSessions.putAll(sessionsByIdForTransport);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d client sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsByIdForTransport.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
}
}
}
private <T extends SessionEntity> void importSessionsWithExpiration(Map<? extends Object, SessionEntityWrapper<T>> sessionsById,
BasicCache cache, BiFunction<RealmModel, T, Long> lifespanMsCalculator,
BiFunction<RealmModel, T, Long> maxIdleTimeMsCalculator) {
sessionsById.forEach((id, sessionEntityWrapper) -> {
T sessionEntity = sessionEntityWrapper.getEntity();
RealmModel currentRealm = session.realms().getRealm(sessionEntity.getRealmId());
long lifespan = lifespanMsCalculator.apply(currentRealm, sessionEntity);
long maxIdle = maxIdleTimeMsCalculator.apply(currentRealm, sessionEntity);
if(lifespan != SessionTimeouts.ENTRY_EXPIRED_FLAG
&& maxIdle != SessionTimeouts.ENTRY_EXPIRED_FLAG ) {
if (cache instanceof RemoteCache) {
Retry.executeWithBackoff((int iteration) -> {
try {
cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsById.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
} else {
cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
}
}
});
}
// Imports just userSession without it's clientSessions
protected UserSessionAdapter importUserSession(UserSessionModel userSession, boolean offline) {
UserSessionEntity entity = createUserSessionEntityInstance(userSession);
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
SessionUpdateTask<UserSessionEntity> importTask = Tasks.addIfAbsentSync();
userSessionUpdateTx.addTask(userSession.getId(), importTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
UserSessionAdapter importedSession = wrap(userSession.getRealm(), entity, offline);
return importedSession;
}
private UserSessionEntity createUserSessionEntityInstance(UserSessionModel userSession) {
UserSessionEntity entity = new UserSessionEntity();
entity.setId(userSession.getId());
entity.setRealmId(userSession.getRealm().getId());
entity.setAuthMethod(userSession.getAuthMethod());
entity.setBrokerSessionId(userSession.getBrokerSessionId());
entity.setBrokerUserId(userSession.getBrokerUserId());
entity.setIpAddress(userSession.getIpAddress());
entity.setNotes(userSession.getNotes() == null ? new ConcurrentHashMap<>() : userSession.getNotes());
entity.setAuthenticatedClientSessions(new AuthenticatedClientSessionStore());
entity.setRememberMe(userSession.isRememberMe());
entity.setState(userSession.getState());
if (userSession instanceof OfflineUserSessionModel) {
// this is a hack so that UserModel doesn't have to be available when offline token is imported.
// see related JIRA - KEYCLOAK-5350 and corresponding test
OfflineUserSessionModel oline = (OfflineUserSessionModel)userSession;
entity.setUser(oline.getUserId());
// NOTE: Hack
// We skip calling entity.setLoginUsername(userSession.getLoginUsername())
} else {
entity.setLoginUsername(userSession.getLoginUsername());
entity.setUser(userSession.getUser().getId());
}
entity.setStarted(userSession.getStarted());
entity.setLastSessionRefresh(userSession.getLastSessionRefresh());
return entity;
}
private AuthenticatedClientSessionAdapter importClientSession(UserSessionAdapter sessionToImportInto, AuthenticatedClientSessionModel clientSession,
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx,
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx,
boolean offline) {
AuthenticatedClientSessionEntity entity = createAuthenticatedClientSessionInstance(clientSession, sessionToImportInto.getRealm().getId(), offline);
final UUID clientSessionId = entity.getId();
SessionUpdateTask<AuthenticatedClientSessionEntity> createClientSessionTask = Tasks.addIfAbsentSync();
clientSessionUpdateTx.addTask(entity.getId(), createClientSessionTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
AuthenticatedClientSessionStore clientSessions = sessionToImportInto.getEntity().getAuthenticatedClientSessions();
clientSessions.put(clientSession.getClient().getId(), clientSessionId);
SessionUpdateTask registerClientSessionTask = new RegisterClientSessionTask(clientSession.getClient().getId(), clientSessionId);
userSessionUpdateTx.addTask(sessionToImportInto.getId(), registerClientSessionTask);
return new AuthenticatedClientSessionAdapter(session,this, entity, clientSession.getClient(), sessionToImportInto, clientSessionUpdateTx, offline);
}
private AuthenticatedClientSessionEntity createAuthenticatedClientSessionInstance(AuthenticatedClientSessionModel clientSession, String realmId, boolean offline) {
final UUID clientSessionId = keyGenerator.generateKeyUUID(session, getClientSessionCache(offline));
AuthenticatedClientSessionEntity entity = new AuthenticatedClientSessionEntity(clientSessionId);
entity.setRealmId(realmId);
entity.setAction(clientSession.getAction());
entity.setAuthMethod(clientSession.getProtocol());
entity.setNotes(clientSession.getNotes() == null ? new ConcurrentHashMap<>() : clientSession.getNotes());
entity.setRedirectUri(clientSession.getRedirectUri());
entity.setTimestamp(clientSession.getTimestamp());
return entity;
}
private static class RegisterClientSessionTask implements SessionUpdateTask<UserSessionEntity> {
private final String clientUuid;
private final UUID clientSessionId;
public RegisterClientSessionTask(String clientUuid, UUID clientSessionId) {
this.clientUuid = clientUuid;
this.clientSessionId = clientSessionId;
}
@Override
public void runUpdate(UserSessionEntity session) {
AuthenticatedClientSessionStore clientSessions = session.getAuthenticatedClientSessions();
clientSessions.put(clientUuid, clientSessionId);
}
@Override
public CacheOperation getOperation(UserSessionEntity session) {
return CacheOperation.REPLACE;
}
@Override
public CrossDCMessageStatus getCrossDCMessageStatus(SessionEntityWrapper<UserSessionEntity> sessionWrapper) {
return CrossDCMessageStatus.SYNC;
}
}
}
| model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.sessions.infinispan;
import org.infinispan.Cache;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.exceptions.HotRodClientException;
import org.infinispan.commons.api.BasicCache;
import org.infinispan.context.Flag;
import org.infinispan.stream.CacheCollectors;
import org.jboss.logging.Logger;
import org.keycloak.cluster.ClusterProvider;
import org.keycloak.common.util.Retry;
import org.keycloak.common.util.Time;
import org.keycloak.device.DeviceActivityManager;
import org.keycloak.models.AuthenticatedClientSessionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelException;
import org.keycloak.models.OfflineUserSessionModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.UserSessionSpi;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.sessions.infinispan.changes.Tasks;
import org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStore;
import org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStore;
import org.keycloak.models.sessions.infinispan.entities.SessionEntity;
import org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker;
import org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper;
import org.keycloak.models.sessions.infinispan.changes.InfinispanChangelogBasedTransaction;
import org.keycloak.models.sessions.infinispan.changes.SessionUpdateTask;
import org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity;
import org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore;
import org.keycloak.models.sessions.infinispan.entities.UserSessionEntity;
import org.keycloak.models.sessions.infinispan.events.RealmRemovedSessionEvent;
import org.keycloak.models.sessions.infinispan.events.RemoveUserSessionsEvent;
import org.keycloak.models.sessions.infinispan.events.SessionEventsSenderTransaction;
import org.keycloak.models.sessions.infinispan.stream.Comparators;
import org.keycloak.models.sessions.infinispan.stream.Mappers;
import org.keycloak.models.sessions.infinispan.stream.SessionPredicate;
import org.keycloak.models.sessions.infinispan.stream.UserSessionPredicate;
import org.keycloak.models.sessions.infinispan.util.FuturesHelper;
import org.keycloak.models.sessions.infinispan.util.InfinispanKeyGenerator;
import org.keycloak.connections.infinispan.InfinispanUtil;
import org.keycloak.models.sessions.infinispan.util.SessionTimeouts;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static org.keycloak.utils.StreamsUtil.paginatedStream;
/**
* @author <a href="mailto:[email protected]">Stian Thorgersen</a>
*/
public class InfinispanUserSessionProvider implements UserSessionProvider {
private static final Logger log = Logger.getLogger(InfinispanUserSessionProvider.class);
protected final KeycloakSession session;
protected final Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionCache;
protected final Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionCache;
protected final Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache;
protected final Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionCache;
protected final InfinispanChangelogBasedTransaction<String, UserSessionEntity> sessionTx;
protected final InfinispanChangelogBasedTransaction<String, UserSessionEntity> offlineSessionTx;
protected final InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionTx;
protected final InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> offlineClientSessionTx;
protected final SessionEventsSenderTransaction clusterEventsSenderTx;
protected final CrossDCLastSessionRefreshStore lastSessionRefreshStore;
protected final CrossDCLastSessionRefreshStore offlineLastSessionRefreshStore;
protected final PersisterLastSessionRefreshStore persisterLastSessionRefreshStore;
protected final RemoteCacheInvoker remoteCacheInvoker;
protected final InfinispanKeyGenerator keyGenerator;
protected final boolean loadOfflineSessionsFromDatabase;
public InfinispanUserSessionProvider(KeycloakSession session,
RemoteCacheInvoker remoteCacheInvoker,
CrossDCLastSessionRefreshStore lastSessionRefreshStore,
CrossDCLastSessionRefreshStore offlineLastSessionRefreshStore,
PersisterLastSessionRefreshStore persisterLastSessionRefreshStore,
InfinispanKeyGenerator keyGenerator,
Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionCache,
Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionCache,
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache,
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionCache,
boolean loadOfflineSessionsFromDatabase) {
this.session = session;
this.sessionCache = sessionCache;
this.clientSessionCache = clientSessionCache;
this.offlineSessionCache = offlineSessionCache;
this.offlineClientSessionCache = offlineClientSessionCache;
this.sessionTx = new InfinispanChangelogBasedTransaction<>(session, sessionCache, remoteCacheInvoker, SessionTimeouts::getUserSessionLifespanMs, SessionTimeouts::getUserSessionMaxIdleMs);
this.offlineSessionTx = new InfinispanChangelogBasedTransaction<>(session, offlineSessionCache, remoteCacheInvoker, SessionTimeouts::getOfflineSessionLifespanMs, SessionTimeouts::getOfflineSessionMaxIdleMs);
this.clientSessionTx = new InfinispanChangelogBasedTransaction<>(session, clientSessionCache, remoteCacheInvoker, SessionTimeouts::getClientSessionLifespanMs, SessionTimeouts::getClientSessionMaxIdleMs);
this.offlineClientSessionTx = new InfinispanChangelogBasedTransaction<>(session, offlineClientSessionCache, remoteCacheInvoker, SessionTimeouts::getOfflineClientSessionLifespanMs, SessionTimeouts::getOfflineClientSessionMaxIdleMs);
this.clusterEventsSenderTx = new SessionEventsSenderTransaction(session);
this.lastSessionRefreshStore = lastSessionRefreshStore;
this.offlineLastSessionRefreshStore = offlineLastSessionRefreshStore;
this.persisterLastSessionRefreshStore = persisterLastSessionRefreshStore;
this.remoteCacheInvoker = remoteCacheInvoker;
this.keyGenerator = keyGenerator;
this.loadOfflineSessionsFromDatabase = loadOfflineSessionsFromDatabase;
session.getTransactionManager().enlistAfterCompletion(clusterEventsSenderTx);
session.getTransactionManager().enlistAfterCompletion(sessionTx);
session.getTransactionManager().enlistAfterCompletion(offlineSessionTx);
session.getTransactionManager().enlistAfterCompletion(clientSessionTx);
session.getTransactionManager().enlistAfterCompletion(offlineClientSessionTx);
}
protected Cache<String, SessionEntityWrapper<UserSessionEntity>> getCache(boolean offline) {
return offline ? offlineSessionCache : sessionCache;
}
protected InfinispanChangelogBasedTransaction<String, UserSessionEntity> getTransaction(boolean offline) {
return offline ? offlineSessionTx : sessionTx;
}
protected Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> getClientSessionCache(boolean offline) {
return offline ? offlineClientSessionCache : clientSessionCache;
}
protected InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> getClientSessionTransaction(boolean offline) {
return offline ? offlineClientSessionTx : clientSessionTx;
}
protected CrossDCLastSessionRefreshStore getLastSessionRefreshStore() {
return lastSessionRefreshStore;
}
protected CrossDCLastSessionRefreshStore getOfflineLastSessionRefreshStore() {
return offlineLastSessionRefreshStore;
}
protected PersisterLastSessionRefreshStore getPersisterLastSessionRefreshStore() {
return persisterLastSessionRefreshStore;
}
@Override
public KeycloakSession getKeycloakSession() {
return session;
}
@Override
public AuthenticatedClientSessionModel createClientSession(RealmModel realm, ClientModel client, UserSessionModel userSession) {
final UUID clientSessionId = keyGenerator.generateKeyUUID(session, clientSessionCache);
AuthenticatedClientSessionEntity entity = new AuthenticatedClientSessionEntity(clientSessionId);
entity.setRealmId(realm.getId());
entity.setTimestamp(Time.currentTime());
entity.getNotes().put(AuthenticatedClientSessionModel.STARTED_AT_NOTE, String.valueOf(entity.getTimestamp()));
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(false);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(false);
AuthenticatedClientSessionAdapter adapter = new AuthenticatedClientSessionAdapter(session, this, entity, client, userSession, clientSessionUpdateTx, false);
// For now, the clientSession is considered transient in case that userSession was transient
UserSessionModel.SessionPersistenceState persistenceState = (userSession instanceof UserSessionAdapter && ((UserSessionAdapter) userSession).getPersistenceState() != null) ?
((UserSessionAdapter) userSession).getPersistenceState() : UserSessionModel.SessionPersistenceState.PERSISTENT;
SessionUpdateTask<AuthenticatedClientSessionEntity> createClientSessionTask = Tasks.addIfAbsentSync();
clientSessionUpdateTx.addTask(clientSessionId, createClientSessionTask, entity, persistenceState);
SessionUpdateTask registerClientSessionTask = new RegisterClientSessionTask(client.getId(), clientSessionId);
userSessionUpdateTx.addTask(userSession.getId(), registerClientSessionTask);
return adapter;
}
@Override
public UserSessionModel createUserSession(RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
final String userSessionId = keyGenerator.generateKeyString(session, sessionCache);
return createUserSession(userSessionId, realm, user, loginUsername, ipAddress, authMethod, rememberMe, brokerSessionId, brokerUserId, UserSessionModel.SessionPersistenceState.PERSISTENT);
}
@Override
public UserSessionModel createUserSession(String id, RealmModel realm, UserModel user, String loginUsername, String ipAddress,
String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId, UserSessionModel.SessionPersistenceState persistenceState) {
UserSessionEntity entity = new UserSessionEntity();
entity.setId(id);
updateSessionEntity(entity, realm, user, loginUsername, ipAddress, authMethod, rememberMe, brokerSessionId, brokerUserId);
SessionUpdateTask<UserSessionEntity> createSessionTask = Tasks.addIfAbsentSync();
sessionTx.addTask(id, createSessionTask, entity, persistenceState);
UserSessionAdapter adapter = wrap(realm, entity, false);
adapter.setPersistenceState(persistenceState);
if (adapter != null) {
DeviceActivityManager.attachDevice(adapter, session);
}
return adapter;
}
void updateSessionEntity(UserSessionEntity entity, RealmModel realm, UserModel user, String loginUsername, String ipAddress, String authMethod, boolean rememberMe, String brokerSessionId, String brokerUserId) {
entity.setRealmId(realm.getId());
entity.setUser(user.getId());
entity.setLoginUsername(loginUsername);
entity.setIpAddress(ipAddress);
entity.setAuthMethod(authMethod);
entity.setRememberMe(rememberMe);
entity.setBrokerSessionId(brokerSessionId);
entity.setBrokerUserId(brokerUserId);
int currentTime = Time.currentTime();
entity.setStarted(currentTime);
entity.setLastSessionRefresh(currentTime);
}
@Override
public UserSessionModel getUserSession(RealmModel realm, String id) {
return getUserSession(realm, id, false);
}
protected UserSessionAdapter getUserSession(RealmModel realm, String id, boolean offline) {
UserSessionEntity userSessionEntityFromCache = getUserSessionEntity(realm, id, offline);
if (userSessionEntityFromCache != null) {
return wrap(realm, userSessionEntityFromCache, offline);
}
if (!offline) {
return null;
}
// Try to recover from potentially lost offline-sessions by attempting to fetch and re-import
// the offline session information from the PersistenceProvider.
UserSessionEntity userSessionEntityFromPersistenceProvider = getUserSessionEntityFromPersistenceProvider(realm, id, offline);
if (userSessionEntityFromPersistenceProvider != null) {
// we successfully recovered the offline session!
return wrap(realm, userSessionEntityFromPersistenceProvider, offline);
}
// no luck, the session is really not there anymore
return null;
}
private UserSessionEntity getUserSessionEntityFromPersistenceProvider(RealmModel realm, String sessionId, boolean offline) {
log.debugf("Offline user-session not found in infinispan, attempting UserSessionPersisterProvider lookup for sessionId=%s", sessionId);
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
UserSessionModel persistentUserSession = persister.loadUserSession(realm, sessionId, offline);
if (persistentUserSession == null) {
log.debugf("Offline user-session not found in UserSessionPersisterProvider for sessionId=%s", sessionId);
return null;
}
return importUserSession(realm, offline, persistentUserSession);
}
private UserSessionEntity getUserSessionEntityFromCacheOrImportIfNecessary(RealmModel realm, boolean offline, UserSessionModel persistentUserSession) {
UserSessionEntity userSessionEntity = getUserSessionEntity(realm, persistentUserSession.getId(), offline);
if (userSessionEntity != null) {
// user session present in cache, return existing session
return userSessionEntity;
}
return importUserSession(realm, offline, persistentUserSession);
}
private UserSessionEntity importUserSession(RealmModel realm, boolean offline, UserSessionModel persistentUserSession) {
String sessionId = persistentUserSession.getId();
log.debugf("Attempting to import user-session for sessionId=%s offline=%s", sessionId, offline);
session.sessions().importUserSessions(Collections.singleton(persistentUserSession), offline);
log.debugf("user-session imported, trying another lookup for sessionId=%s offline=%s", sessionId, offline);
UserSessionEntity ispnUserSessionEntity = getUserSessionEntity(realm, sessionId, offline);
if (ispnUserSessionEntity != null) {
log.debugf("user-session found after import for sessionId=%s offline=%s", sessionId, offline);
return ispnUserSessionEntity;
}
log.debugf("user-session could not be found after import for sessionId=%s offline=%s", sessionId, offline);
return null;
}
private UserSessionEntity getUserSessionEntity(RealmModel realm, String id, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> tx = getTransaction(offline);
SessionEntityWrapper<UserSessionEntity> entityWrapper = tx.get(id);
if (entityWrapper==null) return null;
UserSessionEntity entity = entityWrapper.getEntity();
if (!entity.getRealmId().equals(realm.getId())) return null;
return entity;
}
private Stream<UserSessionModel> getUserSessionsFromPersistenceProviderStream(RealmModel realm, UserModel user, boolean offline) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.loadUserSessionsStream(realm, user, offline, 0, null)
.map(persistentUserSession -> getUserSessionEntityFromCacheOrImportIfNecessary(realm, offline, persistentUserSession))
.filter(Objects::nonNull)
.map(userSessionEntity -> wrap(realm, userSessionEntity, offline));
}
protected Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, UserSessionPredicate predicate, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the offline user-sessions from the persistence provider
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
if (predicate.getUserId() != null) {
UserModel user = session.users().getUserById(realm, predicate.getUserId());
if (user != null) {
return persister.loadUserSessionsStream(realm, user, true, 0, null);
}
}
if (predicate.getBrokerUserId() != null) {
String[] idpAliasSessionId = predicate.getBrokerUserId().split("\\.");
Map<String, String> attributes = new HashMap<>();
attributes.put(UserModel.IDP_ALIAS, idpAliasSessionId[0]);
attributes.put(UserModel.IDP_USER_ID, idpAliasSessionId[1]);
UserProvider userProvider = session.getProvider(UserProvider.class);
UserModel userModel = userProvider.searchForUserStream(realm, attributes, 0, null).findFirst().orElse(null);
return userModel != null ?
persister.loadUserSessionsStream(realm, userModel, true, 0, null) :
Stream.empty();
}
if (predicate.getBrokerSessionId() != null) {
// TODO add support for offline user-session lookup by brokerSessionId
// currently it is not possible to access the brokerSessionId in offline user-session in a database agnostic way
throw new ModelException("Dynamic database lookup for offline user-sessions by broker session ID is currently only supported for preloaded sessions. " +
"Set preloadOfflineSessionsFromDatabase option to \"true\" in " + UserSessionSpi.NAME + " SPI in "
+ InfinispanUserSessionProviderFactory.PROVIDER_ID + " provider to enable the lookup.");
}
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
// return a stream that 'wraps' the infinispan cache stream so that the cache stream's elements are read one by one
// and then mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
return StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false)
.map(Mappers.userSessionEntity())
.map(entity -> this.wrap(realm, entity, offline));
}
@Override
public AuthenticatedClientSessionAdapter getClientSession(UserSessionModel userSession, ClientModel client, String clientSessionId, boolean offline) {
return getClientSession(userSession, client, clientSessionId == null ? null : UUID.fromString(clientSessionId), offline);
}
@Override
public AuthenticatedClientSessionAdapter getClientSession(UserSessionModel userSession, ClientModel client, UUID clientSessionId, boolean offline) {
AuthenticatedClientSessionEntity entity = getClientSessionEntity(clientSessionId, offline);
return wrap(userSession, client, entity, offline);
}
private AuthenticatedClientSessionEntity getClientSessionEntity(UUID id, boolean offline) {
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> tx = getClientSessionTransaction(offline);
SessionEntityWrapper<AuthenticatedClientSessionEntity> entityWrapper = tx.get(id);
return entityWrapper == null ? null : entityWrapper.getEntity();
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(final RealmModel realm, UserModel user) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).user(user.getId()), false);
}
@Override
public Stream<UserSessionModel> getUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerUserId(brokerUserId), false);
}
@Override
public UserSessionModel getUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId) {
return this.getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerSessionId(brokerSessionId), false)
.findFirst().orElse(null);
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client) {
return getUserSessionsStream(realm, client, -1, -1);
}
@Override
public Stream<UserSessionModel> getUserSessionsStream(RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults) {
return getUserSessionsStream(realm, client, firstResult, maxResults, false);
}
protected Stream<UserSessionModel> getUserSessionsStream(final RealmModel realm, ClientModel client, Integer firstResult, Integer maxResults, final boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the actual offline user session count from the database
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.loadUserSessionsStream(realm, client, true, firstResult, maxResults);
}
final String clientUuid = client.getId();
UserSessionPredicate predicate = UserSessionPredicate.create(realm.getId()).client(clientUuid);
return getUserSessionModels(realm, firstResult, maxResults, offline, predicate);
}
protected Stream<UserSessionModel> getUserSessionModels(RealmModel realm, Integer firstResult, Integer maxResults, boolean offline, UserSessionPredicate predicate) {
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
// return a stream that 'wraps' the infinispan cache stream so that the cache stream's elements are read one by one
// and then filtered/mapped locally to avoid serialization issues when trying to manipulate the cache stream directly.
Stream<UserSessionEntity> stream = StreamSupport.stream(cache.entrySet().stream().filter(predicate).spliterator(), false)
.map(Mappers.userSessionEntity())
.sorted(Comparators.userSessionLastSessionRefresh());
return paginatedStream(stream, firstResult, maxResults).map(entity -> this.wrap(realm, entity, offline));
}
@Override
public UserSessionModel getUserSessionWithPredicate(RealmModel realm, String id, boolean offline, Predicate<UserSessionModel> predicate) {
UserSessionModel userSession = getUserSession(realm, id, offline);
if (userSession == null) {
return null;
}
// We have userSession, which passes predicate. No need for remote lookup.
if (predicate.test(userSession)) {
log.debugf("getUserSessionWithPredicate(%s): found in local cache", id);
return userSession;
}
// Try lookup userSession from remoteCache
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
if (remoteCache != null) {
SessionEntityWrapper<UserSessionEntity> remoteSessionEntityWrapper = (SessionEntityWrapper<UserSessionEntity>) remoteCache.get(id);
if (remoteSessionEntityWrapper != null) {
UserSessionEntity remoteSessionEntity = remoteSessionEntityWrapper.getEntity();
log.debugf("getUserSessionWithPredicate(%s): remote cache contains session entity %s", id, remoteSessionEntity);
UserSessionModel remoteSessionAdapter = wrap(realm, remoteSessionEntity, offline);
if (predicate.test(remoteSessionAdapter)) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> tx = getTransaction(offline);
// Remote entity contains our predicate. Update local cache with the remote entity
SessionEntityWrapper<UserSessionEntity> sessionWrapper = remoteSessionEntity.mergeRemoteEntityWithLocalEntity(tx.get(id));
// Replace entity just in ispn cache. Skip remoteStore
cache.getAdvancedCache().withFlags(Flag.SKIP_CACHE_STORE, Flag.SKIP_CACHE_LOAD, Flag.IGNORE_RETURN_VALUES)
.replace(id, sessionWrapper);
tx.reloadEntityInCurrentTransaction(realm, id, sessionWrapper);
// Recursion. We should have it locally now
return getUserSessionWithPredicate(realm, id, offline, predicate);
} else {
log.debugf("getUserSessionWithPredicate(%s): found, but predicate doesn't pass", id);
return null;
}
} else {
log.debugf("getUserSessionWithPredicate(%s): not found", id);
// Session not available on remoteCache. Was already removed there. So removing locally too.
// TODO: Can be optimized to skip calling remoteCache.remove
removeUserSession(realm, userSession);
return null;
}
} else {
log.debugf("getUserSessionWithPredicate(%s): remote cache not available", id);
return null;
}
}
@Override
public long getActiveUserSessions(RealmModel realm, ClientModel client) {
return getUserSessionsCount(realm, client, false);
}
@Override
public Map<String, Long> getActiveClientSessionStats(RealmModel realm, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.getUserSessionsCountsByClients(realm, true);
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
return cache.entrySet().stream()
.filter(UserSessionPredicate.create(realm.getId()))
.map(Mappers.authClientSessionSetMapper())
.flatMap((Serializable & Function<Set<String>, Stream<? extends String>>)Mappers::toStream)
.collect(
CacheCollectors.serializableCollector(
() -> Collectors.groupingBy(Function.identity(), Collectors.counting())
)
);
}
protected long getUserSessionsCount(RealmModel realm, ClientModel client, boolean offline) {
if (offline && loadOfflineSessionsFromDatabase) {
// fetch the actual offline user session count from the database
UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
return persister.getUserSessionsCount(realm, client, true);
}
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
final String clientUuid = client.getId();
return cache.entrySet().stream()
.filter(UserSessionPredicate.create(realm.getId()).client(clientUuid))
.count();
}
@Override
public void removeUserSession(RealmModel realm, UserSessionModel session) {
UserSessionEntity entity = getUserSessionEntity(realm, session, false);
if (entity != null) {
removeUserSession(entity, false);
}
}
@Override
public void removeUserSessions(RealmModel realm, UserModel user) {
removeUserSessions(realm, user, false);
}
protected void removeUserSessions(RealmModel realm, UserModel user, boolean offline) {
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
cache = CacheDecorators.skipCacheLoaders(cache);
Iterator<UserSessionEntity> itr = cache.entrySet().stream().filter(UserSessionPredicate.create(realm.getId()).user(user.getId())).map(Mappers.userSessionEntity()).iterator();
while (itr.hasNext()) {
UserSessionEntity userSessionEntity = itr.next();
removeUserSession(userSessionEntity, offline);
}
}
public void removeAllExpired() {
// Rely on expiration of cache entries provided by infinispan. Just expire entries from persister is needed
// TODO: Avoid iteration over all realms here (Details in the KEYCLOAK-16802)
session.realms().getRealmsStream().forEach(this::removeExpired);
}
@Override
public void removeExpired(RealmModel realm) {
// Rely on expiration of cache entries provided by infinispan. Nothing needed here besides calling persister
session.getProvider(UserSessionPersisterProvider.class).removeExpired(realm);
}
@Override
public void removeUserSessions(RealmModel realm) {
// Don't send message to all DCs, just to all cluster nodes in current DC. The remoteCache will notify client listeners for removed userSessions.
clusterEventsSenderTx.addEvent(
RemoveUserSessionsEvent.createEvent(RemoveUserSessionsEvent.class, InfinispanUserSessionProviderFactory.REMOVE_USER_SESSIONS_EVENT, session, realm.getId(), true),
ClusterProvider.DCNotify.LOCAL_DC_ONLY);
}
protected void onRemoveUserSessionsEvent(String realmId) {
removeLocalUserSessions(realmId, false);
}
// public for usage in the testsuite
public void removeLocalUserSessions(String realmId, boolean offline) {
FuturesHelper futures = new FuturesHelper();
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = getCache(offline);
Cache<String, SessionEntityWrapper<UserSessionEntity>> localCache = CacheDecorators.localCache(cache);
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionCache = getClientSessionCache(offline);
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> localClientSessionCache = CacheDecorators.localCache(clientSessionCache);
Cache<String, SessionEntityWrapper<UserSessionEntity>> localCacheStoreIgnore = CacheDecorators.skipCacheLoaders(localCache);
final AtomicInteger userSessionsSize = new AtomicInteger();
localCacheStoreIgnore
.entrySet()
.stream()
.filter(SessionPredicate.create(realmId))
.map(Mappers.userSessionEntity())
.forEach(new Consumer<UserSessionEntity>() {
@Override
public void accept(UserSessionEntity userSessionEntity) {
userSessionsSize.incrementAndGet();
// Remove session from remoteCache too. Use removeAsync for better perf
Future future = localCache.removeAsync(userSessionEntity.getId());
futures.addTask(future);
userSessionEntity.getAuthenticatedClientSessions().forEach((clientUUID, clientSessionId) -> {
Future f = localClientSessionCache.removeAsync(clientSessionId);
futures.addTask(f);
});
}
});
futures.waitForAllToFinish();
log.debugf("Removed %d sessions in realm %s. Offline: %b", (Object) userSessionsSize.get(), realmId, offline);
}
@Override
public void onRealmRemoved(RealmModel realm) {
// Don't send message to all DCs, just to all cluster nodes in current DC. The remoteCache will notify client listeners for removed userSessions.
clusterEventsSenderTx.addEvent(
RealmRemovedSessionEvent.createEvent(RealmRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.REALM_REMOVED_SESSION_EVENT, session, realm.getId(), true),
ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onRealmRemoved(realm);
}
}
protected void onRealmRemovedEvent(String realmId) {
removeLocalUserSessions(realmId, true);
removeLocalUserSessions(realmId, false);
}
@Override
public void onClientRemoved(RealmModel realm, ClientModel client) {
// clusterEventsSenderTx.addEvent(
// ClientRemovedSessionEvent.createEvent(ClientRemovedSessionEvent.class, InfinispanUserSessionProviderFactory.CLIENT_REMOVED_SESSION_EVENT, session, realm.getId(), true),
// ClusterProvider.DCNotify.LOCAL_DC_ONLY);
UserSessionPersisterProvider sessionsPersister = session.getProvider(UserSessionPersisterProvider.class);
if (sessionsPersister != null) {
sessionsPersister.onClientRemoved(realm, client);
}
}
protected void onClientRemovedEvent(String realmId, String clientUuid) {
// Nothing for now. userSession.getAuthenticatedClientSessions() will check lazily if particular client exists and update userSession on-the-fly.
}
protected void onUserRemoved(RealmModel realm, UserModel user) {
removeUserSessions(realm, user, true);
removeUserSessions(realm, user, false);
UserSessionPersisterProvider persisterProvider = session.getProvider(UserSessionPersisterProvider.class);
if (persisterProvider != null) {
persisterProvider.onUserRemoved(realm, user);
}
}
@Override
public void close() {
}
@Override
public int getStartupTime(RealmModel realm) {
// TODO: take realm.getNotBefore() into account?
return session.getProvider(ClusterProvider.class).getClusterStartupTime();
}
protected void removeUserSession(UserSessionEntity sessionEntity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
sessionEntity.getAuthenticatedClientSessions().forEach((clientUUID, clientSessionId) -> clientSessionUpdateTx.addTask(clientSessionId, Tasks.removeSync()));
SessionUpdateTask<UserSessionEntity> removeTask = Tasks.removeSync();
userSessionUpdateTx.addTask(sessionEntity.getId(), removeTask);
}
UserSessionAdapter wrap(RealmModel realm, UserSessionEntity entity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
return entity != null ? new UserSessionAdapter(session, this, userSessionUpdateTx, clientSessionUpdateTx, realm, entity, offline) : null;
}
AuthenticatedClientSessionAdapter wrap(UserSessionModel userSession, ClientModel client, AuthenticatedClientSessionEntity entity, boolean offline) {
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
return entity != null ? new AuthenticatedClientSessionAdapter(session,this, entity, client, userSession, clientSessionUpdateTx, offline) : null;
}
UserSessionEntity getUserSessionEntity(RealmModel realm, UserSessionModel userSession, boolean offline) {
if (userSession instanceof UserSessionAdapter) {
if (!userSession.getRealm().equals(realm)) return null;
return ((UserSessionAdapter) userSession).getEntity();
} else {
return getUserSessionEntity(realm, userSession.getId(), offline);
}
}
@Override
public UserSessionModel createOfflineUserSession(UserSessionModel userSession) {
UserSessionAdapter offlineUserSession = importUserSession(userSession, true);
// started and lastSessionRefresh set to current time
int currentTime = Time.currentTime();
offlineUserSession.getEntity().setStarted(currentTime);
offlineUserSession.setLastSessionRefresh(currentTime);
session.getProvider(UserSessionPersisterProvider.class).createUserSession(userSession, true);
return offlineUserSession;
}
@Override
public UserSessionAdapter getOfflineUserSession(RealmModel realm, String userSessionId) {
return getUserSession(realm, userSessionId, true);
}
@Override
public UserSessionModel getOfflineUserSessionByBrokerSessionId(RealmModel realm, String brokerSessionId) {
return this.getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerSessionId(brokerSessionId), true)
.findFirst().orElse(null);
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionByBrokerUserIdStream(RealmModel realm, String brokerUserId) {
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).brokerUserId(brokerUserId), true);
}
@Override
public void removeOfflineUserSession(RealmModel realm, UserSessionModel userSession) {
UserSessionEntity userSessionEntity = getUserSessionEntity(realm, userSession, true);
if (userSessionEntity != null) {
removeUserSession(userSessionEntity, true);
}
session.getProvider(UserSessionPersisterProvider.class).removeUserSession(userSession.getId(), true);
}
@Override
public AuthenticatedClientSessionModel createOfflineClientSession(AuthenticatedClientSessionModel clientSession, UserSessionModel offlineUserSession) {
UserSessionAdapter userSessionAdapter = (offlineUserSession instanceof UserSessionAdapter) ? (UserSessionAdapter) offlineUserSession :
getOfflineUserSession(offlineUserSession.getRealm(), offlineUserSession.getId());
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(true);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(true);
AuthenticatedClientSessionAdapter offlineClientSession = importClientSession(userSessionAdapter, clientSession, userSessionUpdateTx, clientSessionUpdateTx, true);
// update timestamp to current time
offlineClientSession.setTimestamp(Time.currentTime());
offlineClientSession.getNotes().put(AuthenticatedClientSessionModel.STARTED_AT_NOTE, String.valueOf(offlineClientSession.getTimestamp()));
session.getProvider(UserSessionPersisterProvider.class).createClientSession(clientSession, true);
return offlineClientSession;
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, UserModel user) {
if (loadOfflineSessionsFromDatabase) {
return getUserSessionsFromPersistenceProviderStream(realm, user, true);
}
return getUserSessionsStream(realm, UserSessionPredicate.create(realm.getId()).user(user.getId()), true);
}
@Override
public long getOfflineSessionsCount(RealmModel realm, ClientModel client) {
return getUserSessionsCount(realm, client, true);
}
@Override
public Stream<UserSessionModel> getOfflineUserSessionsStream(RealmModel realm, ClientModel client, Integer first, Integer max) {
return getUserSessionsStream(realm, client, first, max, true);
}
@Override
public void importUserSessions(Collection<UserSessionModel> persistentUserSessions, boolean offline) {
if (persistentUserSessions == null || persistentUserSessions.isEmpty()) {
return;
}
Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionsById = new HashMap<>();
Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsById = persistentUserSessions.stream()
.map((UserSessionModel persistentUserSession) -> {
UserSessionEntity userSessionEntityToImport = createUserSessionEntityInstance(persistentUserSession);
for (Map.Entry<String, AuthenticatedClientSessionModel> entry : persistentUserSession.getAuthenticatedClientSessions().entrySet()) {
String clientUUID = entry.getKey();
AuthenticatedClientSessionModel clientSession = entry.getValue();
AuthenticatedClientSessionEntity clientSessionToImport = createAuthenticatedClientSessionInstance(clientSession, userSessionEntityToImport.getRealmId(), offline);
// Update timestamp to same value as userSession. LastSessionRefresh of userSession from DB will have correct value
clientSessionToImport.setTimestamp(userSessionEntityToImport.getLastSessionRefresh());
clientSessionsById.put(clientSessionToImport.getId(), new SessionEntityWrapper<>(clientSessionToImport));
// Update userSession entity with the clientSession
AuthenticatedClientSessionStore clientSessions = userSessionEntityToImport.getAuthenticatedClientSessions();
clientSessions.put(clientUUID, clientSessionToImport.getId());
}
return userSessionEntityToImport;
})
.map(SessionEntityWrapper::new)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
// Directly put all entities to the infinispan cache
Cache<String, SessionEntityWrapper<UserSessionEntity>> cache = CacheDecorators.skipCacheLoaders(getCache(offline));
boolean importWithExpiration = sessionsById.size() == 1;
if (importWithExpiration) {
importSessionsWithExpiration(sessionsById, cache,
offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,
offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
} else {
cache.putAll(sessionsById);
}
// put all entities to the remoteCache (if exists)
RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);
if (remoteCache != null) {
Map<String, SessionEntityWrapper<UserSessionEntity>> sessionsByIdForTransport = sessionsById.values().stream()
.map(SessionEntityWrapper::forTransport)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
if (importWithExpiration) {
importSessionsWithExpiration(sessionsByIdForTransport, remoteCache,
offline ? SessionTimeouts::getOfflineSessionLifespanMs : SessionTimeouts::getUserSessionLifespanMs,
offline ? SessionTimeouts::getOfflineSessionMaxIdleMs : SessionTimeouts::getUserSessionMaxIdleMs);
} else {
Retry.executeWithBackoff((int iteration) -> {
try {
remoteCache.putAll(sessionsByIdForTransport);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsByIdForTransport.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
}
}
// Import client sessions
Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessCache = offline ? offlineClientSessionCache : clientSessionCache;
clientSessCache = CacheDecorators.skipCacheLoaders(clientSessCache);
if (importWithExpiration) {
importSessionsWithExpiration(clientSessionsById, clientSessCache,
offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,
offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
} else {
clientSessCache.putAll(clientSessionsById);
}
// put all entities to the remoteCache (if exists)
RemoteCache remoteCacheClientSessions = InfinispanUtil.getRemoteCache(clientSessCache);
if (remoteCacheClientSessions != null) {
Map<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> sessionsByIdForTransport = clientSessionsById.values().stream()
.map(SessionEntityWrapper::forTransport)
.collect(Collectors.toMap(sessionEntityWrapper -> sessionEntityWrapper.getEntity().getId(), Function.identity()));
if (importWithExpiration) {
importSessionsWithExpiration(sessionsByIdForTransport, remoteCacheClientSessions,
offline ? SessionTimeouts::getOfflineClientSessionLifespanMs : SessionTimeouts::getClientSessionLifespanMs,
offline ? SessionTimeouts::getOfflineClientSessionMaxIdleMs : SessionTimeouts::getClientSessionMaxIdleMs);
} else {
Retry.executeWithBackoff((int iteration) -> {
try {
remoteCacheClientSessions.putAll(sessionsByIdForTransport);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d client sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsByIdForTransport.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
}
}
}
private <T extends SessionEntity> void importSessionsWithExpiration(Map<? extends Object, SessionEntityWrapper<T>> sessionsById,
BasicCache cache, BiFunction<RealmModel, T, Long> lifespanMsCalculator,
BiFunction<RealmModel, T, Long> maxIdleTimeMsCalculator) {
sessionsById.forEach((id, sessionEntityWrapper) -> {
T sessionEntity = sessionEntityWrapper.getEntity();
RealmModel currentRealm = session.realms().getRealm(sessionEntity.getRealmId());
long lifespan = lifespanMsCalculator.apply(currentRealm, sessionEntity);
long maxIdle = maxIdleTimeMsCalculator.apply(currentRealm, sessionEntity);
if(lifespan != SessionTimeouts.ENTRY_EXPIRED_FLAG
&& maxIdle != SessionTimeouts.ENTRY_EXPIRED_FLAG ) {
if (cache instanceof RemoteCache) {
Retry.executeWithBackoff((int iteration) -> {
try {
cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
} catch (HotRodClientException re) {
if (log.isDebugEnabled()) {
log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task",
sessionsById.size(), iteration);
}
// Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
throw re;
}
}, 10, 10);
} else {
cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
}
}
});
}
// Imports just userSession without it's clientSessions
protected UserSessionAdapter importUserSession(UserSessionModel userSession, boolean offline) {
UserSessionEntity entity = createUserSessionEntityInstance(userSession);
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
SessionUpdateTask<UserSessionEntity> importTask = Tasks.addIfAbsentSync();
userSessionUpdateTx.addTask(userSession.getId(), importTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
UserSessionAdapter importedSession = wrap(userSession.getRealm(), entity, offline);
return importedSession;
}
private UserSessionEntity createUserSessionEntityInstance(UserSessionModel userSession) {
UserSessionEntity entity = new UserSessionEntity();
entity.setId(userSession.getId());
entity.setRealmId(userSession.getRealm().getId());
entity.setAuthMethod(userSession.getAuthMethod());
entity.setBrokerSessionId(userSession.getBrokerSessionId());
entity.setBrokerUserId(userSession.getBrokerUserId());
entity.setIpAddress(userSession.getIpAddress());
entity.setNotes(userSession.getNotes() == null ? new ConcurrentHashMap<>() : userSession.getNotes());
entity.setAuthenticatedClientSessions(new AuthenticatedClientSessionStore());
entity.setRememberMe(userSession.isRememberMe());
entity.setState(userSession.getState());
if (userSession instanceof OfflineUserSessionModel) {
// this is a hack so that UserModel doesn't have to be available when offline token is imported.
// see related JIRA - KEYCLOAK-5350 and corresponding test
OfflineUserSessionModel oline = (OfflineUserSessionModel)userSession;
entity.setUser(oline.getUserId());
// NOTE: Hack
// We skip calling entity.setLoginUsername(userSession.getLoginUsername())
} else {
entity.setLoginUsername(userSession.getLoginUsername());
entity.setUser(userSession.getUser().getId());
}
entity.setStarted(userSession.getStarted());
entity.setLastSessionRefresh(userSession.getLastSessionRefresh());
return entity;
}
private AuthenticatedClientSessionAdapter importClientSession(UserSessionAdapter sessionToImportInto, AuthenticatedClientSessionModel clientSession,
InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx,
InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx,
boolean offline) {
AuthenticatedClientSessionEntity entity = createAuthenticatedClientSessionInstance(clientSession, sessionToImportInto.getRealm().getId(), offline);
final UUID clientSessionId = entity.getId();
SessionUpdateTask<AuthenticatedClientSessionEntity> createClientSessionTask = Tasks.addIfAbsentSync();
clientSessionUpdateTx.addTask(entity.getId(), createClientSessionTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
AuthenticatedClientSessionStore clientSessions = sessionToImportInto.getEntity().getAuthenticatedClientSessions();
clientSessions.put(clientSession.getClient().getId(), clientSessionId);
SessionUpdateTask registerClientSessionTask = new RegisterClientSessionTask(clientSession.getClient().getId(), clientSessionId);
userSessionUpdateTx.addTask(sessionToImportInto.getId(), registerClientSessionTask);
return new AuthenticatedClientSessionAdapter(session,this, entity, clientSession.getClient(), sessionToImportInto, clientSessionUpdateTx, offline);
}
private AuthenticatedClientSessionEntity createAuthenticatedClientSessionInstance(AuthenticatedClientSessionModel clientSession, String realmId, boolean offline) {
final UUID clientSessionId = keyGenerator.generateKeyUUID(session, getClientSessionCache(offline));
AuthenticatedClientSessionEntity entity = new AuthenticatedClientSessionEntity(clientSessionId);
entity.setRealmId(realmId);
entity.setAction(clientSession.getAction());
entity.setAuthMethod(clientSession.getProtocol());
entity.setNotes(clientSession.getNotes() == null ? new ConcurrentHashMap<>() : clientSession.getNotes());
entity.setRedirectUri(clientSession.getRedirectUri());
entity.setTimestamp(clientSession.getTimestamp());
return entity;
}
private static class RegisterClientSessionTask implements SessionUpdateTask<UserSessionEntity> {
private final String clientUuid;
private final UUID clientSessionId;
public RegisterClientSessionTask(String clientUuid, UUID clientSessionId) {
this.clientUuid = clientUuid;
this.clientSessionId = clientSessionId;
}
@Override
public void runUpdate(UserSessionEntity session) {
AuthenticatedClientSessionStore clientSessions = session.getAuthenticatedClientSessions();
clientSessions.put(clientUuid, clientSessionId);
}
@Override
public CacheOperation getOperation(UserSessionEntity session) {
return CacheOperation.REPLACE;
}
@Override
public CrossDCMessageStatus getCrossDCMessageStatus(SessionEntityWrapper<UserSessionEntity> sessionWrapper) {
return CrossDCMessageStatus.SYNC;
}
}
}
| Avoid updating offline session refresh time during creation
Closes #14384
| model/infinispan/src/main/java/org/keycloak/models/sessions/infinispan/InfinispanUserSessionProvider.java | Avoid updating offline session refresh time during creation |
|
Java | bsd-2-clause | 67e01d30f8d13c66f690218e92465b02769582e0 | 0 | bramp/objectgraph | package net.bramp.objectgraph;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/** @author bramp */
class TestVisitor implements ObjectGraph.Visitor {
public final Set<Object> found = Sets.newIdentityHashSet();
@Override
public boolean visit(Object object, Class<?> clazz) {
System.out.println(clazz.toString() + " " + object.toString());
// We expect non-null arguments
assertThat(object).isNotNull();
assertThat(clazz).isNotNull();
// Check we haven't double visited this node
assertThat(found).usingElementComparator(Ordering.arbitrary()).doesNotContain(object);
found.add(object);
return false;
}
}
| src/test/java/net/bramp/objectgraph/TestVisitor.java | package net.bramp.objectgraph;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/** @author bramp */
class TestVisitor implements ObjectGraph.Visitor {
public final Set<Object> found = Sets.newIdentityHashSet();
@Override
public boolean visit(Object object, Class clazz) {
System.out.println(clazz.toString() + " " + object.toString());
// We expect non-null arguments
assertThat(object).isNotNull();
assertThat(clazz).isNotNull();
// Check we haven't double visited this node
assertThat(found).usingElementComparator(Ordering.arbitrary()).doesNotContain(object);
found.add(object);
return false;
}
}
| Fixed a lint warning.
| src/test/java/net/bramp/objectgraph/TestVisitor.java | Fixed a lint warning. |
|
Java | bsd-2-clause | c0c103666d1133be0cd2f9065173ae309f244c2e | 0 | thecastawaydev/tonegodgui-1,brainless-studios/tonegodgui,meltzow/tonegodgui | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.framework.core.util;
import tonegod.gui.core.Screen;
import tonegod.gui.framework.animation.Interpolation;
/**
*
* @author t0neg0d
*/
public abstract class GameTimer {
private float time = 0;
private float duration = 1;
private boolean active = false;
private boolean complete = false;
private long runCount = 0;
private boolean autoRestart = false;
private boolean isManaged = false;
private Interpolation interpolation = Interpolation.linear;
private boolean updateDurationOnNextRestart = false;
private float nextDuration = 1;
/**
* Creates a new instance of the GameTimer class with a default duration of 1 second
*/
public GameTimer() {
this(1,false);
}
/**
* Creates a new instance of the GameTimer class
* @param targetTime The duration the timer should run in seconds
*/
public GameTimer(float duration) {
this(duration,false);
}
/**
* Creates a new instance of the GameTimer class
* @param targetTime The duration the timer should run in seconds
* @param autoStart Sets the GameTimer to active if true
*/
public GameTimer(float duration, boolean autoStart) {
this.duration = duration;
this.active = autoStart;
}
/**
* Sets the amount of time in seconds that should elapse before the
* GameTimer is complete.
* @param targetTime The duration of the timer
*/
public void setDuration(float duration) {
this.duration = duration;
}
/**
* Sets the duration to a new value on the next call to reset.
* Allows for updating the duration properly from onComplete method
* @param duration The duration to use on the next timer run
*/
public void setNextDuration(float duration) {
this.updateDurationOnNextRestart = true;
this.nextDuration = duration;
}
/**
* Return the amount of time in seconds the GameTimer should run for
* before completing.
* @return targetTime
*/
public float getDuration() {
return this.duration;
}
/**
* Resets the timer for another use.
* @param resetFromLastEndTime GameTimer should subtract the targetTime from the
* previously elapsed time of the timer.
*/
public void reset(boolean resetFromLastEndTime) {
if (resetFromLastEndTime)
time -= duration;
else
time = 0;
if (this.updateDurationOnNextRestart) {
this.duration = nextDuration;
this.updateDurationOnNextRestart = false;
nextDuration = 1;
}
active = false;
complete = false;
}
/**
* Call to reset the number of times the timer has run to 0
*/
public void resetRunCount() {
this.runCount = 0;
}
/**
* Sets the GameTimer to active
*/
public void startGameTimer() {
this.active = true;
}
/**
* Returns if the GameTimer has completed running
* @return
*/
public boolean isComplete() {
return this.complete;
}
/**
* Sets the interpolation to apply to the percent complete returned by getPercentComplete()
* @param interpolation
*/
public void setInterpolation(Interpolation interpolation) {
this.interpolation = interpolation;
}
/**
* Returns the interpolation set to be used by getPercentComplete()
* @return
*/
public Interpolation getInterpolation() {
return this.interpolation;
}
/**
* return a float between 0.0 and 1.0 representing the percent complete
* @return
*/
public float getPercentComplete() {
return interpolation.apply(time/duration);
}
/**
* Returns if the GameTimer is running
* @return
*/
public boolean isActive() {
return this.active;
}
/**
* Returns the number of times startGameTimer has been called on this timer
* @return
*/
public long getRunCount() {
return this.runCount;
}
/**
* For use with or without managed GameTimers.
* Enables auto restart of the timer after calling onComplete.
* @param autoRestart
*/
public void setAutoRestart(boolean autoRestart) {
this.autoRestart = autoRestart;
}
/**
* Returns if the GameTimer will automatically reset and restart after calling onComplete.
* @return
*/
public boolean getAutoRestart() {
return this.autoRestart;
}
/**
* FOR INTERNAL USE ONLY. Do not call this method directly.
*/
public void setIsManaged(boolean isManaged) {
this.isManaged = isManaged;
}
public boolean getIsManaged() { return this.isManaged; }
/**
* Should be called each game loop
* @param tpf
*/
public void update(float tpf) {
if (active && !complete) {
time += tpf;
if (time >= duration) {
complete = true;
active = false;
validateRestart(time);
}
}
}
private void validateRestart(float time) {
runCount++;
onComplete(time);
if (autoRestart) {
reset(true);
startGameTimer();
}
}
public abstract void onComplete(float time);
}
| src/tonegod/gui/framework/core/util/GameTimer.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tonegod.gui.framework.core.util;
import tonegod.gui.core.Screen;
import tonegod.gui.framework.animation.Interpolation;
/**
*
* @author t0neg0d
*/
public abstract class GameTimer {
private float time = 0;
private float duration = 1;
private boolean active = false;
private boolean complete = false;
private long runCount = 0;
private boolean autoRestart = false;
private boolean isManaged = false;
private Interpolation interpolation = Interpolation.linear;
/**
* Creates a new instance of the GameTimer class with a default duration of 1 second
*/
public GameTimer() {
this(1,false);
}
/**
* Creates a new instance of the GameTimer class
* @param targetTime The duration the timer should run in seconds
*/
public GameTimer(float duration) {
this(duration,false);
}
/**
* Creates a new instance of the GameTimer class
* @param targetTime The duration the timer should run in seconds
* @param autoStart Sets the GameTimer to active if true
*/
public GameTimer(float duration, boolean autoStart) {
this.duration = duration;
this.active = autoStart;
}
/**
* Sets the amount of time in seconds that should elapse before the
* GameTimer is complete.
* @param targetTime The duration of the timer
*/
public void setDuration(float duration) {
this.duration = duration;
}
/**
* Return the amount of time in seconds the GameTimer should run for
* before completing.
* @return targetTime
*/
public float getDuration() {
return this.duration;
}
/**
* Resets the timer for another use.
* @param resetFromLastEndTime GameTimer should subtract the targetTime from the
* previously elapsed time of the timer.
*/
public void reset(boolean resetFromLastEndTime) {
if (resetFromLastEndTime)
time -= duration;
else
time = 0;
active = false;
complete = false;
}
/**
* Call to reset the number of times the timer has run to 0
*/
public void resetRunCount() {
this.runCount = 0;
}
/**
* Sets the GameTimer to active
*/
public void startGameTimer() {
this.active = true;
runCount++;
}
/**
* Returns if the GameTimer has completed running
* @return
*/
public boolean isComplete() {
return this.complete;
}
/**
* Sets the interpolation to apply to the percent complete returned by getPercentComplete()
* @param interpolation
*/
public void setInterpolation(Interpolation interpolation) {
this.interpolation = interpolation;
}
/**
* Returns the interpolation set to be used by getPercentComplete()
* @return
*/
public Interpolation getInterpolation() {
return this.interpolation;
}
/**
* return a float between 0.0 and 1.0 representing the percent complete
* @return
*/
public float getPercentComplete() {
return interpolation.apply(time/duration);
}
/**
* Returns if the GameTimer is running
* @return
*/
public boolean isActive() {
return this.active;
}
/**
* Returns the number of times startGameTimer has been called on this timer
* @return
*/
public long getRunCount() {
return this.runCount;
}
/**
* For use with or without managed GameTimers.
* Enables auto restart of the timer after calling onComplete.
* @param autoRestart
*/
public void setAutoRestart(boolean autoRestart) {
this.autoRestart = autoRestart;
}
/**
* Returns if the GameTimer will automatically reset and restart after calling onComplete.
* @return
*/
public boolean getAutoRestart() {
return this.autoRestart;
}
/**
* FOR INTERNAL USE ONLY. Do not call this method directly.
*/
public void setIsManaged(boolean isManaged) {
this.isManaged = isManaged;
}
public boolean getIsManaged() { return this.isManaged; }
/**
* Should be called each game loop
* @param tpf
*/
public void update(float tpf) {
if (active && !complete) {
time += tpf;
if (time >= duration) {
complete = true;
active = false;
validateRestart(time);
}
}
}
private void validateRestart(float time) {
if (autoRestart) {
reset(true);
startGameTimer();
}
onComplete(time);
}
public abstract void onComplete(float time);
}
| Update to allows for modifying the duration from the onComplete call. This allows for complex stepped commands with the use of auto-repeat | src/tonegod/gui/framework/core/util/GameTimer.java | Update to allows for modifying the duration from the onComplete call. This allows for complex stepped commands with the use of auto-repeat |
|
Java | bsd-2-clause | 70e848ff81dbfe75dbcc163709260e73bf072f09 | 0 | void256/nifty-gui,Ryszard-Trojnacki/nifty-gui,void256/nifty-gui,Ryszard-Trojnacki/nifty-gui,bgroenks96/nifty-gui,bgroenks96/nifty-gui | package de.lessvoid.nifty.render.batch.core;
import java.nio.IntBuffer;
import javax.annotation.Nonnull;
import de.lessvoid.nifty.render.batch.CheckGL;
import de.lessvoid.nifty.render.batch.spi.BufferFactory;
import de.lessvoid.nifty.render.batch.spi.core.CoreGL;
/**
* @author void
* @author Aaron Mahan <[email protected]>
*
* Note: Requires OpenGL 3.2 or greater.
*/
public class CoreProfileSaveGLState {
@Nonnull
private final CoreGL gl;
@Nonnull
private final IntBuffer params;
private int currentProgram;
private int textureBinding;
private int activeTexture;
private int samplerBindingTex0;
private boolean blending;
private int blendingSrcFactor;
private int blendingDstFactor;
private boolean primitiveRestart;
private int primitiveRestartIndex;
public CoreProfileSaveGLState(@Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory) {
this.gl = gl;
params = bufferFactory.createNativeOrderedIntBuffer(16);
}
public void saveCore() {
params.clear();
gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM(), params);
currentProgram = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_ACTIVE_TEXTURE(), params);
activeTexture = params.get(0);
params.clear();
// set active texture to zero for reading sampler binding
gl.glActiveTexture(gl.GL_ACTIVE_TEXTURE());
gl.glGetIntegerv(gl.GL_SAMPLER_BINDING(), params);
samplerBindingTex0 = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D(), params);
textureBinding = params.get(0);
blending = gl.glIsEnabled(gl.GL_BLEND());
params.clear();
gl.glGetIntegerv(gl.GL_BLEND_SRC(), params);
blendingSrcFactor = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_BLEND_DST(), params);
blendingDstFactor = params.get(0);
primitiveRestart = gl.glIsEnabled(gl.GL_PRIMITIVE_RESTART());
params.clear();
gl.glGetIntegerv(gl.GL_PRIMITIVE_RESTART_INDEX(), params);
primitiveRestartIndex = params.get(0);
CheckGL.checkGLError(gl, "Failed to save OpenGL Core Profile state!", true);
}
public void restoreCore() {
gl.glUseProgram(currentProgram);
gl.glActiveTexture(activeTexture);
gl.glBindSampler(0, samplerBindingTex0);
gl.glBindTexture(gl.GL_TEXTURE_2D(), textureBinding);
enable(gl.GL_BLEND(), blending);
gl.glBlendFunc(blendingSrcFactor, blendingDstFactor);
enable(gl.GL_PRIMITIVE_RESTART(), primitiveRestart);
gl.glPrimitiveRestartIndex(primitiveRestartIndex);
CheckGL.checkGLError(gl, "Failed to restore OpenGL Core Profile state!", true);
}
private void enable(final int state, final boolean value) {
if (value) {
gl.glEnable(state);
} else {
gl.glDisable(state);
}
}
}
| nifty-core/src/main/java/de/lessvoid/nifty/render/batch/core/CoreProfileSaveGLState.java | package de.lessvoid.nifty.render.batch.core;
import java.nio.IntBuffer;
import javax.annotation.Nonnull;
import de.lessvoid.nifty.render.batch.CheckGL;
import de.lessvoid.nifty.render.batch.spi.BufferFactory;
import de.lessvoid.nifty.render.batch.spi.core.CoreGL;
/**
* @author void
* @author Aaron Mahan <[email protected]>
*
* Note: Requires OpenGL 3.2 or greater.
*/
public class CoreProfileSaveGLState {
@Nonnull
private final CoreGL gl;
@Nonnull
private final IntBuffer params;
private int currentProgram;
private int textureBinding;
private int activeTexture;
private int samplerBindingTex0;
private boolean blending;
private int blendingSrcFactor;
private int blendingDstFactor;
private boolean primitiveRestart;
private int primitiveRestartIndex;
public CoreProfileSaveGLState(@Nonnull final CoreGL gl, @Nonnull final BufferFactory bufferFactory) {
this.gl = gl;
params = bufferFactory.createNativeOrderedIntBuffer(16);
}
public void saveCore() {
params.clear();
gl.glGetIntegerv(gl.GL_CURRENT_PROGRAM(), params);
currentProgram = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_ACTIVE_TEXTURE(), params);
activeTexture = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_SAMPLER_BINDING(), params);
samplerBindingTex0 = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_TEXTURE_BINDING_2D(), params);
textureBinding = params.get(0);
blending = gl.glIsEnabled(gl.GL_BLEND());
params.clear();
gl.glGetIntegerv(gl.GL_BLEND_SRC(), params);
blendingSrcFactor = params.get(0);
params.clear();
gl.glGetIntegerv(gl.GL_BLEND_DST(), params);
blendingDstFactor = params.get(0);
primitiveRestart = gl.glIsEnabled(gl.GL_PRIMITIVE_RESTART());
params.clear();
gl.glGetIntegerv(gl.GL_PRIMITIVE_RESTART_INDEX(), params);
primitiveRestartIndex = params.get(0);
CheckGL.checkGLError(gl, "Failed to save OpenGL Core Profile state!", true);
}
public void restoreCore() {
gl.glUseProgram(currentProgram);
gl.glActiveTexture(activeTexture);
gl.glBindSampler(0, samplerBindingTex0);
gl.glBindTexture(gl.GL_TEXTURE_2D(), textureBinding);
enable(gl.GL_BLEND(), blending);
gl.glBlendFunc(blendingSrcFactor, blendingDstFactor);
enable(gl.GL_PRIMITIVE_RESTART(), primitiveRestart);
gl.glPrimitiveRestartIndex(primitiveRestartIndex);
CheckGL.checkGLError(gl, "Failed to restore OpenGL Core Profile state!", true);
}
private void enable(final int state, final boolean value) {
if (value) {
gl.glEnable(state);
} else {
gl.glDisable(state);
}
}
}
| fix: add glActiveTexture call before sampler read.
| nifty-core/src/main/java/de/lessvoid/nifty/render/batch/core/CoreProfileSaveGLState.java | fix: add glActiveTexture call before sampler read. |
|
Java | bsd-3-clause | 186728d53ffb4c0722fc5e70b077e94d7d254368 | 0 | fbastian/owltools,owlcollab/owltools,dhimmel/owltools,dhimmel/owltools,dhimmel/owltools,dhimmel/owltools,fbastian/owltools,fbastian/owltools,owlcollab/owltools,fbastian/owltools,dhimmel/owltools,fbastian/owltools,owlcollab/owltools,owlcollab/owltools,dhimmel/owltools,owlcollab/owltools,fbastian/owltools,owlcollab/owltools | package owltools.cli;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.obolibrary.oboformat.model.FrameMergeException;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyIRIMapper;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.OWLSubClassOfAxiom;
import org.semanticweb.owlapi.model.RemoveAxiom;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import org.semanticweb.owlapi.util.AutoIRIMapper;
import org.semanticweb.owlapi.util.SimpleIRIMapper;
import com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory;
import owltools.gfx.OWLGraphLayoutRenderer;
import owltools.graph.OWLGraphEdge;
import owltools.graph.OWLGraphWrapper;
import owltools.graph.OWLQuantifiedProperty;
import owltools.graph.OWLQuantifiedProperty.Quantifier;
import owltools.io.GraphClosureWriter;
import owltools.io.OWLPrettyPrinter;
import owltools.io.ParserWrapper;
import owltools.io.TableToAxiomConverter;
import owltools.mooncat.Mooncat;
import owltools.sim.DescriptionTreeSimilarity;
import owltools.sim.MultiSimilarity;
import owltools.sim.OWLObjectPair;
import owltools.sim.Reporter;
import owltools.sim.SimEngine;
import owltools.sim.JaccardSimilarity;
import owltools.sim.SimEngine.SimilarityAlgorithmException;
import owltools.sim.SimSearch;
import owltools.sim.Similarity;
import uk.ac.manchester.cs.factplusplus.owlapiv3.FaCTPlusPlusReasonerFactory;
public class CommandLineInterface {
private static Logger LOG = Logger.getLogger(CommandLineInterface.class);
private static class Opts {
int i = 0;
String[] args;
boolean helpMode = false;
public Opts(String[] args) {
super();
this.i = 0;
this.args = args;
}
public boolean hasArgs() {
return i < args.length;
}
public boolean hasOpts() {
return hasArgs() && args[i].startsWith("-");
}
public boolean nextEq(String eq) {
if (helpMode) {
System.out.println(" "+eq);
return false;
}
if (eq.contains("|")) {
return nextEq(eq.split("\\|"));
}
if (hasArgs()) {
if (args[i].equals(eq)) {
i++;
return true;
}
}
return false;
}
private boolean nextEq(String[] eqs) {
for (String eq : eqs) {
if (nextEq(eq))
return true;
}
return false;
}
public boolean hasOpt(String opt) {
for (int j=i; j<args.length; j++) {
if (args[j].equals(opt))
return true;
}
return false;
}
public boolean nextEq(Collection<String> eqs) {
for (String eq : eqs) {
if (nextEq(eq))
return true;
}
return false;
}
public String nextOpt() {
String opt = args[i];
i++;
return opt;
}
public String peekArg() {
if (hasArgs())
return args[i];
return null;
}
public boolean nextArgIsHelp() {
if (hasArgs() && (args[i].equals("-h")
|| args[i].equals("--help"))) {
nextOpt();
return true;
}
return false;
}
public void fail() {
// TODO Auto-generated method stub
}
public void info(String params, String desc) {
if (this.nextArgIsHelp()) {
System.out.println(args[i-1]+" "+params+"\t "+desc);
System.exit(0);
}
}
}
public static void main(String[] args) throws OWLOntologyCreationException, IOException, FrameMergeException, SimilarityAlgorithmException, OWLOntologyStorageException {
List<String> paths = new ArrayList<String>();
//Integer i=0;
// REDUNDANT: see new method
//String reasonerClassName = "uk.ac.manchester.cs.factplusplus.owlapiv3.Reasoner";
String reasonerClassName = "com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory";
String reasonerName = "pellet";
boolean createNamedRestrictions = false;
boolean createDefaultInstances = false;
boolean merge = false;
OWLOntology simOnt = null;
Set<OWLSubClassOfAxiom> removedSubClassOfAxioms = null;
OWLPrettyPrinter owlpp;
//Configuration config = new PropertiesConfiguration("owltools.properties");
String similarityAlgorithmName = "JaccardSimilarity";
OWLGraphWrapper g = null;
ParserWrapper pw = new ParserWrapper();
Opts opts = new Opts(args);
while (opts.hasArgs()) {
if (opts.nextArgIsHelp()) {
help();
opts.helpMode = true;
}
//String opt = opts.nextOpt();
//System.out.println("processing arg: "+opt);
if (opts.nextEq("--pellet")) {
reasonerClassName = "com.clarkparsia.pellet.owlapiv3.Reasoner";
reasonerName = "pellet";
}
else if (opts.nextEq("--hermit")) {
reasonerClassName = "org.semanticweb.HermiT.Reasoner";
reasonerName = "hermit";
}
else if (opts.nextEq("--no-reasoner")) {
reasonerClassName = "";
reasonerName = "";
}
else if (opts.nextEq("-r") || opts.nextEq("--namerestr")) {
createNamedRestrictions = true;
}
else if (opts.nextEq("-i") || opts.nextEq("--inst")) {
createDefaultInstances = true;
}
else if (opts.nextEq("--log-info")) {
Logger.getRootLogger().setLevel(Level.INFO);
}
else if (opts.nextEq("--log-debug")) {
Logger.getRootLogger().setLevel(Level.DEBUG);
}
else if (opts.nextEq("--monitor-memory")) {
g.getConfig().isMonitorMemory = true;
}
else if (opts.nextEq("--list-classes")) {
Set<OWLClass> clss = g.getSourceOntology().getClassesInSignature();
for (OWLClass c : clss) {
System.out.println(c);
}
}
else if (opts.nextEq("--merge")) {
g.mergeOntology(pw.parse(opts.nextOpt()));
}
else if (opts.nextEq("--map-iri")) {
//OWLOntologyIRIMapper iriMapper = new SimpleIRIMapper();
}
else if (opts.nextEq("--auto-iri")) {
File file = new File(opts.nextOpt());
OWLOntologyIRIMapper iriMapper = new AutoIRIMapper(file, false);
pw.getManager().addIRIMapper(iriMapper);
}
else if (opts.nextEq("--remove-imports-declarations")) {
OWLOntology ont = g.getManager().createOntology(g.getSourceOntology().getOntologyID().getOntologyIRI());
for (OWLAxiom a : g.getSourceOntology().getAxioms()) {
g.getManager().addAxiom(ont, a);
}
g.setSourceOntology(ont);
}
else if (opts.nextEq("--merge-support-ontologies")) {
for (OWLOntology ont : g.getSupportOntologySet())
g.mergeOntology(ont);
g.setSupportOntologySet(new HashSet<OWLOntology>());
}
else if (opts.nextEq("--add-support-from-imports")) {
g.addSupportOntologiesFromImportsClosure();
}
else if (opts.nextEq("-m") || opts.nextEq("--mcat")) {
catOntologies(g,opts);
}
else if (opts.nextEq("--info")) {
opts.info("","show ontology statistics");
for (OWLOntology ont : g.getAllOntologies()) {
summarizeOntology(ont);
}
}
else if (opts.nextEq("--save-closure")) {
GraphClosureWriter gcw = new GraphClosureWriter(opts.nextOpt());
gcw.saveClosure(g);
}
else if (opts.nextEq("--serialize-closure")) {
GraphClosureWriter gcw = new GraphClosureWriter(opts.nextOpt());
gcw.serializeClosure(g);
}
else if (opts.nextEq("--run-reasoner")) {
opts.info("[-r reasonername]", "infer new relationships");
if (opts.hasOpts()) {
if (opts.nextEq("-r")) {
reasonerName = opts.nextOpt();
}
}
OWLReasoner reasoner = createReasoner(g.getSourceOntology(),reasonerName,g.getManager());
if (removedSubClassOfAxioms != null) {
System.out.println("attempting to recapitulate "+removedSubClassOfAxioms.size()+" axioms");
for (OWLSubClassOfAxiom a : removedSubClassOfAxioms) {
OWLClassExpression sup = a.getSuperClass();
if (sup instanceof OWLClass) {
boolean has = false;
for (Node<OWLClass> isup : reasoner.getSuperClasses(a.getSubClass(),true)) {
if (isup.getEntities().contains(sup)) {
has = true;
break;
}
}
System.out.print(has ? "POSITIVE: " : "NEGATIVE: ");
System.out.println(a);
}
}
}
System.out.println("all inferences");
for (OWLObject obj : g.getAllOWLObjects()) {
if (obj instanceof OWLClass) {
for (Node<OWLClass> sup : reasoner.getSuperClasses((OWLClassExpression) obj, true)) {
System.out.println(obj+" SubClassOf "+sup);
}
Node<OWLClass> ecs = reasoner.getEquivalentClasses(((OWLClassExpression) obj));
System.out.println(obj+" EquivalentTo "+ecs);
}
}
}
else if (opts.nextEq("--stash-subclasses")) {
opts.info("", "removes all subclasses in current source ontology; after reasoning, try to re-infer these");
removedSubClassOfAxioms = new HashSet<OWLSubClassOfAxiom>();
System.out.println("Stashing "+removedSubClassOfAxioms.size()+" SubClassOf axioms");
HashSet<RemoveAxiom> rmaxs = new HashSet<RemoveAxiom>();
for (OWLSubClassOfAxiom a : g.getSourceOntology().getAxioms(AxiomType.SUBCLASS_OF)) {
RemoveAxiom rmax = new RemoveAxiom(g.getSourceOntology(),a);
rmaxs.add(rmax);
removedSubClassOfAxioms.add(g.getDataFactory().getOWLSubClassOfAxiom(a.getSubClass(), a.getSuperClass()));
}
for (RemoveAxiom rmax : rmaxs) {
g.getManager().applyChange(rmax);
}
}
else if (opts.nextEq("-a|--ancestors")) {
opts.info("LABEL", "list edges in graph closure to root nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosureReflexive(obj);
showEdges(edges);
}
else if (opts.nextEq("--ancestors-with-ic")) {
opts.info("LABEL", "list edges in graph closure to root nodes, with the IC of the target node");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosureReflexive(obj);
SimEngine se = new SimEngine(g);
for (OWLGraphEdge e : edges) {
System.out.println(e);
System.out.println(" TARGET IC:"+se.getInformationContent(e.getTarget()));
}
}
else if (opts.nextEq("--ancestor-nodes")) {
opts.info("LABEL", "list nodes in graph closure to root nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
for (OWLObject a : g.getAncestors(obj))
System.out.println(a);
}
else if (opts.nextEq("--parents-named")) {
opts.info("LABEL", "list direct outgoing edges to named classes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getOutgoingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--parents")) {
opts.info("LABEL", "list direct outgoing edges");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getPrimitiveOutgoingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--grandparents")) {
opts.info("LABEL", "list direct outgoing edges and their direct outgoing edges");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getPrimitiveOutgoingEdges(obj);
for (OWLGraphEdge e1 : edges) {
System.out.println(e1);
for (OWLGraphEdge e2 : g.getPrimitiveOutgoingEdges(e1.getTarget())) {
System.out.println(" "+e2);
}
}
}
else if (opts.nextEq("--subsumers")) {
opts.info("LABEL", "list named subsumers and subsuming expressions");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
Set<OWLObject> ancs = g.getSubsumersFromClosure(obj);
for (OWLObject a : ancs) {
System.out.println(a);
}
}
else if (opts.nextEq("--incoming-edges")) {
opts.info("LABEL", "list edges in graph to leaf nodes");
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getIncomingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--descendant-edges")) {
opts.info("LABEL", "list edges in graph closure to leaf nodes");
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getIncomingEdgesClosure(obj);
showEdges(edges);
}
else if (opts.nextEq("--descendants")) {
opts.info("LABEL", "show all descendant nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLObject> ds = g.getDescendants(obj);
for (OWLObject d : ds)
System.out.println(d);
}
else if (opts.nextEq("--subsumed-by")) {
opts.info("LABEL", "show all descendant nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLObject> ds = g.queryDescendants((OWLClass)obj);
for (OWLObject d : ds)
System.out.println(d);
}
else if (opts.nextEq("-d") || opts.nextEq("--draw")) {
opts.info("LABEL", "generates a file tmp.png made using QuickGO code");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj);
OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(g);
r.addObject(obj);
r.renderImage("png", new FileOutputStream("tmp.png"));
Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosureReflexive(obj);
showEdges(edges);
}
else if (opts.nextEq("--draw-all")) {
opts.info("", "draws ALL objects in the ontology (caution: small ontologies only)");
//System.out.println("i= "+i);
OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(g);
r.addAllObjects();
r.renderImage("png", new FileOutputStream("tmp.png"));
}
else if (opts.nextEq("--dump-node-attributes")) {
opts.info("", "dumps all nodes attributes in CytoScape compliant format");
FileOutputStream fos;
PrintStream stream = null;
try {
fos = new FileOutputStream(opts.nextOpt());
stream = new PrintStream(new BufferedOutputStream(fos));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stream.println("Label");
for (OWLObject obj : g.getAllOWLObjects()) {
String label = g.getLabel(obj);
if (label != null)
stream.println(g.getIdentifier(obj)+"\t=\t"+label);
}
stream.close();
}
else if (opts.nextEq("--dump-sif")) {
opts.info("", "dumps CytoScape compliant sif format");
FileOutputStream fos;
PrintStream stream = null;
try {
fos = new FileOutputStream(opts.nextOpt());
stream = new PrintStream(new BufferedOutputStream(fos));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (OWLObject x : g.getAllOWLObjects()) {
for (OWLGraphEdge e : g.getOutgoingEdges(x)) {
OWLQuantifiedProperty qp = e.getSingleQuantifiedProperty();
String label;
if (qp.getProperty() != null)
label = qp.getProperty().toString();
else
label = qp.getQuantifier().toString();
if (label != null)
stream.println(g.getIdentifier(x)+"\t"+label+"\t"+g.getIdentifier(e.getTarget()));
}
}
stream.close();
}
else if (opts.nextEq("--all-class-ic")) {
opts.info("", "show calculated Information Content for all classes");
SimEngine se = new SimEngine(g);
Similarity sa = se.getSimilarityAlgorithm(similarityAlgorithmName);
// no point in caching, as we only check descendants of each object once
g.getConfig().isCacheClosure = false;
for (OWLObject obj : g.getAllOWLObjects()) {
if (se.hasInformationContent(obj)) {
System.out.println(obj+"\t"+se.getInformationContent(obj));
}
}
}
else if (opts.nextEq("--sim-method")) {
opts.info("metric", "sets deafult similarity metric. Type --all to show all TODO");
similarityAlgorithmName = opts.nextOpt();
}
else if (opts.nextEq("--sim-all")) {
opts.info("", "calculates similarity between all pairs");
Double minScore = null;
SimEngine se = new SimEngine(g);
if (opts.hasOpts()) {
if (opts.nextEq("-m|--min")) {
minScore = Double.valueOf(opts.nextOpt());
}
else if (opts.nextEq("-s|--subclass-of")) {
se.comparisonSuperclass = resolveEntity(g,opts);
}
}
//Similarity metric = se.getSimilarityAlgorithm(similarityAlgorithmName);
//SimilarityAlgorithm metric = se.new JaccardSimilarity();
se.calculateSimilarityAllByAll(similarityAlgorithmName, minScore);
//System.out.println(metric.getClass().getName());
}
else if (opts.nextEq("--sim")) {
Reporter reporter = new Reporter(g);
opts.info("[-m metric] A B", "calculates similarity between A and B");
boolean nr = false;
Vector<OWLObjectPair> pairs = new Vector<OWLObjectPair>();
String subSimMethod = null;
boolean isAll = false;
SimEngine se = new SimEngine(g);
while (opts.hasOpts()) {
System.out.println("sub-opts for --sim");
if (opts.nextEq("-m")) {
similarityAlgorithmName = opts.nextOpt();
}
else if (opts.nextEq("-p")) {
se.comparisonProperty = g.getOWLObjectProperty(opts.nextOpt());
}
else if (opts.nextEq("--min-ic")) {
se.minimumIC = Double.valueOf(opts.nextOpt());
}
else if (opts.nextEq("--sub-method")) {
opts.info("MethodName","sets the method used to compare all attributes in a MultiSim test");
subSimMethod = opts.nextOpt();
}
else if (opts.nextEq("--query")) {
OWLObject q = resolveEntity(g,opts.nextOpt());
SimSearch search = new SimSearch(se, reporter);
isAll = true;
boolean isClasses = true;
boolean isInstances = true;
int MAX_PAIRS = 50; // todo - make configurable
while (opts.hasOpts()) {
if (opts.nextEq("-i"))
isClasses = false;
else if (opts.nextEq("-c"))
isInstances = false;
else if (opts.nextEq("--max-hits"))
MAX_PAIRS = Integer.parseInt(opts.nextOpt());
else
break;
}
search.setMaxHits(MAX_PAIRS);
OWLObject cc = resolveEntity(g,opts.nextOpt());
Set<OWLObject> candidates = g.queryDescendants((OWLClass)cc, isInstances, isClasses);
candidates.remove(cc);
search.setCandidates(candidates);
System.out.println(" numCandidates:"+candidates.size());
List<OWLObject> hits = search.search(q);
System.out.println(" hits:"+hits.size());
int n = 0;
for (OWLObject hit : hits) {
if (n < MAX_PAIRS)
pairs.add(new OWLObjectPair(q,hit));
n++;
System.out.println("HIT:"+n+"\t"+g.getLabelOrDisplayId(hit));
}
while (opts.nextEq("--include")) {
OWLObjectPair pair = new OWLObjectPair(q,resolveEntity(g,opts.nextOpt()));
if (!pairs.contains(pair)) {
pairs.add(pair);
System.out.println("adding_extra_pair:"+pair);
}
else {
System.out.println("extra_pair_alrwady_added:"+pair);
}
}
}
else if (opts.nextEq("-a|--all")) {
isAll = true;
boolean isClasses = true;
boolean isInstances = true;
if (opts.nextEq("-i"))
isClasses = false;
if (opts.nextEq("-c"))
isInstances = false;
OWLObject anc = resolveEntity(g,opts.nextOpt());
System.out.println("Set1:"+anc+" "+anc.getClass());
Set<OWLObject> objs = g.queryDescendants((OWLClass)anc, isInstances, isClasses);
objs.remove(anc);
System.out.println(" Size1:"+objs.size());
Set<OWLObject> objs2 = objs;
if (opts.nextEq("--vs")) {
OWLObject anc2 = resolveEntity(g,opts.nextOpt());
System.out.println("Set2:"+anc2+" "+anc2.getClass());
objs2 = g.queryDescendants((OWLClass)anc2, isInstances, isClasses);
objs2.remove(anc2);
System.out.println(" Size2:"+objs2.size());
}
for (OWLObject a : objs) {
if (!(a instanceof OWLNamedObject)) {
continue;
}
for (OWLObject b : objs2) {
if (!(b instanceof OWLNamedObject)) {
continue;
}
if (a.equals(b))
continue;
//if (a.compareTo(b) <= 0)
// continue;
OWLObjectPair pair = new OWLObjectPair(a,b);
System.out.println("Scheduling:"+pair);
pairs.add(pair);
}
}
}
else if (opts.nextEq("-s|--subclass-of")) {
se.comparisonSuperclass = resolveEntity(g,opts);
}
else if (opts.nextEq("--no-create-reflexive")) {
nr = true;
}
else {
// not recognized - end of this block of opts
break;
//System.err.println("???"+opts.nextOpt());
}
}
if (isAll) {
// TODO
//se.calculateSimilarityAllByAll(similarityAlgorithmName, 0.0);
}
else {
pairs.add(new OWLObjectPair(resolveEntity(g,opts.nextOpt()),
resolveEntity(g,opts.nextOpt())));
}
for (OWLObjectPair pair : pairs) {
OWLObject oa = pair.getA();
OWLObject ob = pair.getB();
Similarity metric = se.getSimilarityAlgorithm(similarityAlgorithmName);
if (nr) {
((DescriptionTreeSimilarity)metric).forceReflexivePropertyCreation = false;
}
if (subSimMethod != null)
((MultiSimilarity)metric).setSubSimMethod(subSimMethod);
System.out.println("comparing: "+oa+" vs "+ob);
Similarity r = se.calculateSimilarity(metric, oa, ob);
//System.out.println(metric+" = "+r);
metric.print();
metric.report(reporter);
if (simOnt == null) {
simOnt = g.getManager().createOntology();
}
if (opts.hasOpt("--save-sim")) {
metric.addResultsToOWLOntology(simOnt);
}
}
}
else if (opts.nextEq("-o|--output")) {
opts.info("FILE", "writes source ontology -- specified as IRI, e.g. file://`pwd`/foo.owl");
pw.saveOWL(g.getSourceOntology(), opts.nextOpt());
}
else if (opts.nextEq("--save-sim")) {
opts.info("FILE", "saves similarity results as an OWL ontology. Use after --sim or --sim-all");
pw.saveOWL(simOnt, opts.nextOpt());
}
else if (opts.nextEq("--merge-sim")) {
opts.info("FILE", "merges similarity results into source OWL ontology. Use after --sim or --sim-all");
g.mergeOntology(simOnt);
}
else if (opts.nextEq("--list-axioms")) {
for (OWLAxiom a : g.getSourceOntology().getAxioms()) {
System.out.println("AX:"+a);
}
}
else if (opts.nextEq("--follow-subclass")) {
opts.info("", "follow subclass axioms (and also equivalence axioms) in graph traversal.\n"+
" default is to follow ALL. if this is specified then only explicitly specified edges followed");
if (g.getConfig().graphEdgeIncludeSet == null)
g.getConfig().graphEdgeIncludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeIncludeSet.add(new OWLQuantifiedProperty(Quantifier.SUBCLASS_OF));
}
else if (opts.nextEq("--follow-property")) {
opts.info("PROP-LABEL", "follow object properties of this type in graph traversal.\n"+
" default is to follow ALL. if this is specified then only explicitly specified edges followed");
OWLObjectProperty p = (OWLObjectProperty) resolveEntity(g, opts);
if (g.getConfig().graphEdgeIncludeSet == null)
g.getConfig().graphEdgeIncludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeIncludeSet.add(new OWLQuantifiedProperty(p, null));
}
else if (opts.nextEq("--exclude-property")) {
opts.info("PROP-LABEL", "exclude object properties of this type in graph traversal.\n"+
" default is to exclude NONE.");
OWLObjectProperty p = g.getOWLObjectProperty(opts.nextOpt());
System.out.println("Excluding "+p+" "+p.getClass());
if (g.getConfig().graphEdgeExcludeSet == null)
g.getConfig().graphEdgeExcludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeExcludeSet.add(new OWLQuantifiedProperty(p, null));
}
else if (opts.nextEq("--exclude-metaclass")) {
opts.info("METACLASS-LABEL", "exclude classes of this type in graph traversal.\n"+
" default is to follow ALL classes");
OWLClass c = (OWLClass) resolveEntity(g, opts);
g.getConfig().excludeMetaClass = c;
}
else if (opts.nextEq("--parse-tsv")) {
opts.info("[-s] FILE", "parses a tabular file to OWL axioms");
TableToAxiomConverter ttac = new TableToAxiomConverter(g);
ttac.config.axiomType = AxiomType.CLASS_ASSERTION;
while (opts.hasOpts()) {
if (opts.nextEq("-s")) {
ttac.config.isSwitchSubjectObject = true;
}
else if (opts.nextEq("-l|--label")) {
ttac.config.setPropertyToLabel();
ttac.config.axiomType = AxiomType.ANNOTATION_ASSERTION;
}
else if (opts.nextEq("-p|--prop")) {
ttac.config.property = ((OWLNamedObject) resolveEntity(g, opts)).getIRI();
}
else if (opts.nextEq("-a|--axiom-type")) {
ttac.config.setAxiomType(opts.nextOpt());
}
else if (opts.nextEq("-t|--individuals-type")) {
System.out.println("setting types");
ttac.config.individualsType = resolveClass(g, opts.nextOpt());
}
else {
// TODO - other options
}
}
String f = opts.nextOpt();
System.out.println("tabfile: "+f);
ttac.parse(f);
}
else if (opts.nextEq("--no-cache")) {
g.getConfig().isCacheClosure = false;
}
else if (opts.nextEq("--create-ontology")) {
opts.info("ONT-IRI", "creates a new OWLOntology and makes it the source ontology");
g = new OWLGraphWrapper(opts.nextOpt());
}
else if (opts.hasArgs()) {
String f = opts.nextOpt();
try {
OWLOntology ont = pw.parse(f);
if (g == null)
g = new OWLGraphWrapper(ont);
else {
System.out.println("adding support ont "+ont);
g.addSupportOntology(ont);
}
}
catch (Exception e) {
System.err.println("could not parse:"+f+" Exception:"+e);
System.exit(1);
}
//paths.add(opt);
}
else {
if (opts.helpMode)
helpFooter();
// should only reach here in help mode
}
}
/*
OWLGraphWrapper g;
if (paths.size() == 0) {
throw new Error("must specify at least one file");
}
if (paths.size() > 1) {
if (merge) {
// note: currently we can only merge obo files
pw.parseOBOFiles(paths);
}
else {
throw new Error("cannot load multiple files unless --merge is set");
}
}
else {
g = pw.parseToOWLGraph(paths.get(0));
}
*/
}
private static OWLReasoner createReasoner(OWLOntology ont, String reasonerName,
OWLOntologyManager manager) {
OWLReasonerFactory reasonerFactory = null;
if (reasonerName == null || reasonerName.equals("factpp"))
reasonerFactory = new FaCTPlusPlusReasonerFactory();
else if (reasonerName.equals("pellet"))
reasonerFactory = new PelletReasonerFactory();
else if (reasonerName.equals("hermit")) {
//return new org.semanticweb.HermiT.Reasoner.ReasonerFactory().createReasoner(ont);
//reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory();
}
else
System.out.println("no such reasoner: "+reasonerName);
OWLReasoner reasoner = reasonerFactory.createReasoner(ont);
return reasoner;
}
private static void catOntologies(OWLGraphWrapper g, Opts opts) throws OWLOntologyCreationException, IOException {
opts.info("[-r|--ref-ont ONT] [-i|--use-imports]", "Catenate ontologies taking only referenced subsets of supporting onts.\n"+
" See Mooncat docs");
Mooncat m = new Mooncat(g);
ParserWrapper pw = new ParserWrapper();
if (opts.hasOpts()) {
//String opt = opts.nextOpt();
if (opts.nextEq("-r") || opts.nextEq("--ref-ont")) {
String f = opts.nextOpt();
m.addReferencedOntology(pw.parseOWL(f));
}
else if (opts.nextEq("-s") || opts.nextEq("--src-ont")) {
m.setOntology(pw.parseOWL(opts.nextOpt()));
}
else if (opts.nextEq("-i") || opts.nextEq("--use-imports")) {
System.out.println("using everything in imports closure");
g.addSupportOntologiesFromImportsClosure();
}
else {
opts.fail();
}
}
if (m.getReferencedOntologies().size() == 0) {
m.setReferencedOntologies(g.getSupportOntologySet());
}
//g.useImportClosureForQueries();
for (OWLAxiom ax : m.getClosureAxiomsOfExternalReferencedEntities()) {
System.out.println("M_AX:"+ax);
}
m.mergeOntologies();
}
private static void showEdges(Set<OWLGraphEdge> edges) {
for (OWLGraphEdge e : edges) {
System.out.println(e);
}
}
public static void summarizeOntology(OWLOntology ont) {
System.out.println("Ontology:"+ont);
System.out.println(" Classes:"+ont.getClassesInSignature().size());
System.out.println(" Individuals:"+ont.getIndividualsInSignature().size());
System.out.println(" ObjectProperties:"+ont.getObjectPropertiesInSignature().size());
System.out.println(" AxiomCount:"+ont.getAxiomCount());
}
// todo - move to util
public static OWLObject resolveEntity(OWLGraphWrapper g, Opts opts) {
OWLObject obj = null;
String id = opts.nextOpt(); // in future we will allow resolution by name etc
return resolveEntity(g,id);
}
public static OWLObject resolveEntity(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return obj;
obj = g.getOWLObject(id);
if (obj != null)
return obj;
obj = g.getOWLObjectByIdentifier(id);
return obj;
}
public static OWLObjectProperty resolveObjectProperty(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return (OWLObjectProperty) obj;
return g.getOWLObjectProperty(id);
}
public static OWLClass resolveClass(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return (OWLClass) obj;
return g.getDataFactory().getOWLClass(IRI.create(id));
}
public static void help() {
System.out.println("owltools [ONTOLOGY ...] [COMMAND ...]\n");
System.out.println("Commands/Options");
System.out.println(" (type 'owltools COMMAND -h' for more info)");
}
public static void helpFooter() {
System.out.println("\nOntologies:");
System.out.println(" These are specified as IRIs. The IRI is typically 'file:PATH' or a URL");
System.out.println("\nLabel Resolution:");
System.out.println(" you can pass in either a class label (enclosed in single quotes), an OBO ID or a IRI");
System.out.println("\nExecution:");
System.out.println(" note that commands are processed *in order*. This allows you to run mini-pipelines" +
" or programs on the command line");
System.out.println("\nExamples:");
System.out.println(" ");
}
}
| src/owltools/cli/CommandLineInterface.java | package owltools.cli;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.obolibrary.oboformat.model.FrameMergeException;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLImportsDeclaration;
import org.semanticweb.owlapi.model.OWLNamedObject;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLObjectProperty;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyIRIMapper;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.semanticweb.owlapi.model.OWLSubClassOfAxiom;
import org.semanticweb.owlapi.model.RemoveAxiom;
import org.semanticweb.owlapi.reasoner.Node;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import org.semanticweb.owlapi.util.AutoIRIMapper;
import org.semanticweb.owlapi.util.SimpleIRIMapper;
import com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory;
import owltools.gfx.OWLGraphLayoutRenderer;
import owltools.graph.OWLGraphEdge;
import owltools.graph.OWLGraphWrapper;
import owltools.graph.OWLQuantifiedProperty;
import owltools.graph.OWLQuantifiedProperty.Quantifier;
import owltools.io.GraphClosureWriter;
import owltools.io.OWLPrettyPrinter;
import owltools.io.ParserWrapper;
import owltools.io.TableToAxiomConverter;
import owltools.mooncat.Mooncat;
import owltools.sim.DescriptionTreeSimilarity;
import owltools.sim.MultiSimilarity;
import owltools.sim.OWLObjectPair;
import owltools.sim.Reporter;
import owltools.sim.SimEngine;
import owltools.sim.JaccardSimilarity;
import owltools.sim.SimEngine.SimilarityAlgorithmException;
import owltools.sim.SimSearch;
import owltools.sim.Similarity;
import uk.ac.manchester.cs.factplusplus.owlapiv3.FaCTPlusPlusReasonerFactory;
public class CommandLineInterface {
private static Logger LOG = Logger.getLogger(CommandLineInterface.class);
private static class Opts {
int i = 0;
String[] args;
boolean helpMode = false;
public Opts(String[] args) {
super();
this.i = 0;
this.args = args;
}
public boolean hasArgs() {
return i < args.length;
}
public boolean hasOpts() {
return hasArgs() && args[i].startsWith("-");
}
public boolean nextEq(String eq) {
if (helpMode) {
System.out.println(" "+eq);
return false;
}
if (eq.contains("|")) {
return nextEq(eq.split("\\|"));
}
if (hasArgs()) {
if (args[i].equals(eq)) {
i++;
return true;
}
}
return false;
}
private boolean nextEq(String[] eqs) {
for (String eq : eqs) {
if (nextEq(eq))
return true;
}
return false;
}
public boolean hasOpt(String opt) {
for (int j=i; j<args.length; j++) {
if (args[j].equals(opt))
return true;
}
return false;
}
public boolean nextEq(Collection<String> eqs) {
for (String eq : eqs) {
if (nextEq(eq))
return true;
}
return false;
}
public String nextOpt() {
String opt = args[i];
i++;
return opt;
}
public String peekArg() {
if (hasArgs())
return args[i];
return null;
}
public boolean nextArgIsHelp() {
if (hasArgs() && (args[i].equals("-h")
|| args[i].equals("--help"))) {
nextOpt();
return true;
}
return false;
}
public void fail() {
// TODO Auto-generated method stub
}
public void info(String params, String desc) {
if (this.nextArgIsHelp()) {
System.out.println(args[i-1]+" "+params+"\t "+desc);
System.exit(0);
}
}
}
public static void main(String[] args) throws OWLOntologyCreationException, IOException, FrameMergeException, SimilarityAlgorithmException, OWLOntologyStorageException {
List<String> paths = new ArrayList<String>();
//Integer i=0;
// REDUNDANT: see new method
//String reasonerClassName = "uk.ac.manchester.cs.factplusplus.owlapiv3.Reasoner";
String reasonerClassName = "com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory";
String reasonerName = "pellet";
boolean createNamedRestrictions = false;
boolean createDefaultInstances = false;
boolean merge = false;
OWLOntology simOnt = null;
Set<OWLSubClassOfAxiom> removedSubClassOfAxioms = null;
OWLPrettyPrinter owlpp;
//Configuration config = new PropertiesConfiguration("owltools.properties");
String similarityAlgorithmName = "JaccardSimilarity";
OWLGraphWrapper g = null;
ParserWrapper pw = new ParserWrapper();
Opts opts = new Opts(args);
while (opts.hasArgs()) {
if (opts.nextArgIsHelp()) {
help();
opts.helpMode = true;
}
//String opt = opts.nextOpt();
//System.out.println("processing arg: "+opt);
if (opts.nextEq("--pellet")) {
reasonerClassName = "com.clarkparsia.pellet.owlapiv3.Reasoner";
reasonerName = "pellet";
}
else if (opts.nextEq("--hermit")) {
reasonerClassName = "org.semanticweb.HermiT.Reasoner";
reasonerName = "hermit";
}
else if (opts.nextEq("--no-reasoner")) {
reasonerClassName = "";
reasonerName = "";
}
else if (opts.nextEq("-r") || opts.nextEq("--namerestr")) {
createNamedRestrictions = true;
}
else if (opts.nextEq("-i") || opts.nextEq("--inst")) {
createDefaultInstances = true;
}
else if (opts.nextEq("--log-info")) {
Logger.getRootLogger().setLevel(Level.INFO);
}
else if (opts.nextEq("--log-debug")) {
Logger.getRootLogger().setLevel(Level.DEBUG);
}
else if (opts.nextEq("--monitor-memory")) {
g.getConfig().isMonitorMemory = true;
}
else if (opts.nextEq("--list-classes")) {
Set<OWLClass> clss = g.getSourceOntology().getClassesInSignature();
for (OWLClass c : clss) {
System.out.println(c);
}
}
else if (opts.nextEq("--merge")) {
g.mergeOntology(pw.parse(opts.nextOpt()));
}
else if (opts.nextEq("--map-iri")) {
//OWLOntologyIRIMapper iriMapper = new SimpleIRIMapper();
}
else if (opts.nextEq("--auto-iri")) {
File file = new File(opts.nextOpt());
OWLOntologyIRIMapper iriMapper = new AutoIRIMapper(file, false);
pw.getManager().addIRIMapper(iriMapper);
}
else if (opts.nextEq("--remove-imports-declarations")) {
OWLOntology ont = g.getManager().createOntology(g.getSourceOntology().getOntologyID().getOntologyIRI());
for (OWLAxiom a : g.getSourceOntology().getAxioms()) {
g.getManager().addAxiom(ont, a);
}
g.setSourceOntology(ont);
}
else if (opts.nextEq("--merge-support-ontologies")) {
for (OWLOntology ont : g.getSupportOntologySet())
g.mergeOntology(ont);
g.setSupportOntologySet(new HashSet<OWLOntology>());
}
else if (opts.nextEq("--add-support-from-imports")) {
g.addSupportOntologiesFromImportsClosure();
}
else if (opts.nextEq("-m") || opts.nextEq("--mcat")) {
catOntologies(g,opts);
}
else if (opts.nextEq("--info")) {
opts.info("","show ontology statistics");
for (OWLOntology ont : g.getAllOntologies()) {
summarizeOntology(ont);
}
}
else if (opts.nextEq("--save-closure")) {
GraphClosureWriter gcw = new GraphClosureWriter(opts.nextOpt());
gcw.saveClosure(g);
}
else if (opts.nextEq("--serialize-closure")) {
GraphClosureWriter gcw = new GraphClosureWriter(opts.nextOpt());
gcw.serializeClosure(g);
}
else if (opts.nextEq("--run-reasoner")) {
opts.info("[-r reasonername]", "infer new relationships");
if (opts.hasOpts()) {
if (opts.nextEq("-r")) {
reasonerName = opts.nextOpt();
}
}
OWLReasoner reasoner = createReasoner(g.getSourceOntology(),reasonerName,g.getManager());
if (removedSubClassOfAxioms != null) {
System.out.println("attempting to recapitulate "+removedSubClassOfAxioms.size()+" axioms");
for (OWLSubClassOfAxiom a : removedSubClassOfAxioms) {
OWLClassExpression sup = a.getSuperClass();
if (sup instanceof OWLClass) {
boolean has = false;
for (Node<OWLClass> isup : reasoner.getSuperClasses(a.getSubClass(),true)) {
if (isup.getEntities().contains(sup)) {
has = true;
break;
}
}
System.out.print(has ? "POSITIVE: " : "NEGATIVE: ");
System.out.println(a);
}
}
}
System.out.println("all inferences");
for (OWLObject obj : g.getAllOWLObjects()) {
if (obj instanceof OWLClass) {
for (Node<OWLClass> sup : reasoner.getSuperClasses((OWLClassExpression) obj, true)) {
System.out.println(obj+" SubClassOf "+sup);
}
Node<OWLClass> ecs = reasoner.getEquivalentClasses(((OWLClassExpression) obj));
System.out.println(obj+" EquivalentTo "+ecs);
}
}
}
else if (opts.nextEq("--stash-subclasses")) {
opts.info("", "removes all subclasses in current source ontology; after reasoning, try to re-infer these");
removedSubClassOfAxioms = new HashSet<OWLSubClassOfAxiom>();
System.out.println("Stashing "+removedSubClassOfAxioms.size()+" SubClassOf axioms");
HashSet<RemoveAxiom> rmaxs = new HashSet<RemoveAxiom>();
for (OWLSubClassOfAxiom a : g.getSourceOntology().getAxioms(AxiomType.SUBCLASS_OF)) {
RemoveAxiom rmax = new RemoveAxiom(g.getSourceOntology(),a);
rmaxs.add(rmax);
removedSubClassOfAxioms.add(g.getDataFactory().getOWLSubClassOfAxiom(a.getSubClass(), a.getSuperClass()));
}
for (RemoveAxiom rmax : rmaxs) {
g.getManager().applyChange(rmax);
}
}
else if (opts.nextEq("-a|--ancestors")) {
opts.info("LABEL", "list edges in graph closure to root nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosureReflexive(obj);
showEdges(edges);
}
else if (opts.nextEq("--ancestor-nodes")) {
opts.info("LABEL", "list nodes in graph closure to root nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
for (OWLObject a : g.getAncestors(obj))
System.out.println(a);
}
else if (opts.nextEq("--parents-named")) {
opts.info("LABEL", "list direct outgoing edges to named classes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getOutgoingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--parents")) {
opts.info("LABEL", "list direct outgoing edges");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getPrimitiveOutgoingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--grandparents")) {
opts.info("LABEL", "list direct outgoing edges and their direct outgoing edges");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getPrimitiveOutgoingEdges(obj);
for (OWLGraphEdge e1 : edges) {
System.out.println(e1);
for (OWLGraphEdge e2 : g.getPrimitiveOutgoingEdges(e1.getTarget())) {
System.out.println(" "+e2);
}
}
}
else if (opts.nextEq("--subsumers")) {
opts.info("LABEL", "list named subsumers and subsuming expressions");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
Set<OWLObject> ancs = g.getSubsumersFromClosure(obj);
for (OWLObject a : ancs) {
System.out.println(a);
}
}
else if (opts.nextEq("--incoming-edges")) {
opts.info("LABEL", "list edges in graph to leaf nodes");
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getIncomingEdges(obj);
showEdges(edges);
}
else if (opts.nextEq("--descendant-edges")) {
opts.info("LABEL", "list edges in graph closure to leaf nodes");
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLGraphEdge> edges = g.getIncomingEdgesClosure(obj);
showEdges(edges);
}
else if (opts.nextEq("--descendants")) {
opts.info("LABEL", "show all descendant nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLObject> ds = g.getDescendants(obj);
for (OWLObject d : ds)
System.out.println(d);
}
else if (opts.nextEq("--subsumed-by")) {
opts.info("LABEL", "show all descendant nodes");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj+ " "+obj.getClass());
Set<OWLObject> ds = g.queryDescendants((OWLClass)obj);
for (OWLObject d : ds)
System.out.println(d);
}
else if (opts.nextEq("-d") || opts.nextEq("--draw")) {
opts.info("LABEL", "generates a file tmp.png made using QuickGO code");
//System.out.println("i= "+i);
OWLObject obj = resolveEntity(g, opts);
System.out.println(obj);
OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(g);
r.addObject(obj);
r.renderImage("png", new FileOutputStream("tmp.png"));
Set<OWLGraphEdge> edges = g.getOutgoingEdgesClosureReflexive(obj);
showEdges(edges);
}
else if (opts.nextEq("--draw-all")) {
opts.info("", "draws ALL objects in the ontology (caution: small ontologies only)");
//System.out.println("i= "+i);
OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(g);
r.addAllObjects();
r.renderImage("png", new FileOutputStream("tmp.png"));
}
else if (opts.nextEq("--dump-node-attributes")) {
opts.info("", "dumps all nodes attributes in CytoScape compliant format");
FileOutputStream fos;
PrintStream stream = null;
try {
fos = new FileOutputStream(opts.nextOpt());
stream = new PrintStream(new BufferedOutputStream(fos));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stream.println("Label");
for (OWLObject obj : g.getAllOWLObjects()) {
String label = g.getLabel(obj);
if (label != null)
stream.println(g.getIdentifier(obj)+"\t=\t"+label);
}
stream.close();
}
else if (opts.nextEq("--dump-sif")) {
opts.info("", "dumps CytoScape compliant sif format");
FileOutputStream fos;
PrintStream stream = null;
try {
fos = new FileOutputStream(opts.nextOpt());
stream = new PrintStream(new BufferedOutputStream(fos));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (OWLObject x : g.getAllOWLObjects()) {
for (OWLGraphEdge e : g.getOutgoingEdges(x)) {
OWLQuantifiedProperty qp = e.getSingleQuantifiedProperty();
String label;
if (qp.getProperty() != null)
label = qp.getProperty().toString();
else
label = qp.getQuantifier().toString();
if (label != null)
stream.println(g.getIdentifier(x)+"\t"+label+"\t"+g.getIdentifier(e.getTarget()));
}
}
stream.close();
}
else if (opts.nextEq("--all-class-ic")) {
opts.info("", "show calculated Information Content for all classes");
SimEngine se = new SimEngine(g);
Similarity sa = se.getSimilarityAlgorithm(similarityAlgorithmName);
// no point in caching, as we only check descendants of each object once
g.getConfig().isCacheClosure = false;
for (OWLObject obj : g.getAllOWLObjects()) {
if (se.hasInformationContent(obj)) {
System.out.println(obj+"\t"+se.getInformationContent(obj));
}
}
}
else if (opts.nextEq("--sim-method")) {
opts.info("metric", "sets deafult similarity metric. Type --all to show all TODO");
similarityAlgorithmName = opts.nextOpt();
}
else if (opts.nextEq("--sim-all")) {
opts.info("", "calculates similarity between all pairs");
Double minScore = null;
SimEngine se = new SimEngine(g);
if (opts.hasOpts()) {
if (opts.nextEq("-m|--min")) {
minScore = Double.valueOf(opts.nextOpt());
}
else if (opts.nextEq("-s|--subclass-of")) {
se.comparisonSuperclass = resolveEntity(g,opts);
}
}
//Similarity metric = se.getSimilarityAlgorithm(similarityAlgorithmName);
//SimilarityAlgorithm metric = se.new JaccardSimilarity();
se.calculateSimilarityAllByAll(similarityAlgorithmName, minScore);
//System.out.println(metric.getClass().getName());
}
else if (opts.nextEq("--sim")) {
Reporter reporter = new Reporter(g);
opts.info("[-m metric] A B", "calculates similarity between A and B");
boolean nr = false;
Vector<OWLObjectPair> pairs = new Vector<OWLObjectPair>();
String subSimMethod = null;
boolean isAll = false;
SimEngine se = new SimEngine(g);
while (opts.hasOpts()) {
System.out.println("sub-opts for --sim");
if (opts.nextEq("-m")) {
similarityAlgorithmName = opts.nextOpt();
}
else if (opts.nextEq("-p")) {
se.comparisonProperty = g.getOWLObjectProperty(opts.nextOpt());
}
else if (opts.nextEq("--min-ic")) {
se.minimumIC = Double.valueOf(opts.nextOpt());
}
else if (opts.nextEq("--sub-method")) {
opts.info("MethodName","sets the method used to compare all attributes in a MultiSim test");
subSimMethod = opts.nextOpt();
}
else if (opts.nextEq("--query")) {
OWLObject q = resolveEntity(g,opts.nextOpt());
SimSearch search = new SimSearch(se, reporter);
isAll = true;
boolean isClasses = true;
boolean isInstances = true;
int MAX_PAIRS = 50; // todo - make configurable
while (opts.hasOpts()) {
if (opts.nextEq("-i"))
isClasses = false;
else if (opts.nextEq("-c"))
isInstances = false;
else if (opts.nextEq("--max-hits"))
MAX_PAIRS = Integer.parseInt(opts.nextOpt());
else
break;
}
search.setMaxHits(MAX_PAIRS);
OWLObject cc = resolveEntity(g,opts.nextOpt());
Set<OWLObject> candidates = g.queryDescendants((OWLClass)cc, isInstances, isClasses);
candidates.remove(cc);
search.setCandidates(candidates);
System.out.println(" numCandidates:"+candidates.size());
List<OWLObject> hits = search.search(q);
System.out.println(" hits:"+hits.size());
int n = 0;
for (OWLObject hit : hits) {
if (n < MAX_PAIRS)
pairs.add(new OWLObjectPair(q,hit));
n++;
System.out.println("HIT:"+n+"\t"+g.getLabelOrDisplayId(hit));
}
while (opts.nextEq("--include")) {
OWLObjectPair pair = new OWLObjectPair(q,resolveEntity(g,opts.nextOpt()));
if (!pairs.contains(pair)) {
pairs.add(pair);
System.out.println("adding_extra_pair:"+pair);
}
else {
System.out.println("extra_pair_alrwady_added:"+pair);
}
}
}
else if (opts.nextEq("-a|--all")) {
isAll = true;
boolean isClasses = true;
boolean isInstances = true;
if (opts.nextEq("-i"))
isClasses = false;
if (opts.nextEq("-c"))
isInstances = false;
OWLObject anc = resolveEntity(g,opts.nextOpt());
System.out.println("Set1:"+anc+" "+anc.getClass());
Set<OWLObject> objs = g.queryDescendants((OWLClass)anc, isInstances, isClasses);
objs.remove(anc);
System.out.println(" Size1:"+objs.size());
Set<OWLObject> objs2 = objs;
if (opts.nextEq("--vs")) {
OWLObject anc2 = resolveEntity(g,opts.nextOpt());
System.out.println("Set2:"+anc2+" "+anc2.getClass());
objs2 = g.queryDescendants((OWLClass)anc2, isInstances, isClasses);
objs2.remove(anc2);
System.out.println(" Size2:"+objs2.size());
}
for (OWLObject a : objs) {
if (!(a instanceof OWLNamedObject)) {
continue;
}
for (OWLObject b : objs2) {
if (!(b instanceof OWLNamedObject)) {
continue;
}
if (a.equals(b))
continue;
//if (a.compareTo(b) <= 0)
// continue;
OWLObjectPair pair = new OWLObjectPair(a,b);
System.out.println("Scheduling:"+pair);
pairs.add(pair);
}
}
}
else if (opts.nextEq("-s|--subclass-of")) {
se.comparisonSuperclass = resolveEntity(g,opts);
}
else if (opts.nextEq("--no-create-reflexive")) {
nr = true;
}
else {
// not recognized - end of this block of opts
break;
//System.err.println("???"+opts.nextOpt());
}
}
if (isAll) {
// TODO
//se.calculateSimilarityAllByAll(similarityAlgorithmName, 0.0);
}
else {
pairs.add(new OWLObjectPair(resolveEntity(g,opts.nextOpt()),
resolveEntity(g,opts.nextOpt())));
}
for (OWLObjectPair pair : pairs) {
OWLObject oa = pair.getA();
OWLObject ob = pair.getB();
Similarity metric = se.getSimilarityAlgorithm(similarityAlgorithmName);
if (nr) {
((DescriptionTreeSimilarity)metric).forceReflexivePropertyCreation = false;
}
if (subSimMethod != null)
((MultiSimilarity)metric).setSubSimMethod(subSimMethod);
System.out.println("comparing: "+oa+" vs "+ob);
Similarity r = se.calculateSimilarity(metric, oa, ob);
//System.out.println(metric+" = "+r);
metric.print();
metric.report(reporter);
if (simOnt == null) {
simOnt = g.getManager().createOntology();
}
if (opts.hasOpt("--save-sim")) {
metric.addResultsToOWLOntology(simOnt);
}
}
}
else if (opts.nextEq("-o|--output")) {
opts.info("FILE", "writes source ontology -- specified as IRI, e.g. file://`pwd`/foo.owl");
pw.saveOWL(g.getSourceOntology(), opts.nextOpt());
}
else if (opts.nextEq("--save-sim")) {
opts.info("FILE", "saves similarity results as an OWL ontology. Use after --sim or --sim-all");
pw.saveOWL(simOnt, opts.nextOpt());
}
else if (opts.nextEq("--merge-sim")) {
opts.info("FILE", "merges similarity results into source OWL ontology. Use after --sim or --sim-all");
g.mergeOntology(simOnt);
}
else if (opts.nextEq("--list-axioms")) {
for (OWLAxiom a : g.getSourceOntology().getAxioms()) {
System.out.println("AX:"+a);
}
}
else if (opts.nextEq("--follow-subclass")) {
opts.info("", "follow subclass axioms (and also equivalence axioms) in graph traversal.\n"+
" default is to follow ALL. if this is specified then only explicitly specified edges followed");
if (g.getConfig().graphEdgeIncludeSet == null)
g.getConfig().graphEdgeIncludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeIncludeSet.add(new OWLQuantifiedProperty(Quantifier.SUBCLASS_OF));
}
else if (opts.nextEq("--follow-property")) {
opts.info("PROP-LABEL", "follow object properties of this type in graph traversal.\n"+
" default is to follow ALL. if this is specified then only explicitly specified edges followed");
OWLObjectProperty p = (OWLObjectProperty) resolveEntity(g, opts);
if (g.getConfig().graphEdgeIncludeSet == null)
g.getConfig().graphEdgeIncludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeIncludeSet.add(new OWLQuantifiedProperty(p, null));
}
else if (opts.nextEq("--exclude-property")) {
opts.info("PROP-LABEL", "exclude object properties of this type in graph traversal.\n"+
" default is to exclude NONE.");
OWLObjectProperty p = g.getOWLObjectProperty(opts.nextOpt());
System.out.println("Excluding "+p+" "+p.getClass());
if (g.getConfig().graphEdgeExcludeSet == null)
g.getConfig().graphEdgeExcludeSet = new HashSet<OWLQuantifiedProperty>();
g.getConfig().graphEdgeExcludeSet.add(new OWLQuantifiedProperty(p, null));
}
else if (opts.nextEq("--exclude-metaclass")) {
opts.info("METACLASS-LABEL", "exclude classes of this type in graph traversal.\n"+
" default is to follow ALL classes");
OWLClass c = (OWLClass) resolveEntity(g, opts);
g.getConfig().excludeMetaClass = c;
}
else if (opts.nextEq("--parse-tsv")) {
opts.info("[-s] FILE", "parses a tabular file to OWL axioms");
TableToAxiomConverter ttac = new TableToAxiomConverter(g);
ttac.config.axiomType = AxiomType.CLASS_ASSERTION;
while (opts.hasOpts()) {
if (opts.nextEq("-s")) {
ttac.config.isSwitchSubjectObject = true;
}
else if (opts.nextEq("-l|--label")) {
ttac.config.setPropertyToLabel();
ttac.config.axiomType = AxiomType.ANNOTATION_ASSERTION;
}
else if (opts.nextEq("-p|--prop")) {
ttac.config.property = ((OWLNamedObject) resolveEntity(g, opts)).getIRI();
}
else if (opts.nextEq("-a|--axiom-type")) {
ttac.config.setAxiomType(opts.nextOpt());
}
else if (opts.nextEq("-t|--individuals-type")) {
System.out.println("setting types");
ttac.config.individualsType = resolveClass(g, opts.nextOpt());
}
else {
// TODO - other options
}
}
String f = opts.nextOpt();
System.out.println("tabfile: "+f);
ttac.parse(f);
}
else if (opts.nextEq("--no-cache")) {
g.getConfig().isCacheClosure = false;
}
else if (opts.nextEq("--create-ontology")) {
opts.info("ONT-IRI", "creates a new OWLOntology and makes it the source ontology");
g = new OWLGraphWrapper(opts.nextOpt());
}
else if (opts.hasArgs()) {
String f = opts.nextOpt();
try {
OWLOntology ont = pw.parse(f);
if (g == null)
g = new OWLGraphWrapper(ont);
else {
System.out.println("adding support ont "+ont);
g.addSupportOntology(ont);
}
}
catch (Exception e) {
System.err.println("could not parse:"+f+" Exception:"+e);
System.exit(1);
}
//paths.add(opt);
}
else {
if (opts.helpMode)
helpFooter();
// should only reach here in help mode
}
}
/*
OWLGraphWrapper g;
if (paths.size() == 0) {
throw new Error("must specify at least one file");
}
if (paths.size() > 1) {
if (merge) {
// note: currently we can only merge obo files
pw.parseOBOFiles(paths);
}
else {
throw new Error("cannot load multiple files unless --merge is set");
}
}
else {
g = pw.parseToOWLGraph(paths.get(0));
}
*/
}
private static OWLReasoner createReasoner(OWLOntology ont, String reasonerName,
OWLOntologyManager manager) {
OWLReasonerFactory reasonerFactory = null;
if (reasonerName == null || reasonerName.equals("factpp"))
reasonerFactory = new FaCTPlusPlusReasonerFactory();
else if (reasonerName.equals("pellet"))
reasonerFactory = new PelletReasonerFactory();
else if (reasonerName.equals("hermit")) {
//return new org.semanticweb.HermiT.Reasoner.ReasonerFactory().createReasoner(ont);
//reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory();
}
else
System.out.println("no such reasoner: "+reasonerName);
OWLReasoner reasoner = reasonerFactory.createReasoner(ont);
return reasoner;
}
private static void catOntologies(OWLGraphWrapper g, Opts opts) throws OWLOntologyCreationException, IOException {
opts.info("[-r|--ref-ont ONT] [-i|--use-imports]", "Catenate ontologies taking only referenced subsets of supporting onts.\n"+
" See Mooncat docs");
Mooncat m = new Mooncat(g);
ParserWrapper pw = new ParserWrapper();
if (opts.hasOpts()) {
//String opt = opts.nextOpt();
if (opts.nextEq("-r") || opts.nextEq("--ref-ont")) {
String f = opts.nextOpt();
m.addReferencedOntology(pw.parseOWL(f));
}
else if (opts.nextEq("-s") || opts.nextEq("--src-ont")) {
m.setOntology(pw.parseOWL(opts.nextOpt()));
}
else if (opts.nextEq("-i") || opts.nextEq("--use-imports")) {
System.out.println("using everything in imports closure");
g.addSupportOntologiesFromImportsClosure();
}
else {
opts.fail();
}
}
if (m.getReferencedOntologies().size() == 0) {
m.setReferencedOntologies(g.getSupportOntologySet());
}
//g.useImportClosureForQueries();
for (OWLAxiom ax : m.getClosureAxiomsOfExternalReferencedEntities()) {
System.out.println("M_AX:"+ax);
}
m.mergeOntologies();
}
private static void showEdges(Set<OWLGraphEdge> edges) {
for (OWLGraphEdge e : edges) {
System.out.println(e);
}
}
public static void summarizeOntology(OWLOntology ont) {
System.out.println("Ontology:"+ont);
System.out.println(" Classes:"+ont.getClassesInSignature().size());
System.out.println(" Individuals:"+ont.getIndividualsInSignature().size());
System.out.println(" ObjectProperties:"+ont.getObjectPropertiesInSignature().size());
System.out.println(" AxiomCount:"+ont.getAxiomCount());
}
// todo - move to util
public static OWLObject resolveEntity(OWLGraphWrapper g, Opts opts) {
OWLObject obj = null;
String id = opts.nextOpt(); // in future we will allow resolution by name etc
return resolveEntity(g,id);
}
public static OWLObject resolveEntity(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return obj;
obj = g.getOWLObject(id);
if (obj != null)
return obj;
obj = g.getOWLObjectByIdentifier(id);
return obj;
}
public static OWLObjectProperty resolveObjectProperty(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return (OWLObjectProperty) obj;
return g.getOWLObjectProperty(id);
}
public static OWLClass resolveClass(OWLGraphWrapper g, String id) {
OWLObject obj = null;
obj = g.getOWLObjectByLabel(id);
if (obj != null)
return (OWLClass) obj;
return g.getDataFactory().getOWLClass(IRI.create(id));
}
public static void help() {
System.out.println("owltools [ONTOLOGY ...] [COMMAND ...]\n");
System.out.println("Commands/Options");
System.out.println(" (type 'owltools COMMAND -h' for more info)");
}
public static void helpFooter() {
System.out.println("\nOntologies:");
System.out.println(" These are specified as IRIs. The IRI is typically 'file:PATH' or a URL");
System.out.println("\nLabel Resolution:");
System.out.println(" you can pass in either a class label (enclosed in single quotes), an OBO ID or a IRI");
System.out.println("\nExecution:");
System.out.println(" note that commands are processed *in order*. This allows you to run mini-pipelines" +
" or programs on the command line");
System.out.println("\nExamples:");
System.out.println(" ");
}
}
|
git-svn-id: http://owltools.googlecode.com/svn/trunk@6 18f1da76-1bb4-b526-5913-e828fe20442d
| src/owltools/cli/CommandLineInterface.java | ||
Java | bsd-3-clause | 6757a0a0915d99bf65235729fafb798a42471d0c | 0 | sekiguchi-nagisa/DShell,sekiguchi-nagisa/DShell | package dshell.internal.process;
import static dshell.internal.process.TaskConfig.Behavior.background;
import static dshell.internal.process.TaskConfig.Behavior.printable;
import static dshell.internal.process.TaskConfig.Behavior.returnable;
import static dshell.internal.process.TaskConfig.Behavior.throwable;
import static dshell.internal.process.TaskConfig.RetType.IntType;
import static dshell.internal.process.TaskConfig.RetType.TaskType;
import static dshell.internal.process.TaskConfig.RetType.VoidType;
import java.util.ArrayList;
import java.util.List;
import dshell.internal.lib.RuntimeContext;
import dshell.internal.lib.Utils;
import dshell.lang.Task;
public class TaskContext {
private final List<AbstractProcessContext> procContexts;
private final TaskConfig config;
private boolean enableTrace = false;
public TaskContext(boolean isBackGround) {
this.procContexts = new ArrayList<>();
this.config = new TaskConfig().setFlag(background, isBackGround);
}
public TaskContext addContext(AbstractProcessContext context) {
this.procContexts.add(context);
if(context.hasTraced()) {
this.enableTrace = true;
}
return this;
}
public TaskContext setOutputBuffer(OutputBuffer buffer) {
this.config.setOutputBuffer(buffer);
return this;
}
public static AbstractProcessContext createProcessContext(String commandName) {
if(commandName.indexOf('/') != -1) { // qualify name
return new ProcessContext(commandName);
}
AbstractProcessContext context = RuntimeContext.getInstance().getBuiltinCommand(commandName);
if(context != null) {
return context;
}
return new ProcessContext(Utils.getCommandFromPath(commandName)); // get qualify name from path
}
private static boolean checkTraceRequirements() {
if(System.getProperty("os.name").equals("Linux")) {
ProcessContext.traceBackendType = ProcessContext.traceBackend_ltrace;
return Utils.getCommandFromPath("ltrace") != null;
}
return false;
}
private Object execTask() {
/**
* init system call trace.
*/
if(this.enableTrace) {
boolean tracable = checkTraceRequirements();
for(AbstractProcessContext context : this.procContexts) {
if(context instanceof ProcessContext) {
((ProcessContext) context).initTrace(tracable);
}
}
if(!tracable) {
System.err.println("Systemcall Trace is Not Supported");
}
}
/**
* launch task.
*/
this.procContexts.get(0).setAsFirstProc(true);
this.procContexts.get(this.procContexts.size() - 1).setAsLastProc(true);
Task task = new Task(this.procContexts, this.config);
if(this.config.is(background)) {
return (this.config.isRetType(TaskType) && this.config.is(returnable)) ? task : null;
}
task.join();
if(this.config.is(returnable)) {
if(this.config.isRetType(IntType)) {
return new Long(task.getExitStatus());
} else if(this.config.isRetType(TaskType)) {
return task;
}
}
return null;
}
// launch task.
public void execAsVoid() {
this.config.setRetType(VoidType).setFlag(printable, true).setFlag(throwable, true);
this.execTask();
}
public long execAsInt() {
this.config.setRetType(IntType).setFlag(printable, true).
setFlag(returnable, true).setFlag(background, false);
return ((Long)this.execTask()).longValue();
}
public boolean execAsBoolean() {
return this.execAsInt() == 0;
}
public Task execAsTask() {
this.config.setRetType(TaskType).
setFlag(printable, true).setFlag(returnable, true).setFlag(throwable, true);
return (Task) this.execTask();
}
}
| src/dshell/internal/process/TaskContext.java | package dshell.internal.process;
import static dshell.internal.process.TaskConfig.Behavior.background;
import static dshell.internal.process.TaskConfig.Behavior.printable;
import static dshell.internal.process.TaskConfig.Behavior.returnable;
import static dshell.internal.process.TaskConfig.Behavior.throwable;
import static dshell.internal.process.TaskConfig.RetType.IntType;
import static dshell.internal.process.TaskConfig.RetType.TaskType;
import static dshell.internal.process.TaskConfig.RetType.VoidType;
import java.util.ArrayList;
import java.util.List;
import dshell.internal.lib.RuntimeContext;
import dshell.internal.lib.Utils;
import dshell.lang.Task;
public class TaskContext {
private final List<AbstractProcessContext> procContexts;
private final TaskConfig config;
private boolean enableTrace = false;
public TaskContext(boolean isBackGround) {
this.procContexts = new ArrayList<>();
this.config = new TaskConfig().setFlag(background, isBackGround);
}
public TaskContext addContext(AbstractProcessContext context) {
this.procContexts.add(context);
if(context.hasTraced()) {
this.enableTrace = true;
}
return this;
}
public TaskContext setOutputBuffer(OutputBuffer buffer) {
this.config.setOutputBuffer(buffer);
return this;
}
public static AbstractProcessContext createProcessContext(String commandName) {
AbstractProcessContext context = RuntimeContext.getInstance().getBuiltinCommand(commandName);
return context != null ? context : new ProcessContext(commandName);
}
private static boolean checkTraceRequirements() {
if(System.getProperty("os.name").equals("Linux")) {
ProcessContext.traceBackendType = ProcessContext.traceBackend_ltrace;
return Utils.getCommandFromPath("ltrace") != null;
}
return false;
}
private Object execTask() {
/**
* init system call trace.
*/
if(this.enableTrace) {
boolean tracable = checkTraceRequirements();
for(AbstractProcessContext context : this.procContexts) {
if(context instanceof ProcessContext) {
((ProcessContext) context).initTrace(tracable);
}
}
if(!tracable) {
System.err.println("Systemcall Trace is Not Supported");
}
}
/**
* launch task.
*/
this.procContexts.get(0).setAsFirstProc(true);
this.procContexts.get(this.procContexts.size() - 1).setAsLastProc(true);
Task task = new Task(this.procContexts, this.config);
if(this.config.is(background)) {
return (this.config.isRetType(TaskType) && this.config.is(returnable)) ? task : null;
}
task.join();
if(this.config.is(returnable)) {
if(this.config.isRetType(IntType)) {
return new Long(task.getExitStatus());
} else if(this.config.isRetType(TaskType)) {
return task;
}
}
return null;
}
// launch task.
public void execAsVoid() {
this.config.setRetType(VoidType).setFlag(printable, true).setFlag(throwable, true);
this.execTask();
}
public long execAsInt() {
this.config.setRetType(IntType).setFlag(printable, true).
setFlag(returnable, true).setFlag(background, false);
return ((Long)this.execTask()).longValue();
}
public boolean execAsBoolean() {
return this.execAsInt() == 0;
}
public Task execAsTask() {
this.config.setRetType(TaskType).
setFlag(printable, true).setFlag(returnable, true).setFlag(throwable, true);
return (Task) this.execTask();
}
}
| bugfix path resolution
| src/dshell/internal/process/TaskContext.java | bugfix path resolution |
|
Java | bsd-3-clause | fbc56281757cf6cc72aba818d657903b8ef4b448 | 0 | wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy | /*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.phases.common.inlining.walker;
import com.oracle.graal.api.code.Assumptions;
import com.oracle.graal.api.code.BailoutException;
import com.oracle.graal.api.meta.JavaTypeProfile;
import com.oracle.graal.api.meta.ResolvedJavaMethod;
import com.oracle.graal.api.meta.ResolvedJavaType;
import com.oracle.graal.compiler.common.GraalInternalError;
import com.oracle.graal.compiler.common.type.ObjectStamp;
import com.oracle.graal.debug.Debug;
import com.oracle.graal.debug.DebugMetric;
import com.oracle.graal.graph.Graph;
import com.oracle.graal.graph.Node;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.java.MethodCallTargetNode;
import com.oracle.graal.phases.OptimisticOptimizations;
import com.oracle.graal.phases.common.CanonicalizerPhase;
import com.oracle.graal.phases.common.inlining.InliningUtil;
import com.oracle.graal.phases.common.inlining.info.*;
import com.oracle.graal.phases.common.inlining.policy.InliningPolicy;
import com.oracle.graal.phases.graph.FixedNodeProbabilityCache;
import com.oracle.graal.phases.tiers.HighTierContext;
import com.oracle.graal.phases.util.Providers;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleFunction;
import static com.oracle.graal.compiler.common.GraalOptions.*;
/**
* Holds the data for building the callee graphs recursively: graphs and invocations (each
* invocation can have multiple graphs).
*/
public class InliningData {
private static final CallsiteHolder DUMMY_CALLSITE_HOLDER = new CallsiteHolder(null, 1.0, 1.0);
// Metrics
private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed");
private static final DebugMetric metricInliningRuns = Debug.metric("InliningRuns");
private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered");
/**
* Call hierarchy from outer most call (i.e., compilation unit) to inner most callee.
*/
private final ArrayDeque<CallsiteHolder> graphQueue = new ArrayDeque<>();
private final ArrayDeque<MethodInvocation> invocationQueue = new ArrayDeque<>();
private final ToDoubleFunction<FixedNode> probabilities = new FixedNodeProbabilityCache();
private final HighTierContext context;
private final int maxMethodPerInlining;
private final CanonicalizerPhase canonicalizer;
private final InliningPolicy inliningPolicy;
private int maxGraphs;
public InliningData(StructuredGraph rootGraph, HighTierContext context, int maxMethodPerInlining, CanonicalizerPhase canonicalizer, InliningPolicy inliningPolicy) {
assert rootGraph != null;
this.context = context;
this.maxMethodPerInlining = maxMethodPerInlining;
this.canonicalizer = canonicalizer;
this.inliningPolicy = inliningPolicy;
this.maxGraphs = 1;
Assumptions rootAssumptions = context.getAssumptions();
invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0));
pushGraph(rootGraph, 1.0, 1.0);
}
private boolean checkTargetConditions(Invoke invoke, ResolvedJavaMethod method, OptimisticOptimizations optimisticOpts) {
String failureMessage = null;
if (method == null) {
failureMessage = "the method is not resolved";
} else if (method.isNative() && (!Intrinsify.getValue() || !InliningUtil.canIntrinsify(context.getReplacements(), method))) {
failureMessage = "it is a non-intrinsic native method";
} else if (method.isAbstract()) {
failureMessage = "it is an abstract method";
} else if (!method.getDeclaringClass().isInitialized()) {
failureMessage = "the method's class is not initialized";
} else if (!method.canBeInlined()) {
failureMessage = "it is marked non-inlinable";
} else if (countRecursiveInlining(method) > MaximumRecursiveInlining.getValue()) {
failureMessage = "it exceeds the maximum recursive inlining depth";
} else if (new OptimisticOptimizations(method.getProfilingInfo()).lessOptimisticThan(optimisticOpts)) {
failureMessage = "the callee uses less optimistic optimizations than caller";
}
if (failureMessage == null) {
return true;
} else {
InliningUtil.logNotInlined(invoke, inliningDepth(), method, failureMessage);
return false;
}
}
/**
* Determines if inlining is possible at the given invoke node.
*
* @param invoke the invoke that should be inlined
* @return an instance of InlineInfo, or null if no inlining is possible at the given invoke
*/
private InlineInfo getInlineInfo(Invoke invoke, Assumptions assumptions) {
final String failureMessage = InliningUtil.checkInvokeConditions(invoke);
if (failureMessage != null) {
InliningUtil.logNotInlinedMethod(invoke, failureMessage);
return null;
}
MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget();
ResolvedJavaMethod targetMethod = callTarget.targetMethod();
if (callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Special || targetMethod.canBeStaticallyBound()) {
return getExactInlineInfo(invoke, targetMethod);
}
assert callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Virtual || callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Interface;
ResolvedJavaType holder = targetMethod.getDeclaringClass();
if (!(callTarget.receiver().stamp() instanceof ObjectStamp)) {
return null;
}
ObjectStamp receiverStamp = (ObjectStamp) callTarget.receiver().stamp();
if (receiverStamp.alwaysNull()) {
// Don't inline if receiver is known to be null
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
if (receiverStamp.type() != null) {
// the invoke target might be more specific than the holder (happens after inlining:
// parameters lose their declared type...)
ResolvedJavaType receiverType = receiverStamp.type();
if (receiverType != null && holder.isAssignableFrom(receiverType)) {
holder = receiverType;
if (receiverStamp.isExactType()) {
assert targetMethod.getDeclaringClass().isAssignableFrom(holder) : holder + " subtype of " + targetMethod.getDeclaringClass() + " for " + targetMethod;
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, resolvedMethod);
}
}
}
}
if (holder.isArray()) {
// arrays can be treated as Objects
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, resolvedMethod);
}
}
if (assumptions.useOptimisticAssumptions()) {
ResolvedJavaType uniqueSubtype = holder.findUniqueConcreteSubtype();
if (uniqueSubtype != null) {
ResolvedJavaMethod resolvedMethod = uniqueSubtype.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getAssumptionInlineInfo(invoke, resolvedMethod, new Assumptions.ConcreteSubtype(holder, uniqueSubtype));
}
}
ResolvedJavaMethod concrete = holder.findUniqueConcreteMethod(targetMethod);
if (concrete != null) {
return getAssumptionInlineInfo(invoke, concrete, new Assumptions.ConcreteMethod(targetMethod, holder, concrete));
}
}
// type check based inlining
return getTypeCheckedInlineInfo(invoke, targetMethod);
}
private InlineInfo getTypeCheckedInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) {
JavaTypeProfile typeProfile;
ValueNode receiver = invoke.callTarget().arguments().get(0);
if (receiver instanceof TypeProfileProxyNode) {
TypeProfileProxyNode typeProfileProxyNode = (TypeProfileProxyNode) receiver;
typeProfile = typeProfileProxyNode.getProfile();
} else {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no type profile exists");
return null;
}
JavaTypeProfile.ProfiledType[] ptypes = typeProfile.getTypes();
if (ptypes == null || ptypes.length <= 0) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no types in profile");
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
double notRecordedTypeProbability = typeProfile.getNotRecordedProbability();
final OptimisticOptimizations optimisticOpts = context.getOptimisticOptimizations();
if (ptypes.length == 1 && notRecordedTypeProbability == 0) {
if (!optimisticOpts.inlineMonomorphicCalls()) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "inlining monomorphic calls is disabled");
return null;
}
ResolvedJavaType type = ptypes[0].getType();
assert type.isArray() || !type.isAbstract();
ResolvedJavaMethod concrete = type.resolveMethod(targetMethod, contextType);
if (!checkTargetConditions(invoke, concrete, optimisticOpts)) {
return null;
}
return new TypeGuardInlineInfo(invoke, concrete, type);
} else {
invoke.setPolymorphic(true);
if (!optimisticOpts.inlinePolymorphicCalls() && notRecordedTypeProbability == 0) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining polymorphic calls is disabled (%d types)", ptypes.length);
return null;
}
if (!optimisticOpts.inlineMegamorphicCalls() && notRecordedTypeProbability > 0) {
// due to filtering impossible types, notRecordedTypeProbability can be > 0 although
// the number of types is lower than what can be recorded in a type profile
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining megamorphic calls is disabled (%d types, %f %% not recorded types)", ptypes.length,
notRecordedTypeProbability * 100);
return null;
}
// Find unique methods and their probabilities.
ArrayList<ResolvedJavaMethod> concreteMethods = new ArrayList<>();
ArrayList<Double> concreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < ptypes.length; i++) {
ResolvedJavaMethod concrete = ptypes[i].getType().resolveMethod(targetMethod, contextType);
if (concrete == null) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "could not resolve method");
return null;
}
int index = concreteMethods.indexOf(concrete);
double curProbability = ptypes[i].getProbability();
if (index < 0) {
index = concreteMethods.size();
concreteMethods.add(concrete);
concreteMethodsProbabilities.add(curProbability);
} else {
concreteMethodsProbabilities.set(index, concreteMethodsProbabilities.get(index) + curProbability);
}
}
if (concreteMethods.size() > maxMethodPerInlining) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "polymorphic call with more than %d target methods", maxMethodPerInlining);
return null;
}
// Clear methods that fall below the threshold.
if (notRecordedTypeProbability > 0) {
ArrayList<ResolvedJavaMethod> newConcreteMethods = new ArrayList<>();
ArrayList<Double> newConcreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < concreteMethods.size(); ++i) {
if (concreteMethodsProbabilities.get(i) >= MegamorphicInliningMinMethodProbability.getValue()) {
newConcreteMethods.add(concreteMethods.get(i));
newConcreteMethodsProbabilities.add(concreteMethodsProbabilities.get(i));
}
}
if (newConcreteMethods.size() == 0) {
// No method left that is worth inlining.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no methods remaining after filtering less frequent methods (%d methods previously)",
concreteMethods.size());
return null;
}
concreteMethods = newConcreteMethods;
concreteMethodsProbabilities = newConcreteMethodsProbabilities;
}
// Clean out types whose methods are no longer available.
ArrayList<JavaTypeProfile.ProfiledType> usedTypes = new ArrayList<>();
ArrayList<Integer> typesToConcretes = new ArrayList<>();
for (JavaTypeProfile.ProfiledType type : ptypes) {
ResolvedJavaMethod concrete = type.getType().resolveMethod(targetMethod, contextType);
int index = concreteMethods.indexOf(concrete);
if (index == -1) {
notRecordedTypeProbability += type.getProbability();
} else {
assert type.getType().isArray() || !type.getType().isAbstract() : type + " " + concrete;
usedTypes.add(type);
typesToConcretes.add(index);
}
}
if (usedTypes.size() == 0) {
// No type left that is worth checking for.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no types remaining after filtering less frequent types (%d types previously)", ptypes.length);
return null;
}
for (ResolvedJavaMethod concrete : concreteMethods) {
if (!checkTargetConditions(invoke, concrete, optimisticOpts)) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "it is a polymorphic method call and at least one invoked method cannot be inlined");
return null;
}
}
return new MultiTypeGuardInlineInfo(invoke, concreteMethods, concreteMethodsProbabilities, usedTypes, typesToConcretes, notRecordedTypeProbability);
}
}
private InlineInfo getAssumptionInlineInfo(Invoke invoke, ResolvedJavaMethod concrete, Assumptions.Assumption takenAssumption) {
assert !concrete.isAbstract();
if (!checkTargetConditions(invoke, concrete, context.getOptimisticOptimizations())) {
return null;
}
return new AssumptionInlineInfo(invoke, concrete, takenAssumption);
}
private InlineInfo getExactInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) {
assert !targetMethod.isAbstract();
if (!checkTargetConditions(invoke, targetMethod, context.getOptimisticOptimizations())) {
return null;
}
return new ExactInlineInfo(invoke, targetMethod);
}
private void doInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, Assumptions callerAssumptions) {
StructuredGraph callerGraph = callerCallsiteHolder.graph();
Graph.Mark markBeforeInlining = callerGraph.getMark();
InlineInfo callee = calleeInfo.callee();
try {
try (Debug.Scope scope = Debug.scope("doInline", callerGraph)) {
List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot();
callee.inline(new Providers(context), callerAssumptions);
callerAssumptions.record(calleeInfo.assumptions());
metricInliningRuns.increment();
Debug.dump(callerGraph, "after %s", callee);
if (OptCanonicalizer.getValue()) {
Graph.Mark markBeforeCanonicalization = callerGraph.getMark();
canonicalizer.applyIncremental(callerGraph, context, invokeUsages, markBeforeInlining);
// process invokes that are possibly created during canonicalization
for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) {
if (newNode instanceof Invoke) {
callerCallsiteHolder.pushInvoke((Invoke) newNode);
}
}
}
callerCallsiteHolder.computeProbabilities();
metricInliningPerformed.increment();
}
} catch (BailoutException bailout) {
throw bailout;
} catch (AssertionError | RuntimeException e) {
throw new GraalInternalError(e).addContext(callee.toString());
} catch (GraalInternalError e) {
throw e.addContext(callee.toString());
}
}
/**
* @return true iff inlining was actually performed
*/
private boolean tryToInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, MethodInvocation parentInvocation, int inliningDepth) {
InlineInfo callee = calleeInfo.callee();
Assumptions callerAssumptions = parentInvocation.assumptions();
metricInliningConsidered.increment();
if (inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), callee, inliningDepth, calleeInfo.probability(), calleeInfo.relevance(), true)) {
doInline(callerCallsiteHolder, calleeInfo, callerAssumptions);
return true;
}
if (context.getOptimisticOptimizations().devirtualizeInvokes()) {
callee.tryToDevirtualizeInvoke(context.getMetaAccess(), callerAssumptions);
}
return false;
}
/**
* Process the next invoke and enqueue all its graphs for processing.
*/
private void processNextInvoke() {
CallsiteHolder callsiteHolder = currentGraph();
Invoke invoke = callsiteHolder.popInvoke();
MethodInvocation callerInvocation = currentInvocation();
Assumptions parentAssumptions = callerInvocation.assumptions();
InlineInfo info = getInlineInfo(invoke, parentAssumptions);
if (info != null) {
double invokeProbability = callsiteHolder.invokeProbability(invoke);
double invokeRelevance = callsiteHolder.invokeRelevance(invoke);
MethodInvocation calleeInvocation = pushInvocation(info, parentAssumptions, invokeProbability, invokeRelevance);
for (int i = 0; i < info.numberOfMethods(); i++) {
InliningUtil.Inlineable elem = DepthSearchUtil.getInlineableElement(info.methodAt(i), info.invoke(), context.replaceAssumptions(calleeInvocation.assumptions()), canonicalizer);
info.setInlinableElement(i, elem);
if (elem instanceof InliningUtil.InlineableGraph) {
pushGraph(((InliningUtil.InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i));
} else {
assert elem instanceof InliningUtil.InlineableMacroNode;
pushDummyGraph();
}
}
}
}
public int graphCount() {
return graphQueue.size();
}
private void pushGraph(StructuredGraph graph, double probability, double relevance) {
assert graph != null;
assert !contains(graph);
graphQueue.push(new CallsiteHolder(graph, probability, relevance));
assert graphQueue.size() <= maxGraphs;
}
private void pushDummyGraph() {
graphQueue.push(DUMMY_CALLSITE_HOLDER);
}
public boolean hasUnprocessedGraphs() {
return !graphQueue.isEmpty();
}
private CallsiteHolder currentGraph() {
return graphQueue.peek();
}
private void popGraph() {
graphQueue.pop();
assert graphQueue.size() <= maxGraphs;
}
private void popGraphs(int count) {
assert count >= 0;
for (int i = 0; i < count; i++) {
graphQueue.pop();
}
}
private static final Object[] NO_CONTEXT = {};
/**
* Gets the call hierarchy of this inlining from outer most call to inner most callee.
*/
private Object[] inliningContext() {
if (!Debug.isDumpEnabled()) {
return NO_CONTEXT;
}
Object[] result = new Object[graphQueue.size()];
int i = 0;
for (CallsiteHolder g : graphQueue) {
result[i++] = g.method();
}
return result;
}
private MethodInvocation currentInvocation() {
return invocationQueue.peekFirst();
}
private MethodInvocation pushInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
MethodInvocation methodInvocation = new MethodInvocation(info, new Assumptions(assumptions.useOptimisticAssumptions()), probability, relevance);
invocationQueue.addFirst(methodInvocation);
maxGraphs += info.numberOfMethods();
assert graphQueue.size() <= maxGraphs;
return methodInvocation;
}
private void popInvocation() {
maxGraphs -= invocationQueue.peekFirst().callee().numberOfMethods();
assert graphQueue.size() <= maxGraphs;
invocationQueue.removeFirst();
}
public int countRecursiveInlining(ResolvedJavaMethod method) {
int count = 0;
for (CallsiteHolder callsiteHolder : graphQueue) {
if (method.equals(callsiteHolder.method())) {
count++;
}
}
return count;
}
public int inliningDepth() {
assert invocationQueue.size() > 0;
return invocationQueue.size() - 1;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("Invocations: ");
for (MethodInvocation invocation : invocationQueue) {
if (invocation.callee() != null) {
result.append(invocation.callee().numberOfMethods());
result.append("x ");
result.append(invocation.callee().invoke());
result.append("; ");
}
}
result.append("\nGraphs: ");
for (CallsiteHolder graph : graphQueue) {
result.append(graph.graph());
result.append("; ");
}
return result.toString();
}
private boolean contains(StructuredGraph graph) {
for (CallsiteHolder info : graphQueue) {
if (info.graph() == graph) {
return true;
}
}
return false;
}
/**
* @return true iff inlining was actually performed
*/
public boolean moveForward() {
final MethodInvocation currentInvocation = currentInvocation();
final boolean backtrack = (!currentInvocation.isRoot() && !inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), currentInvocation.callee(), inliningDepth(),
currentInvocation.probability(), currentInvocation.relevance(), false));
if (backtrack) {
int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs();
assert remainingGraphs > 0;
popGraphs(remainingGraphs);
popInvocation();
return false;
}
final boolean delve = currentGraph().hasRemainingInvokes() && inliningPolicy.continueInlining(currentGraph().graph());
if (delve) {
processNextInvoke();
return false;
}
popGraph();
if (currentInvocation.isRoot()) {
return false;
}
// try to inline
assert currentInvocation.callee().invoke().asNode().isAlive();
currentInvocation.incrementProcessedGraphs();
if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) {
popInvocation();
final MethodInvocation parentInvoke = currentInvocation();
try (Debug.Scope s = Debug.scope("Inlining", inliningContext())) {
return tryToInline(currentGraph(), currentInvocation, parentInvoke, inliningDepth() + 1);
} catch (Throwable e) {
throw Debug.handle(e);
}
}
return false;
}
}
| graal/com.oracle.graal.phases.common/src/com/oracle/graal/phases/common/inlining/walker/InliningData.java | /*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.phases.common.inlining.walker;
import com.oracle.graal.api.code.Assumptions;
import com.oracle.graal.api.code.BailoutException;
import com.oracle.graal.api.meta.JavaTypeProfile;
import com.oracle.graal.api.meta.ResolvedJavaMethod;
import com.oracle.graal.api.meta.ResolvedJavaType;
import com.oracle.graal.compiler.common.GraalInternalError;
import com.oracle.graal.compiler.common.type.ObjectStamp;
import com.oracle.graal.debug.Debug;
import com.oracle.graal.debug.DebugMetric;
import com.oracle.graal.graph.Graph;
import com.oracle.graal.graph.Node;
import com.oracle.graal.nodes.*;
import com.oracle.graal.nodes.java.MethodCallTargetNode;
import com.oracle.graal.nodes.spi.Replacements;
import com.oracle.graal.phases.OptimisticOptimizations;
import com.oracle.graal.phases.common.CanonicalizerPhase;
import com.oracle.graal.phases.common.inlining.InliningUtil;
import com.oracle.graal.phases.common.inlining.info.*;
import com.oracle.graal.phases.common.inlining.policy.InliningPolicy;
import com.oracle.graal.phases.graph.FixedNodeProbabilityCache;
import com.oracle.graal.phases.tiers.HighTierContext;
import com.oracle.graal.phases.util.Providers;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToDoubleFunction;
import static com.oracle.graal.compiler.common.GraalOptions.*;
/**
* Holds the data for building the callee graphs recursively: graphs and invocations (each
* invocation can have multiple graphs).
*/
public class InliningData {
private static final CallsiteHolder DUMMY_CALLSITE_HOLDER = new CallsiteHolder(null, 1.0, 1.0);
// Metrics
private static final DebugMetric metricInliningPerformed = Debug.metric("InliningPerformed");
private static final DebugMetric metricInliningRuns = Debug.metric("InliningRuns");
private static final DebugMetric metricInliningConsidered = Debug.metric("InliningConsidered");
/**
* Call hierarchy from outer most call (i.e., compilation unit) to inner most callee.
*/
private final ArrayDeque<CallsiteHolder> graphQueue = new ArrayDeque<>();
private final ArrayDeque<MethodInvocation> invocationQueue = new ArrayDeque<>();
private final ToDoubleFunction<FixedNode> probabilities = new FixedNodeProbabilityCache();
private final HighTierContext context;
private final int maxMethodPerInlining;
private final CanonicalizerPhase canonicalizer;
private final InliningPolicy inliningPolicy;
private int maxGraphs;
public InliningData(StructuredGraph rootGraph, HighTierContext context, int maxMethodPerInlining, CanonicalizerPhase canonicalizer, InliningPolicy inliningPolicy) {
assert rootGraph != null;
this.context = context;
this.maxMethodPerInlining = maxMethodPerInlining;
this.canonicalizer = canonicalizer;
this.inliningPolicy = inliningPolicy;
this.maxGraphs = 1;
Assumptions rootAssumptions = context.getAssumptions();
invocationQueue.push(new MethodInvocation(null, rootAssumptions, 1.0, 1.0));
pushGraph(rootGraph, 1.0, 1.0);
}
private boolean checkTargetConditions(Replacements replacements, Invoke invoke, ResolvedJavaMethod method, OptimisticOptimizations optimisticOpts) {
String failureMessage = null;
if (method == null) {
failureMessage = "the method is not resolved";
} else if (method.isNative() && (!Intrinsify.getValue() || !InliningUtil.canIntrinsify(replacements, method))) {
failureMessage = "it is a non-intrinsic native method";
} else if (method.isAbstract()) {
failureMessage = "it is an abstract method";
} else if (!method.getDeclaringClass().isInitialized()) {
failureMessage = "the method's class is not initialized";
} else if (!method.canBeInlined()) {
failureMessage = "it is marked non-inlinable";
} else if (countRecursiveInlining(method) > MaximumRecursiveInlining.getValue()) {
failureMessage = "it exceeds the maximum recursive inlining depth";
} else if (new OptimisticOptimizations(method.getProfilingInfo()).lessOptimisticThan(optimisticOpts)) {
failureMessage = "the callee uses less optimistic optimizations than caller";
}
if (failureMessage == null) {
return true;
} else {
InliningUtil.logNotInlined(invoke, inliningDepth(), method, failureMessage);
return false;
}
}
/**
* Determines if inlining is possible at the given invoke node.
*
* @param invoke the invoke that should be inlined
* @return an instance of InlineInfo, or null if no inlining is possible at the given invoke
*/
private InlineInfo getInlineInfo(Invoke invoke, Assumptions assumptions) {
final String failureMessage = InliningUtil.checkInvokeConditions(invoke);
if (failureMessage != null) {
InliningUtil.logNotInlinedMethod(invoke, failureMessage);
return null;
}
MethodCallTargetNode callTarget = (MethodCallTargetNode) invoke.callTarget();
ResolvedJavaMethod targetMethod = callTarget.targetMethod();
if (callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Special || targetMethod.canBeStaticallyBound()) {
return getExactInlineInfo(invoke, targetMethod);
}
assert callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Virtual || callTarget.invokeKind() == MethodCallTargetNode.InvokeKind.Interface;
ResolvedJavaType holder = targetMethod.getDeclaringClass();
if (!(callTarget.receiver().stamp() instanceof ObjectStamp)) {
return null;
}
ObjectStamp receiverStamp = (ObjectStamp) callTarget.receiver().stamp();
if (receiverStamp.alwaysNull()) {
// Don't inline if receiver is known to be null
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
if (receiverStamp.type() != null) {
// the invoke target might be more specific than the holder (happens after inlining:
// parameters lose their declared type...)
ResolvedJavaType receiverType = receiverStamp.type();
if (receiverType != null && holder.isAssignableFrom(receiverType)) {
holder = receiverType;
if (receiverStamp.isExactType()) {
assert targetMethod.getDeclaringClass().isAssignableFrom(holder) : holder + " subtype of " + targetMethod.getDeclaringClass() + " for " + targetMethod;
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, resolvedMethod);
}
}
}
}
if (holder.isArray()) {
// arrays can be treated as Objects
ResolvedJavaMethod resolvedMethod = holder.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getExactInlineInfo(invoke, resolvedMethod);
}
}
if (assumptions.useOptimisticAssumptions()) {
ResolvedJavaType uniqueSubtype = holder.findUniqueConcreteSubtype();
if (uniqueSubtype != null) {
ResolvedJavaMethod resolvedMethod = uniqueSubtype.resolveMethod(targetMethod, contextType);
if (resolvedMethod != null) {
return getAssumptionInlineInfo(invoke, resolvedMethod, new Assumptions.ConcreteSubtype(holder, uniqueSubtype));
}
}
ResolvedJavaMethod concrete = holder.findUniqueConcreteMethod(targetMethod);
if (concrete != null) {
return getAssumptionInlineInfo(invoke, concrete, new Assumptions.ConcreteMethod(targetMethod, holder, concrete));
}
}
// type check based inlining
return getTypeCheckedInlineInfo(invoke, targetMethod);
}
private InlineInfo getTypeCheckedInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) {
JavaTypeProfile typeProfile;
ValueNode receiver = invoke.callTarget().arguments().get(0);
if (receiver instanceof TypeProfileProxyNode) {
TypeProfileProxyNode typeProfileProxyNode = (TypeProfileProxyNode) receiver;
typeProfile = typeProfileProxyNode.getProfile();
} else {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no type profile exists");
return null;
}
JavaTypeProfile.ProfiledType[] ptypes = typeProfile.getTypes();
if (ptypes == null || ptypes.length <= 0) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "no types in profile");
return null;
}
ResolvedJavaType contextType = invoke.getContextType();
double notRecordedTypeProbability = typeProfile.getNotRecordedProbability();
final OptimisticOptimizations optimisticOpts = context.getOptimisticOptimizations();
if (ptypes.length == 1 && notRecordedTypeProbability == 0) {
if (!optimisticOpts.inlineMonomorphicCalls()) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "inlining monomorphic calls is disabled");
return null;
}
ResolvedJavaType type = ptypes[0].getType();
assert type.isArray() || !type.isAbstract();
ResolvedJavaMethod concrete = type.resolveMethod(targetMethod, contextType);
if (!checkTargetConditions(context.getReplacements(), invoke, concrete, optimisticOpts)) {
return null;
}
return new TypeGuardInlineInfo(invoke, concrete, type);
} else {
invoke.setPolymorphic(true);
if (!optimisticOpts.inlinePolymorphicCalls() && notRecordedTypeProbability == 0) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining polymorphic calls is disabled (%d types)", ptypes.length);
return null;
}
if (!optimisticOpts.inlineMegamorphicCalls() && notRecordedTypeProbability > 0) {
// due to filtering impossible types, notRecordedTypeProbability can be > 0 although
// the number of types is lower than what can be recorded in a type profile
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "inlining megamorphic calls is disabled (%d types, %f %% not recorded types)", ptypes.length,
notRecordedTypeProbability * 100);
return null;
}
// Find unique methods and their probabilities.
ArrayList<ResolvedJavaMethod> concreteMethods = new ArrayList<>();
ArrayList<Double> concreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < ptypes.length; i++) {
ResolvedJavaMethod concrete = ptypes[i].getType().resolveMethod(targetMethod, contextType);
if (concrete == null) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "could not resolve method");
return null;
}
int index = concreteMethods.indexOf(concrete);
double curProbability = ptypes[i].getProbability();
if (index < 0) {
index = concreteMethods.size();
concreteMethods.add(concrete);
concreteMethodsProbabilities.add(curProbability);
} else {
concreteMethodsProbabilities.set(index, concreteMethodsProbabilities.get(index) + curProbability);
}
}
if (concreteMethods.size() > maxMethodPerInlining) {
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "polymorphic call with more than %d target methods", maxMethodPerInlining);
return null;
}
// Clear methods that fall below the threshold.
if (notRecordedTypeProbability > 0) {
ArrayList<ResolvedJavaMethod> newConcreteMethods = new ArrayList<>();
ArrayList<Double> newConcreteMethodsProbabilities = new ArrayList<>();
for (int i = 0; i < concreteMethods.size(); ++i) {
if (concreteMethodsProbabilities.get(i) >= MegamorphicInliningMinMethodProbability.getValue()) {
newConcreteMethods.add(concreteMethods.get(i));
newConcreteMethodsProbabilities.add(concreteMethodsProbabilities.get(i));
}
}
if (newConcreteMethods.size() == 0) {
// No method left that is worth inlining.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no methods remaining after filtering less frequent methods (%d methods previously)",
concreteMethods.size());
return null;
}
concreteMethods = newConcreteMethods;
concreteMethodsProbabilities = newConcreteMethodsProbabilities;
}
// Clean out types whose methods are no longer available.
ArrayList<JavaTypeProfile.ProfiledType> usedTypes = new ArrayList<>();
ArrayList<Integer> typesToConcretes = new ArrayList<>();
for (JavaTypeProfile.ProfiledType type : ptypes) {
ResolvedJavaMethod concrete = type.getType().resolveMethod(targetMethod, contextType);
int index = concreteMethods.indexOf(concrete);
if (index == -1) {
notRecordedTypeProbability += type.getProbability();
} else {
assert type.getType().isArray() || !type.getType().isAbstract() : type + " " + concrete;
usedTypes.add(type);
typesToConcretes.add(index);
}
}
if (usedTypes.size() == 0) {
// No type left that is worth checking for.
InliningUtil.logNotInlinedInvoke(invoke, inliningDepth(), targetMethod, "no types remaining after filtering less frequent types (%d types previously)", ptypes.length);
return null;
}
for (ResolvedJavaMethod concrete : concreteMethods) {
if (!checkTargetConditions(context.getReplacements(), invoke, concrete, optimisticOpts)) {
InliningUtil.logNotInlined(invoke, inliningDepth(), targetMethod, "it is a polymorphic method call and at least one invoked method cannot be inlined");
return null;
}
}
return new MultiTypeGuardInlineInfo(invoke, concreteMethods, concreteMethodsProbabilities, usedTypes, typesToConcretes, notRecordedTypeProbability);
}
}
private InlineInfo getAssumptionInlineInfo(Invoke invoke, ResolvedJavaMethod concrete, Assumptions.Assumption takenAssumption) {
assert !concrete.isAbstract();
if (!checkTargetConditions(context.getReplacements(), invoke, concrete, context.getOptimisticOptimizations())) {
return null;
}
return new AssumptionInlineInfo(invoke, concrete, takenAssumption);
}
private InlineInfo getExactInlineInfo(Invoke invoke, ResolvedJavaMethod targetMethod) {
assert !targetMethod.isAbstract();
if (!checkTargetConditions(context.getReplacements(), invoke, targetMethod, context.getOptimisticOptimizations())) {
return null;
}
return new ExactInlineInfo(invoke, targetMethod);
}
private void doInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, Assumptions callerAssumptions) {
StructuredGraph callerGraph = callerCallsiteHolder.graph();
Graph.Mark markBeforeInlining = callerGraph.getMark();
InlineInfo callee = calleeInfo.callee();
try {
try (Debug.Scope scope = Debug.scope("doInline", callerGraph)) {
List<Node> invokeUsages = callee.invoke().asNode().usages().snapshot();
callee.inline(new Providers(context), callerAssumptions);
callerAssumptions.record(calleeInfo.assumptions());
metricInliningRuns.increment();
Debug.dump(callerGraph, "after %s", callee);
if (OptCanonicalizer.getValue()) {
Graph.Mark markBeforeCanonicalization = callerGraph.getMark();
canonicalizer.applyIncremental(callerGraph, context, invokeUsages, markBeforeInlining);
// process invokes that are possibly created during canonicalization
for (Node newNode : callerGraph.getNewNodes(markBeforeCanonicalization)) {
if (newNode instanceof Invoke) {
callerCallsiteHolder.pushInvoke((Invoke) newNode);
}
}
}
callerCallsiteHolder.computeProbabilities();
metricInliningPerformed.increment();
}
} catch (BailoutException bailout) {
throw bailout;
} catch (AssertionError | RuntimeException e) {
throw new GraalInternalError(e).addContext(callee.toString());
} catch (GraalInternalError e) {
throw e.addContext(callee.toString());
}
}
/**
* @return true iff inlining was actually performed
*/
private boolean tryToInline(CallsiteHolder callerCallsiteHolder, MethodInvocation calleeInfo, MethodInvocation parentInvocation, int inliningDepth) {
InlineInfo callee = calleeInfo.callee();
Assumptions callerAssumptions = parentInvocation.assumptions();
metricInliningConsidered.increment();
if (inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), callee, inliningDepth, calleeInfo.probability(), calleeInfo.relevance(), true)) {
doInline(callerCallsiteHolder, calleeInfo, callerAssumptions);
return true;
}
if (context.getOptimisticOptimizations().devirtualizeInvokes()) {
callee.tryToDevirtualizeInvoke(context.getMetaAccess(), callerAssumptions);
}
return false;
}
/**
* Process the next invoke and enqueue all its graphs for processing.
*/
private void processNextInvoke() {
CallsiteHolder callsiteHolder = currentGraph();
Invoke invoke = callsiteHolder.popInvoke();
MethodInvocation callerInvocation = currentInvocation();
Assumptions parentAssumptions = callerInvocation.assumptions();
InlineInfo info = getInlineInfo(invoke, parentAssumptions);
if (info != null) {
double invokeProbability = callsiteHolder.invokeProbability(invoke);
double invokeRelevance = callsiteHolder.invokeRelevance(invoke);
MethodInvocation calleeInvocation = pushInvocation(info, parentAssumptions, invokeProbability, invokeRelevance);
for (int i = 0; i < info.numberOfMethods(); i++) {
InliningUtil.Inlineable elem = DepthSearchUtil.getInlineableElement(info.methodAt(i), info.invoke(), context.replaceAssumptions(calleeInvocation.assumptions()), canonicalizer);
info.setInlinableElement(i, elem);
if (elem instanceof InliningUtil.InlineableGraph) {
pushGraph(((InliningUtil.InlineableGraph) elem).getGraph(), invokeProbability * info.probabilityAt(i), invokeRelevance * info.relevanceAt(i));
} else {
assert elem instanceof InliningUtil.InlineableMacroNode;
pushDummyGraph();
}
}
}
}
public int graphCount() {
return graphQueue.size();
}
private void pushGraph(StructuredGraph graph, double probability, double relevance) {
assert graph != null;
assert !contains(graph);
graphQueue.push(new CallsiteHolder(graph, probability, relevance));
assert graphQueue.size() <= maxGraphs;
}
private void pushDummyGraph() {
graphQueue.push(DUMMY_CALLSITE_HOLDER);
}
public boolean hasUnprocessedGraphs() {
return !graphQueue.isEmpty();
}
private CallsiteHolder currentGraph() {
return graphQueue.peek();
}
private void popGraph() {
graphQueue.pop();
assert graphQueue.size() <= maxGraphs;
}
private void popGraphs(int count) {
assert count >= 0;
for (int i = 0; i < count; i++) {
graphQueue.pop();
}
}
private static final Object[] NO_CONTEXT = {};
/**
* Gets the call hierarchy of this inlining from outer most call to inner most callee.
*/
private Object[] inliningContext() {
if (!Debug.isDumpEnabled()) {
return NO_CONTEXT;
}
Object[] result = new Object[graphQueue.size()];
int i = 0;
for (CallsiteHolder g : graphQueue) {
result[i++] = g.method();
}
return result;
}
private MethodInvocation currentInvocation() {
return invocationQueue.peekFirst();
}
private MethodInvocation pushInvocation(InlineInfo info, Assumptions assumptions, double probability, double relevance) {
MethodInvocation methodInvocation = new MethodInvocation(info, new Assumptions(assumptions.useOptimisticAssumptions()), probability, relevance);
invocationQueue.addFirst(methodInvocation);
maxGraphs += info.numberOfMethods();
assert graphQueue.size() <= maxGraphs;
return methodInvocation;
}
private void popInvocation() {
maxGraphs -= invocationQueue.peekFirst().callee().numberOfMethods();
assert graphQueue.size() <= maxGraphs;
invocationQueue.removeFirst();
}
public int countRecursiveInlining(ResolvedJavaMethod method) {
int count = 0;
for (CallsiteHolder callsiteHolder : graphQueue) {
if (method.equals(callsiteHolder.method())) {
count++;
}
}
return count;
}
public int inliningDepth() {
assert invocationQueue.size() > 0;
return invocationQueue.size() - 1;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("Invocations: ");
for (MethodInvocation invocation : invocationQueue) {
if (invocation.callee() != null) {
result.append(invocation.callee().numberOfMethods());
result.append("x ");
result.append(invocation.callee().invoke());
result.append("; ");
}
}
result.append("\nGraphs: ");
for (CallsiteHolder graph : graphQueue) {
result.append(graph.graph());
result.append("; ");
}
return result.toString();
}
private boolean contains(StructuredGraph graph) {
for (CallsiteHolder info : graphQueue) {
if (info.graph() == graph) {
return true;
}
}
return false;
}
/**
* @return true iff inlining was actually performed
*/
public boolean moveForward() {
final MethodInvocation currentInvocation = currentInvocation();
final boolean backtrack = (!currentInvocation.isRoot() && !inliningPolicy.isWorthInlining(probabilities, context.getReplacements(), currentInvocation.callee(), inliningDepth(),
currentInvocation.probability(), currentInvocation.relevance(), false));
if (backtrack) {
int remainingGraphs = currentInvocation.totalGraphs() - currentInvocation.processedGraphs();
assert remainingGraphs > 0;
popGraphs(remainingGraphs);
popInvocation();
return false;
}
final boolean delve = currentGraph().hasRemainingInvokes() && inliningPolicy.continueInlining(currentGraph().graph());
if (delve) {
processNextInvoke();
return false;
}
popGraph();
if (currentInvocation.isRoot()) {
return false;
}
// try to inline
assert currentInvocation.callee().invoke().asNode().isAlive();
currentInvocation.incrementProcessedGraphs();
if (currentInvocation.processedGraphs() == currentInvocation.totalGraphs()) {
popInvocation();
final MethodInvocation parentInvoke = currentInvocation();
try (Debug.Scope s = Debug.scope("Inlining", inliningContext())) {
return tryToInline(currentGraph(), currentInvocation, parentInvoke, inliningDepth() + 1);
} catch (Throwable e) {
throw Debug.handle(e);
}
}
return false;
}
}
| [inlining-5] "where does replacements come from?" answered
| graal/com.oracle.graal.phases.common/src/com/oracle/graal/phases/common/inlining/walker/InliningData.java | [inlining-5] "where does replacements come from?" answered |
|
Java | bsd-3-clause | 40a177f3a750195b27b1c04b40a82d5ceaeb8e73 | 0 | agmip/translator-generic-csv,MengZhang/translator-generic-csv | package org.agmip.translators.csv;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import au.com.bytecode.opencsv.CSVReader;
import java.util.HashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.agmip.ace.AcePathfinder;
import org.agmip.ace.util.AcePathfinderUtil;
import org.agmip.core.types.TranslatorInput;
/**
* This class converts CSV formatted files into the AgMIP ACE JSON format. It
* uses a common file pattern as described below.
*
* <p><b>First Column Descriptors</b></p> <p># - Lines with the first column
* text containing only a "#" is considered a header row</p> <p>! - Lines with
* the first column text containing only a "!" are considered a comment and not
* parsed.
*
* The first header/datarow(s) are metadata (or global data) if there are
* multiple rows of metadata, they are considered to be a collection of
* experiments.
*
*/
public class CSVInput implements TranslatorInput {
private static Logger LOG = LoggerFactory.getLogger(CSVInput.class);
// private HashMap<String, HashMap<String, HashMap<String, Object>>> finalMap;
private HashMap<String, HashMap<String, Object>> expMap, weatherMap, soilMap; // Storage maps
private HashMap<String, Integer> trtTracker;
private HashMap<String, String> idMap;
private ArrayList<String> orderring;
private String listSeparator;
private AcePathfinder pathfinder = AcePathfinderUtil.getInstance();
private static HashSet unknowVars = new HashSet();
private enum HeaderType {
UNKNOWN, // Probably uninitialized
SUMMARY, // #
SERIES // %
}
private static class CSVHeader {
private final ArrayList<String> headers;
private final ArrayList<Integer> skippedColumns;
private final String defPath;
private final AcePathfinderUtil.PathType defPathType;
public CSVHeader(ArrayList<String> headers, ArrayList<Integer> sc) {
this(headers, sc, null, AcePathfinderUtil.PathType.UNKNOWN);
}
public CSVHeader(ArrayList<String> headers, ArrayList<Integer> sc, String defPath, AcePathfinderUtil.PathType defPathType) {
this.headers = headers;
this.skippedColumns = sc;
this.defPath = defPath;
this.defPathType = defPathType;
}
public CSVHeader() {
this.headers = new ArrayList<String>();
this.skippedColumns = new ArrayList<Integer>();
this.defPath = null;
this.defPathType = AcePathfinderUtil.PathType.UNKNOWN;
}
public ArrayList<String> getHeaders() {
return headers;
}
public ArrayList<Integer> getSkippedColumns() {
return skippedColumns;
}
public String getDefPath() {
return defPath;
}
public AcePathfinderUtil.PathType getDefPathType() {
return defPathType;
}
}
public CSVInput() {
expMap = new HashMap<String, HashMap<String, Object>>();
weatherMap = new HashMap<String, HashMap<String, Object>>();
soilMap = new HashMap<String, HashMap<String, Object>>();
trtTracker = new HashMap<String, Integer>();
idMap = new HashMap<String, String>();
orderring = new ArrayList<String>();
// finalMap = new HashMap<String, HashMap<String, HashMap<String, Object>>>();
this.listSeparator = ",";
// finalMap.put("experiments", expMap);
// finalMap.put("weather", weatherMap);
// finalMap.put("soil", soilMap);
}
@Override
public Map readFile(String fileName) throws Exception {
if (fileName.toUpperCase().endsWith("CSV")) {
readCSV(new FileInputStream(fileName));
} else if (fileName.toUpperCase().endsWith("ZIP")) {
//Handle a ZipInputStream instead
LOG.debug("Launching zip file handler");
ZipFile zf = new ZipFile(fileName);
Enumeration<? extends ZipEntry> e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
LOG.debug("Entering file: " + ze);
readCSV(zf.getInputStream(ze));
}
zf.close();
}
return cleanUpFinalMap();
}
protected void readCSV(InputStream fileStream) throws Exception {
HeaderType section = HeaderType.UNKNOWN;
CSVHeader currentHeader = new CSVHeader();
String[] nextLine;
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
// Check to see if this is an international CSV. (;, vs ,.)
setListSeparator(br);
CSVReader reader = new CSVReader(br, this.listSeparator.charAt(0));
// Clear out the idMap for every file created.
idMap.clear();
int ln = 0;
while ((nextLine = reader.readNext()) != null) {
ln++;
LOG.debug("Line number: " + ln);
if (nextLine[0].startsWith("!")) {
LOG.debug("Found a comment line");
continue;
} else if (nextLine[0].startsWith("#")) {
LOG.debug("Found a summary header line");
section = HeaderType.SUMMARY;
currentHeader = parseHeaderLine(nextLine);
} else if (nextLine[0].startsWith("%")) {
LOG.debug("Found a series header line");
section = HeaderType.SERIES;
currentHeader = parseHeaderLine(nextLine);
} else if (nextLine[0].startsWith("*")) {
LOG.debug("Found a complete experiment line");
section = HeaderType.SUMMARY;
parseDataLine(currentHeader, section, nextLine, true);
} else if (nextLine[0].startsWith("&")) {
LOG.debug("Found a DOME line, skipping");
} else if (nextLine.length == 1) {
LOG.debug("Found a blank line, skipping");
} else {
boolean isBlank = true;
// Check the nextLine array for all blanks
int nlLen = nextLine.length;
for (int i = 0; i < nlLen; i++) {
if (!nextLine[i].equals("")) {
isBlank = false;
break;
}
}
if (!isBlank) {
LOG.debug("Found a data line with [" + nextLine[0] + "] as the index");
parseDataLine(currentHeader, section, nextLine, false);
} else {
LOG.debug("Found a blank line, skipping");
}
}
}
reader.close();
}
protected CSVHeader parseHeaderLine(String[] data) {
ArrayList<String> h = new ArrayList<String>();
ArrayList<Integer> sc = new ArrayList<Integer>();
String defPath = null;
AcePathfinderUtil.PathType defPathType = AcePathfinderUtil.PathType.UNKNOWN;
int l = data.length;
for (int i = 1; i < l; i++) {
if (data[i].startsWith("!")) {
sc.add(i);
}
if (data[i].trim().length() != 0) {
h.add(data[i]);
}
if (defPath == null) {
defPath = AcePathfinderUtil.getInstance().getPath(data[i].trim());
if (defPath != null) {
defPath = defPath.replaceAll(",", "").trim();
defPathType = AcePathfinderUtil.getVariableType(data[i].trim());
}
}
}
return new CSVHeader(h, sc, defPath, defPathType);
}
protected void parseDataLine(CSVHeader header, HeaderType section, String[] data, boolean isComplete) throws Exception {
ArrayList<String> headers = header.getHeaders();
int l = headers.size();
String dataIndex;
dataIndex = UUID.randomUUID().toString();
if (!isComplete) {
if (idMap.containsKey(data[0])) {
dataIndex = idMap.get(data[0]);
} else {
idMap.put(data[0], dataIndex);
}
}
if (data[1].toLowerCase().equals("event")) {
for (int i = 3; i < data.length; i++) {
String var = data[i].toLowerCase();
i++;
if (i < data.length) {
String val = data[i];
LOG.debug("Trimmed var: " + var.trim() + " and length: " + var.trim().length());
if (var.trim().length() != 0 && val.trim().length() != 0) {
LOG.debug("INSERTING! Var: " + var + " Val: " + val);
insertValue(dataIndex, var, val, header);
}
}
}
LOG.debug("Leaving event loop");
} else if (header.getSkippedColumns().isEmpty()) {
for (int i = 0; i < l; i++) {
if (!data[i + 1].equals("")) {
insertValue(dataIndex, headers.get(i), data[i + 1], header);
}
}
} else {
ArrayList<Integer> skipped = header.getSkippedColumns();
for (int i = 0; i < l; i++) {
if (!data[i + 1].equals("")) {
if (!skipped.contains(i + 1)) {
insertValue(dataIndex, headers.get(i), data[i + 1], header);
}
}
}
}
}
protected void insertValue(String index, String variable, String value, CSVHeader header) throws Exception {
try {
String var = variable.toLowerCase();
HashMap<String, HashMap<String, Object>> topMap = null;
if (var.equals("wst_id") || var.equals("soil_id")) {
insertIndex(expMap, index, true);
HashMap<String, Object> temp = expMap.get(index);
temp.put(var, value);
} else if (var.equals("exname")) {
Integer i = 0;
if (trtTracker.containsKey(value)) {
i = trtTracker.get(value);
}
i = i + 1;
trtTracker.put(value, i);
value = value + "_" + i;
} else {
if (pathfinder.isDate(var)) {
LOG.debug("Converting date from: " + value);
value = value.replace("/", "-");
DateFormat f = new SimpleDateFormat("yyyymmdd");
Date d = new SimpleDateFormat("yyyy-mm-dd").parse(value);
value = f.format(d);
LOG.debug("Converting date to: " + value);
}
}
boolean isExperimentMap = false;
String path = null;
switch (AcePathfinderUtil.getVariableType(var)) {
case WEATHER:
topMap = weatherMap;
break;
case SOIL:
topMap = soilMap;
break;
case UNKNOWN:
switch (header.getDefPathType()) {
case WEATHER:
topMap = weatherMap;
path = header.getDefPath();
break;
case SOIL:
topMap = soilMap;
path = header.getDefPath();
break;
}
if (!unknowVars.contains(var)) {
if (path != null || "".equals(path)) {
LOG.warn("Putting unknow variable into [{}] section: [{}]", path, var);
} else {
LOG.warn("Putting unknow variable into root: [{}]", var);
}
unknowVars.add(var);
}
if (topMap != null) {
break;
}
default:
isExperimentMap = true;
topMap = expMap;
break;
}
insertIndex(topMap, index, isExperimentMap);
HashMap<String, Object> currentMap = topMap.get(index);
AcePathfinderUtil.insertValue(currentMap, var, value, path, true);
} catch (Exception ex) {
throw new Exception(ex);
}
}
protected void insertIndex(HashMap<String, HashMap<String, Object>> map, String index, boolean isExperimentMap) {
if (!map.containsKey(index)) {
map.put(index, new HashMap<String, Object>());
if (isExperimentMap) {
orderring.add(index);
}
}
}
protected HashMap<String, ArrayList<HashMap<String, Object>>> cleanUpFinalMap() {
HashMap<String, ArrayList<HashMap<String, Object>>> base = new HashMap<String, ArrayList<HashMap<String, Object>>>();
ArrayList<HashMap<String, Object>> experiments = new ArrayList<HashMap<String, Object>>();
ArrayList<HashMap<String, Object>> weathers = new ArrayList<HashMap<String, Object>>();
ArrayList<HashMap<String, Object>> soils = new ArrayList<HashMap<String, Object>>();
for (String id : orderring) {
//for (HashMap<String, Object> ex : expMap.values()) {
HashMap<String, Object> ex = expMap.get(id);
ex.remove("weather");
ex.remove("soil");
if (ex.size() == 2 && ex.containsKey("wst_id") && ex.containsKey("soil_id")) {
} else if (ex.size() == 1 && (ex.containsKey("wst_id") || ex.containsKey("soil_id"))) {
} else {
experiments.add(ex);
}
}
for (Object wth : weatherMap.values()) {
if (wth instanceof HashMap) {
@SuppressWarnings("unchecked")
HashMap<String, Object> temp = (HashMap<String, Object>) wth;
if (temp.containsKey("weather")) {
@SuppressWarnings("unchecked")
HashMap<String, Object> weather = (HashMap<String, Object>) temp.get("weather");
if (weather.size() == 1 && weather.containsKey("wst_id")) {
} else {
weathers.add(weather);
}
}
}
}
for (Object sl : soilMap.values()) {
if (sl instanceof HashMap) {
@SuppressWarnings("unchecked")
HashMap<String, Object> temp = (HashMap<String, Object>) sl;
if (temp.containsKey("soil")) {
@SuppressWarnings("unchecked")
HashMap<String, Object> soil = (HashMap<String, Object>) temp.get("soil");
if (soil.size() == 1 && soil.containsKey("soil_id")) {
} else {
soils.add(soil);
}
}
}
}
base.put("experiments", experiments);
base.put("weathers", weathers);
base.put("soils", soils);
return base;
}
protected void setListSeparator(BufferedReader in) throws Exception {
// Set a mark at the beginning of the file, so we can get back to it.
in.mark(7168);
String sample;
while ((sample = in.readLine()) != null) {
if (sample.startsWith("#")) {
String listSeperator = sample.substring(1, 2);
LOG.debug("FOUND SEPARATOR: " + listSeperator);
this.listSeparator = listSeperator;
break;
}
}
in.reset();
}
}
| src/main/java/org/agmip/translators/csv/CSVInput.java | package org.agmip.translators.csv;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import au.com.bytecode.opencsv.CSVReader;
import java.util.HashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.agmip.ace.AcePathfinder;
import org.agmip.ace.util.AcePathfinderUtil;
import org.agmip.core.types.TranslatorInput;
/**
* This class converts CSV formatted files into the AgMIP ACE JSON
* format. It uses a common file pattern as described below.
*
* <p><b>First Column Descriptors</b></p>
* <p># - Lines with the first column text containing only a "#" is considered
* a header row</p>
* <p>! - Lines with the first column text containing only a "!" are considered
* a comment and not parsed.
*
* The first header/datarow(s) are metadata (or global data) if there are multiple
* rows of metadata, they are considered to be a collection of experiments.
*
*/
public class CSVInput implements TranslatorInput {
private static Logger LOG = LoggerFactory.getLogger(CSVInput.class);
// private HashMap<String, HashMap<String, HashMap<String, Object>>> finalMap;
private HashMap<String, HashMap<String, Object>> expMap, weatherMap, soilMap; // Storage maps
private HashMap<String, Integer> trtTracker;
private HashMap<String, String> idMap;
private ArrayList<String> orderring;
private String listSeparator;
private AcePathfinder pathfinder = AcePathfinderUtil.getInstance();
private static HashSet unknowVars = new HashSet();
private enum HeaderType {
UNKNOWN, // Probably uninitialized
SUMMARY, // #
SERIES // %
}
private static class CSVHeader {
private final ArrayList<String> headers;
private final ArrayList<Integer> skippedColumns;
public CSVHeader(ArrayList<String> headers, ArrayList<Integer> sc) {
this.headers = headers;
this.skippedColumns = sc;
}
public CSVHeader() {
this.headers = new ArrayList<String>();
this.skippedColumns = new ArrayList<Integer>();
}
public ArrayList<String> getHeaders() {
return headers;
}
public ArrayList<Integer> getSkippedColumns() {
return skippedColumns;
}
}
public CSVInput() {
expMap = new HashMap<String, HashMap<String, Object>>();
weatherMap = new HashMap<String, HashMap<String, Object>>();
soilMap = new HashMap<String, HashMap<String, Object>>();
trtTracker = new HashMap<String, Integer>();
idMap = new HashMap<String, String>();
orderring = new ArrayList<String>();
// finalMap = new HashMap<String, HashMap<String, HashMap<String, Object>>>();
this.listSeparator = ",";
// finalMap.put("experiments", expMap);
// finalMap.put("weather", weatherMap);
// finalMap.put("soil", soilMap);
}
@Override
public Map readFile(String fileName) throws Exception {
if (fileName.toUpperCase().endsWith("CSV")) {
readCSV(new FileInputStream(fileName));
} else if (fileName.toUpperCase().endsWith("ZIP")) {
//Handle a ZipInputStream instead
LOG.debug("Launching zip file handler");
ZipFile zf = new ZipFile(fileName);
Enumeration<? extends ZipEntry> e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
LOG.debug("Entering file: " + ze);
readCSV(zf.getInputStream(ze));
}
zf.close();
}
return cleanUpFinalMap();
}
protected void readCSV(InputStream fileStream) throws Exception {
HeaderType section = HeaderType.UNKNOWN;
CSVHeader currentHeader = new CSVHeader();
String[] nextLine;
BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));
// Check to see if this is an international CSV. (;, vs ,.)
setListSeparator(br);
CSVReader reader = new CSVReader(br, this.listSeparator.charAt(0));
// Clear out the idMap for every file created.
idMap.clear();
int ln = 0;
while ((nextLine = reader.readNext()) != null) {
ln++;
LOG.debug("Line number: " + ln);
if (nextLine[0].startsWith("!")) {
LOG.debug("Found a comment line");
continue;
} else if (nextLine[0].startsWith("#")) {
LOG.debug("Found a summary header line");
section = HeaderType.SUMMARY;
currentHeader = parseHeaderLine(nextLine);
} else if (nextLine[0].startsWith("%")) {
LOG.debug("Found a series header line");
section = HeaderType.SERIES;
currentHeader = parseHeaderLine(nextLine);
} else if (nextLine[0].startsWith("*")) {
LOG.debug("Found a complete experiment line");
section = HeaderType.SUMMARY;
parseDataLine(currentHeader, section, nextLine, true);
} else if (nextLine[0].startsWith("&")) {
LOG.debug("Found a DOME line, skipping");
} else if (nextLine.length == 1) {
LOG.debug("Found a blank line, skipping");
} else {
boolean isBlank = true;
// Check the nextLine array for all blanks
int nlLen = nextLine.length;
for(int i=0; i < nlLen; i++) {
if (! nextLine[i].equals("")) {
isBlank = false;
break;
}
}
if (!isBlank) {
LOG.debug("Found a data line with [" + nextLine[0] + "] as the index");
parseDataLine(currentHeader, section, nextLine, false);
} else {
LOG.debug("Found a blank line, skipping");
}
}
}
reader.close();
}
protected CSVHeader parseHeaderLine(String[] data) {
ArrayList<String> h = new ArrayList<String>();
ArrayList<Integer> sc = new ArrayList<Integer>();
int l = data.length;
for (int i = 1; i < l; i++) {
if (data[i].startsWith("!")) {
sc.add(i);
}
if (data[i].trim().length() != 0) {
h.add(data[i]);
}
}
return new CSVHeader(h, sc);
}
protected void parseDataLine(CSVHeader header, HeaderType section, String[] data, boolean isComplete) throws Exception {
ArrayList<String> headers = header.getHeaders();
int l = headers.size();
String dataIndex;
dataIndex = UUID.randomUUID().toString();
if (!isComplete) {
if (idMap.containsKey(data[0])) {
dataIndex = idMap.get(data[0]);
} else {
idMap.put(data[0], dataIndex);
}
}
if (data[1].toLowerCase().equals("event")) {
for (int i = 3; i < data.length; i++) {
String var = data[i].toLowerCase();
i++;
if (i < data.length) {
String val = data[i];
LOG.debug("Trimmed var: " + var.trim() + " and length: " + var.trim().length());
if (var.trim().length() != 0 && val.trim().length() != 0) {
LOG.debug("INSERTING! Var: "+var+" Val: "+val);
insertValue(dataIndex, var, val);
}
}
}
LOG.debug("Leaving event loop");
} else if (header.getSkippedColumns().isEmpty()) {
for (int i = 0; i < l; i++) {
if (!data[i + 1].equals("")) {
insertValue(dataIndex, headers.get(i), data[i + 1]);
}
}
} else {
ArrayList<Integer> skipped = header.getSkippedColumns();
for (int i = 0; i < l; i++) {
if (!data[i + 1].equals("")) {
if (!skipped.contains(i + 1)) {
insertValue(dataIndex, headers.get(i), data[i + 1]);
}
}
}
}
}
protected void insertValue(String index, String variable, String value) throws Exception {
try {
String var = variable.toLowerCase();
HashMap<String, HashMap<String, Object>> topMap;
if (var.equals("wst_id") || var.equals("soil_id")) {
insertIndex(expMap, index, true);
HashMap<String, Object> temp = expMap.get(index);
temp.put(var, value);
} else if (var.equals("exname")) {
Integer i = 0;
if (trtTracker.containsKey(value)) {
i = trtTracker.get(value);
}
i = i + 1;
trtTracker.put(value, i);
value = value+"_"+i;
} else {
if (pathfinder.isDate(var)) {
LOG.debug("Converting date from: " + value);
value = value.replace("/", "-");
DateFormat f = new SimpleDateFormat("yyyymmdd");
Date d = new SimpleDateFormat("yyyy-mm-dd").parse(value);
value = f.format(d);
LOG.debug("Converting date to: " + value);
}
}
boolean isExperimentMap = false;
switch (AcePathfinderUtil.getVariableType(var)) {
case WEATHER:
topMap = weatherMap;
break;
case SOIL:
topMap = soilMap;
break;
case UNKNOWN:
if (!unknowVars.contains(var)) {
LOG.warn("Putting unknow variable into root: [" + var + "]");
unknowVars.add(var);
}
default:
isExperimentMap = true;
topMap = expMap;
break;
}
insertIndex(topMap, index, isExperimentMap);
HashMap<String, Object> currentMap = topMap.get(index);
AcePathfinderUtil.insertValue(currentMap, var, value, true);
} catch (Exception ex) {
throw new Exception(ex);
}
}
protected void insertIndex(HashMap<String, HashMap<String, Object>> map, String index, boolean isExperimentMap) {
if (!map.containsKey(index)) {
map.put(index, new HashMap<String, Object>());
if (isExperimentMap) {
orderring.add(index);
}
}
}
protected HashMap<String, ArrayList<HashMap<String, Object>>> cleanUpFinalMap() {
HashMap<String, ArrayList<HashMap<String, Object>>> base = new HashMap<String, ArrayList<HashMap<String, Object>>>();
ArrayList<HashMap<String, Object>> experiments = new ArrayList<HashMap<String, Object>>();
ArrayList<HashMap<String, Object>> weathers = new ArrayList<HashMap<String, Object>>();
ArrayList<HashMap<String, Object>> soils = new ArrayList<HashMap<String, Object>>();
for (String id : orderring) {
//for (HashMap<String, Object> ex : expMap.values()) {
HashMap<String, Object> ex = expMap.get(id);
ex.remove("weather");
ex.remove("soil");
if (ex.size() == 2 && ex.containsKey("wst_id") && ex.containsKey("soil_id")) {
} else if (ex.size() == 1 && (ex.containsKey("wst_id") || ex.containsKey("soil_id"))) {
} else {
experiments.add(ex);
}
}
for (Object wth : weatherMap.values()) {
if (wth instanceof HashMap) {
@SuppressWarnings("unchecked")
HashMap<String, Object> temp = (HashMap<String, Object>) wth;
if (temp.containsKey("weather")) {
@SuppressWarnings("unchecked")
HashMap<String, Object> weather = (HashMap<String, Object>) temp.get("weather");
if (weather.size() == 1 && weather.containsKey("wst_id")) {
} else {
weathers.add(weather);
}
}
}
}
for (Object sl : soilMap.values()) {
if (sl instanceof HashMap) {
@SuppressWarnings("unchecked")
HashMap<String, Object> temp = (HashMap<String, Object>) sl;
if (temp.containsKey("soil")) {
@SuppressWarnings("unchecked")
HashMap<String, Object> soil = (HashMap<String, Object>) temp.get("soil");
if (soil.size() == 1 && soil.containsKey("soil_id")) {
} else {
soils.add(soil);
}
}
}
}
base.put("experiments", experiments);
base.put("weathers", weathers);
base.put("soils", soils);
return base;
}
protected void setListSeparator(BufferedReader in) throws Exception {
// Set a mark at the beginning of the file, so we can get back to it.
in.mark(7168);
String sample;
while ((sample = in.readLine()) != null) {
if (sample.startsWith("#")) {
String listSeperator = sample.substring(1,2);
LOG.debug("FOUND SEPARATOR: "+listSeperator);
this.listSeparator = listSeperator;
break;
}
}
in.reset();
}
}
| Add auto-judge for data type when variable is not registered in the ICASA list | src/main/java/org/agmip/translators/csv/CSVInput.java | Add auto-judge for data type when variable is not registered in the ICASA list |
|
Java | bsd-3-clause | 37ccc5e4b329527a4fd174a75fa7e7f4bdf022a4 | 0 | UCDenver-ccp/datasource,bill-baumgartner/datasource,UCDenver-ccp/datasource,bill-baumgartner/datasource | /**
*
*/
package edu.ucdenver.ccp.datasource.identifiers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.ucdenver.ccp.datasource.identifiers.ebi.embl.EmblID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.GenBankID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.refseq.RefSeqID;
import edu.ucdenver.ccp.datasource.identifiers.other.DdbjId;
/**
* Resolution of accession identifiers based on prefixes available here:
* http://www.ncbi.nlm.nih.gov/Sequin/acc.html
*
* @author Colorado Computational Pharmacology, UC Denver; [email protected]
*
*/
public class ProteinAccessionResolver {
private static final Pattern ACC_PATTERN = Pattern.compile("([A-Z]{3})\\d+\\.?\\d*");
private static final String VALID_UNIPROT_PATTERN_1 = "[A-NR-Z][0-9][A-Z][A-Z0-9][A-Z0-9][0-9]";
private static final String VALID_UNIPROT_PATTERN_2 = "[OPQ][0-9][A-Z0-9][A-Z0-9][A-Z0-9][0-9]";
public static DataSourceIdentifier<String> resolveProteinAccession(String acc) {
if (acc.matches("[A-Z][A-Z]_\\d+\\.?\\d*")) {
return new RefSeqID(acc);
}
if (acc.matches(VALID_UNIPROT_PATTERN_1) || acc.matches(VALID_UNIPROT_PATTERN_2)) {
return new UniProtID(acc);
}
Matcher m = ACC_PATTERN.matcher(acc);
if (m.find()) {
String prefix = m.group(1);
if (prefix.startsWith("A")) {
return new GenBankID(acc);
}
if (prefix.startsWith("B")) {
return new DdbjId(acc);
}
if (prefix.startsWith("C")) {
return new EmblID(acc);
}
if (prefix.startsWith("D")) {
return new GenBankID(acc);
}
if (prefix.startsWith("E")) {
return new GenBankID(acc);
}
if (prefix.startsWith("F")) {
return new DdbjId(acc);
}
if (prefix.startsWith("G")) {
return new DdbjId(acc);
}
if (prefix.startsWith("H")) {
return new GenBankID(acc);
}
if (prefix.startsWith("I")) {
return new DdbjId(acc);
}
if (prefix.startsWith("J")) {
return new GenBankID(acc);
}
}
throw new IllegalArgumentException("Input is not a known protein accession pattern: " + acc);
}
}
| datasource-identifiers/src/main/java/edu/ucdenver/ccp/datasource/identifiers/ProteinAccessionResolver.java | /**
*
*/
package edu.ucdenver.ccp.datasource.identifiers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.ucdenver.ccp.datasource.identifiers.ebi.embl.EmblID;
import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.GenBankID;
import edu.ucdenver.ccp.datasource.identifiers.ncbi.refseq.RefSeqID;
import edu.ucdenver.ccp.datasource.identifiers.other.DdbjId;
/**
* Resolution of accession identifiers based on prefixes available here:
* http://www.ncbi.nlm.nih.gov/Sequin/acc.html
*
* @author Colorado Computational Pharmacology, UC Denver; [email protected]
*
*/
public class ProteinAccessionResolver {
private static final Pattern ACC_PATTERN = Pattern.compile("([A-Z]{3})\\d+\\.?\\d*");
public static DataSourceIdentifier<String> resolveProteinAccession(String acc) {
if (acc.matches("[A-Z][A-Z]_\\d+\\.?\\d*")) {
return new RefSeqID(acc);
}
if (acc.startsWith("O")) {
return new UniProtID(acc);
}
if (acc.startsWith("P")) {
return new UniProtID(acc);
}
if (acc.startsWith("Q")) {
return new UniProtID(acc);
}
Matcher m = ACC_PATTERN.matcher(acc);
if (m.find()) {
String prefix = m.group(1);
if (prefix.startsWith("A")) {
return new GenBankID(acc);
}
if (prefix.startsWith("B")) {
return new DdbjId(acc);
}
if (prefix.startsWith("C")) {
return new EmblID(acc);
}
if (prefix.startsWith("D")) {
return new GenBankID(acc);
}
if (prefix.startsWith("E")) {
return new GenBankID(acc);
}
if (prefix.startsWith("F")) {
return new DdbjId(acc);
}
if (prefix.startsWith("G")) {
return new DdbjId(acc);
}
if (prefix.startsWith("H")) {
return new GenBankID(acc);
}
if (prefix.startsWith("I")) {
return new DdbjId(acc);
}
if (prefix.startsWith("J")) {
return new GenBankID(acc);
}
}
throw new IllegalArgumentException("Input is not a known protein accession pattern: " + acc);
}
}
| made uniprot accession handling more robust
| datasource-identifiers/src/main/java/edu/ucdenver/ccp/datasource/identifiers/ProteinAccessionResolver.java | made uniprot accession handling more robust |
|
Java | mit | 81828c8cd66b31c14ed9ef1e846ef4eefd4077c9 | 0 | sqlancer/sqlancer,sqlancer/sqlancer | src/sqlancer/sqlite3/ast/Sqlite3ExpressionValue.java | package sqlancer.sqlite3.ast;
public class Sqlite3ExpressionValue {
}
| [SQLite3] Remove obsolete class
| src/sqlancer/sqlite3/ast/Sqlite3ExpressionValue.java | [SQLite3] Remove obsolete class |
||
Java | apache-2.0 | 8c0f7d2255ec42350bb097a6d0c989ec9c799db8 | 0 | MarcoCaballero/FFB_DAW,MarcoCaballero/FFB_DAW,MarcoCaballero/FFB_DAW,MarcoCaballero/FFB_DAW,MarcoCaballero/FFB_DAW | ffb_daw_fase3/src/main/java/com/ffbet/fase3/controllers/ImageTestController.java | package com.ffbet.fase3.controllers;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ffbet.fase3.domain.EgamesMatch;
import com.ffbet.fase3.domain.EgamesTeam;
import com.ffbet.fase3.domain.SportTeam;
import com.ffbet.fase3.domain.SportsMatch;
import com.ffbet.fase3.domain.Team;
import com.ffbet.fase3.domain.User;
import com.ffbet.fase3.repositories.EgamesTeamRepository;
import com.ffbet.fase3.repositories.Egames_match_repository;
import com.ffbet.fase3.repositories.SportTeamRepository;
import com.ffbet.fase3.repositories.Sports_match_repository;
import com.ffbet.fase3.security.UserAuthComponent;
@RestController
public class ImageTestController {
@Autowired
private SportTeamRepository sport_team_repo;
@Autowired
private EgamesTeamRepository egame_team_repo;
@Autowired
private Sports_match_repository sport_match_repo;
@Autowired
private Egames_match_repository egames_match_repo;
@Autowired
UserAuthComponent userComp;
/**
* Initializer on PostConstruct
*
* @throws IOException
* @throws ParseException
*/
@PostConstruct
public void init() throws IOException, ParseException {
SportTeam sport_team = new SportTeam();
sport_team.setName("P_001");
sport_team.setCity("Madrid");
sport_team.setCoach("marianete");
sport_team.setType("Fútbol");
SportTeam sp1 = new SportTeam();
sp1.setName("Equipo 1");
sp1.setCoach("Peperoni");
sp1.setType("Fútbol");
SportTeam sp2 = new SportTeam();
sp2.setName("Equipo 2");
sp2.setCoach("Queseroni");
sp2.setType("Baloncesto");
EgamesTeam eg_team1 = new EgamesTeam();
eg_team1.setName("ORIGEN");
eg_team1.setCity("Murcia");
eg_team1.setCoach("Camacho");
eg_team1.setType("LOL");
EgamesTeam eg_team2 = new EgamesTeam();
eg_team2.setName("SKT T1");
eg_team2.setCity("Tokyo");
eg_team2.setCoach("Simeone");
eg_team2.setType("CS-GO");
SportsMatch sportMatch1 = new SportsMatch();
sportMatch1.setHomeTeam("RealMadrid");
sportMatch1.setVisitingTeam("Atletico");
sportMatch1.setType("Futbol");
SportsMatch sportMatch2 = new SportsMatch();
sportMatch2.setHomeTeam("Fuenla");
sportMatch2.setVisitingTeam("Alcorcon");
sportMatch2.setType("Futbol");
SportsMatch sportMatch3 = new SportsMatch();
sportMatch3.setHomeTeam("RealMadrid");
sportMatch3.setVisitingTeam("Atletico");
sportMatch3.setType("Baloncesto");
SportsMatch sportMatch4 = new SportsMatch();
sportMatch4.setHomeTeam("Barcelona");
sportMatch4.setVisitingTeam("Atletico");
sportMatch4.setType("Baloncesto");
EgamesMatch egamesMatch1 = new EgamesMatch();
egamesMatch1.setHomeTeam("asd");
egamesMatch1.setVisitingTeam("asdddd");
egamesMatch1.setType("Lol");
egamesMatch1.setWinHome(true);
egamesMatch1.setFirstBloodVisiting(true);
EgamesMatch egamesMatch2 = new EgamesMatch();
egamesMatch2.setHomeTeam("SKT");
egamesMatch2.setVisitingTeam("Origin");
egamesMatch2.setType("CS-GO");
egamesMatch2.setWinHome(true);
egamesMatch2.setFirstBloodVisiting(true);
egames_match_repo.save(egamesMatch2);
egames_match_repo.save(egamesMatch1);
sport_match_repo.save(sportMatch1);
sport_match_repo.save(sportMatch2);
sport_match_repo.save(sportMatch3);
sport_match_repo.save(sportMatch4);
EgamesTeam eg_team = new EgamesTeam();
eg_team.setName("P_002");
eg_team.setCity("Valencia");
eg_team.setCoach("marianeta");
eg_team.setType("LOL");
egame_team_repo.save(eg_team);
/*
* try { FileInputStream f_in = new
* FileInputStream("C:\\Users\\Marco\\Desktop\\gato.jpg");
*
* sport_team.setShield_image(IOUtils.toByteArray(f_in)); } catch
* (Exception e) { // TODO: handle exception e.printStackTrace(); }
*/
egame_team_repo.save(eg_team1);
egame_team_repo.save(eg_team2);
sport_team_repo.save(sport_team);
sport_team_repo.save(sp1);
sport_team_repo.save(sp2);
}
}
| Fuera Test
| ffb_daw_fase3/src/main/java/com/ffbet/fase3/controllers/ImageTestController.java | Fuera Test |
||
Java | mit | 8f91c592d637e7eaa7aeb42b809926640960b1ce | 0 | robertbdc/CS2336-Java-Food-Truck | package restauranttester;
import java.util.Scanner;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Restaurant extends Menu
{
Restaurant()
{
//Creates ArrayList of Server Objects
}
public void createMenu()
{
//Creates the object of Menu
Menu menu = new Menu();
//Reads file and sends the code, name and price to setMenuItem()
String code, name;
double price;
String FILE_NAME = "C:\\Users\\Neil\\Documents\\CS2336-501\\Menu.txt";
Path path = Paths.get(FILE_NAME);
try
{
Scanner sc = new Scanner(path);
while(sc.hasNextLine())
{
code = sc.next();
name = sc.next();
price = sc.nextDouble();
MenuItem food = new MenuItem(code, name, price);
menuList.add(food);
}
}
catch(Exception ex)
{
System.out.print(ex.getCause());
}
}
public void displayMenu()
{
//fix this output
for(int i = 0; i < menuList.size(); i++)
{
System.out.print(menuList.get(i).getItemName());
}
}
public void displayServerList()
{
//Displays the list of Servers in the
}
public void restaurantActivity()
{
}
public void processActivity()
{
}
}
| Restaurant.java | package restauranttester;
import java.util.Scanner;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Restaurant
{
Restaurant()
{
//Creates the object of Menu
Menu menu = new Menu();
//Creates ArrayList of Server Objects
//Reads file and sends the code, name and price to setMenuItem()
String code, name;
double price;
String FILE_NAME = "C:\\Users\\Neil\\Documents\\CS2336-501\\Menu.txt";
Path path = Paths.get(FILE_NAME);
try
{
Scanner sc = new Scanner(path);
while(sc.hasNextLine())
{
code = sc.next();
name = sc.next();
price = sc.nextDouble();
menu.setMenuItem(code, name, price);
}
}
catch(Exception ex)
{
System.out.print(ex.getCause());
}
}
public void createMenu()
{
//Creates the objects of MenuItems and adds those to the menu
}
public void displayMenu()
{
}
public void displayServerList()
{
//Displays the list of Servers in the
}
public void restaurantActivity()
{
}
public void processActivity()
{
}
}
| Update Restaurant.java
Updating 10/16/13, work in progress creating the ArrayList of MenuItems. | Restaurant.java | Update Restaurant.java |
|
Java | mit | 701a44d9bffcb7e9bf641cd042e7272ec179eeb5 | 0 | tlaplus/tlaplus,lemmy/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus | package org.lamport.tla.toolbox.tool.tlc.ui.editor.part;
import java.util.Vector;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.lamport.tla.toolbox.tool.tlc.model.Formula;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.BasicFormPage;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.provider.FormulaContentProvider;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.provider.FormulaLabelProvider;
import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper;
import org.lamport.tla.toolbox.tool.tlc.ui.wizard.FormulaWizard;
/**
* Section part with table and add, edit and remove buttons
* @author Simon Zambrovski
* @version $Id: TableSectionPart.java 625 2009-04-07 04:04:58Z simonzam $
*/
public class ValidateableTableSectionPart extends SectionPart implements IValidateble
{
private BasicFormPage page;
// A TableViewer is the JFace object that seems to implement the
// thing that gets displayed on the screen. It has methods for
// adding and removing items and returning the list of all items
// (the latter is the getInput() method, which seems to be a weird
// name because it's the list of things added with the add() method).
protected TableViewer tableViewer;
private Button buttonAdd;
private Button buttonEdit;
private Button buttonRemove;
// a listener reacting on clicks
protected SelectionListener fSelectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e)
{
Object source = e.getSource();
if (source == buttonAdd)
{
doAdd();
} else if (source == buttonRemove)
{
doRemove();
} else if (source == buttonEdit)
{
doEdit();
}
}
};
// a listener reacting on selection in the table viewer
protected ISelectionChangedListener fSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event)
{
Object source = event.getSource();
if (source == tableViewer)
{
changeButtonEnablement();
}
}
};
/**
* Constructor of the part without section flags
* @see ValidateableTableSectionPart#TableSectionPart(Composite, String, String, FormToolkit, int)
*/
public ValidateableTableSectionPart(Composite composite, String title, String description, FormToolkit toolkit,
BasicFormPage page, String sectionName)
{
this(composite, title, description, toolkit, Section.DESCRIPTION | Section.TITLE_BAR, page, sectionName);
}
/**
* Constructs the section part
* @param composite, parent composite
* @param title, part title
* @param description, part description
* @param toolkit, a toolkit for building controls
* @param sectionFlags, flags to be passed to the part during construction
* @param sectionName name of the section
*/
public ValidateableTableSectionPart(Composite composite, String title, String description, FormToolkit toolkit,
int sectionFlags, BasicFormPage page, String sectionName)
{
super(FormHelper.createSectionComposite(composite, title, description, toolkit, sectionFlags, null));
this.page = page;
page.getDataBindingManager().bindSection(this, sectionName, page.getId());
}
/**
* Initialize the section
*/
public void initialize(IManagedForm form)
{
super.initialize(form);
sectionInitialize(form.getToolkit());
}
public void commit(boolean onSave)
{
// commit the part on save, but not on other events
if (onSave)
{
super.commit(onSave);
}
}
/**
* Constructs the section content
* @param toolkit
*/
protected void sectionInitialize(FormToolkit toolkit)
{
GridData gd;
// create the composite
Composite sectionArea = (Composite) getSection().getClient();
sectionArea.setLayout(new GridLayout(2, false));
// The section grabs the entire space
gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessVerticalSpace = true;
getSection().setLayoutData(gd);
// create the table
Table table = createTable(sectionArea, toolkit);
// The table grabs the entire space in the section
gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
// span for the buttons
gd.verticalSpan = 3;
table.setLayoutData(gd);
// create the table viewer
tableViewer = createTableViewer(table);
// create buttons
createButtons(sectionArea, toolkit, true, true, true);
// setup the buttons
changeButtonEnablement();
}
/**
* @param table
* @return
*/
protected TableViewer createTableViewer(Table table)
{
// create
CheckboxTableViewer tableViewer = new CheckboxTableViewer(table);
if (Platform.WS_GTK.equals(Platform.getWS())) {
// Ideally, the invariants and properties viewer would show the formula with a
// fixed-width font (monospace). However, this has issues on Mac and Windows
// (does not handle multi-line formula). Hence, only use a monospaced font
// on GTK (Linux) where the behaviour is fine.
tableViewer.setLabelProvider(new FormulaLabelProvider());
}
// represent formulas in the view
tableViewer.setContentProvider(new FormulaContentProvider());
// on changed selection change button enablement
tableViewer.addSelectionChangedListener(fSelectionChangedListener);
// edit on double-click
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event)
{
doEdit();
}
});
// mark model dirty on checking / un-checking
tableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event)
{
doCheck();
}
});
return tableViewer;
}
/**
* Creates the table to be put into the tableviewer
* @param sectionArea
* @return
*/
protected Table createTable(Composite sectionArea, FormToolkit toolkit)
{
Table table = toolkit.createTable(sectionArea, SWT.MULTI | SWT.CHECK | SWT.V_SCROLL | SWT.H_SCROLL
| SWT.FULL_SELECTION);
table.setLinesVisible(false);
table.setHeaderVisible(false);
return table;
}
/**
* Creates buttons
* <br>
* Subclasses might override this method if they intend to change the buttons. For actual implementation see
* {@link ValidateableTableSectionPart#doCreateButtons(Composite, FormToolkit, boolean, boolean, boolean)}
*/
protected void createButtons(Composite sectionArea, FormToolkit toolkit, boolean add, boolean edit, boolean remove)
{
doCreateButtons(sectionArea, toolkit, add, edit, remove);
}
/**
* Create up to three buttons in the section area
* @param sectionArea
* @param toolkit
* @param add
* @param edit
* @param remove
*/
protected void doCreateButtons(Composite sectionArea, FormToolkit toolkit, boolean add, boolean edit, boolean remove)
{
GridData gd;
int added = 0;
if (add)
{
// add button
buttonAdd = toolkit.createButton(sectionArea, "Add", SWT.PUSH);
buttonAdd.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonAdd.setLayoutData(gd);
added++;
}
if (edit)
{
// edit button
buttonEdit = toolkit.createButton(sectionArea, "Edit", SWT.PUSH);
buttonEdit.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonEdit.setLayoutData(gd);
added++;
}
if (remove)
{
// remove button
buttonRemove = toolkit.createButton(sectionArea, "Remove", SWT.PUSH);
buttonRemove.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonRemove.setLayoutData(gd);
added++;
}
if (added < 3)
{
Composite span = toolkit.createComposite(sectionArea);
gd = new GridData();
gd.verticalSpan = 3 - added;
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
span.setLayoutData(gd);
}
}
/**
* Retrieves the table viewer
* @return
*/
public TableViewer getTableViewer()
{
return tableViewer;
}
/**
* Remove the selected formulas
*/
protected void doRemove()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Vector input = (Vector) tableViewer.getInput();
input.removeAll(selection.toList());
tableViewer.setInput(input);
this.doMakeDirty();
}
/**
* Add a formula to the list
*/
protected void doAdd()
{
Formula formula = doEditFormula(null);
// add a formula
if (formula != null)
{
Vector input = ((Vector) tableViewer.getInput());
input.add(formula);
tableViewer.setInput(input);
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
this.doMakeDirty();
}
}
/**
* Edit selected formula
*/
protected void doEdit()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Formula formula = (Formula) selection.getFirstElement();
Formula editedFormula = doEditFormula(formula);
if (editedFormula != null)
{
formula.setFormula(editedFormula.getFormula());
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
this.doMakeDirty();
tableViewer.refresh();
}
}
/**
* React on formula been checked or un-checked
*/
protected void doCheck()
{
this.doMakeDirty();
}
/**
*
*/
protected void changeButtonEnablement()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (buttonRemove != null)
{
buttonRemove.setEnabled(!selection.isEmpty());
}
if (buttonEdit != null)
{
buttonEdit.setEnabled(selection.size() == 1);
}
}
/**
* Opens a dialog for formula processing and returns the edited formula
* @param formula initial formula, can be <code>null</code>
* @return result of editing or <code>null</code>, if editing canceled
*/
protected Formula doEditFormula(Formula formula)
{
// Create the wizard
FormulaWizard wizard = new FormulaWizard(getSection().getText(), getSection().getDescription());
wizard.setFormula(formula);
// Create the wizard dialog
WizardDialog dialog = new WizardDialog(getTableViewer().getTable().getShell(), wizard);
dialog.setHelpAvailable(true);
// Open the wizard dialog
if (Window.OK == dialog.open())
{
return wizard.getFormula();
} else
{
return null;
}
}
/**
* Marks the part dirty and hooks the validation method of the page
*/
protected void doMakeDirty()
{
this.validate();
this.markDirty();
}
/* (non-Javadoc)
* @see org.lamport.tla.toolbox.tool.tlc.ui.editor.validator.IValidateble#validate(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void validate()
{
page.validatePage(false);
}
}
| org.lamport.tla.toolbox.tool.tlc.ui/src/org/lamport/tla/toolbox/tool/tlc/ui/editor/part/ValidateableTableSectionPart.java | package org.lamport.tla.toolbox.tool.tlc.ui.editor.part;
import java.util.Vector;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.lamport.tla.toolbox.tool.tlc.model.Formula;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.page.BasicFormPage;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.provider.FormulaContentProvider;
import org.lamport.tla.toolbox.tool.tlc.ui.editor.provider.FormulaLabelProvider;
import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper;
import org.lamport.tla.toolbox.tool.tlc.ui.wizard.FormulaWizard;
/**
* Section part with table and add, edit and remove buttons
* @author Simon Zambrovski
* @version $Id: TableSectionPart.java 625 2009-04-07 04:04:58Z simonzam $
*/
public class ValidateableTableSectionPart extends SectionPart implements IValidateble
{
private BasicFormPage page;
// A TableViewer is the JFace object that seems to implement the
// thing that gets displayed on the screen. It has methods for
// adding and removing items and returning the list of all items
// (the latter is the getInput() method, which seems to be a weird
// name because it's the list of things added with the add() method).
protected TableViewer tableViewer;
private Button buttonAdd;
private Button buttonEdit;
private Button buttonRemove;
// a listener reacting on clicks
protected SelectionListener fSelectionListener = new SelectionAdapter() {
public void widgetSelected(SelectionEvent e)
{
Object source = e.getSource();
if (source == buttonAdd)
{
doAdd();
} else if (source == buttonRemove)
{
doRemove();
} else if (source == buttonEdit)
{
doEdit();
}
}
};
// a listener reacting on selection in the table viewer
protected ISelectionChangedListener fSelectionChangedListener = new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event)
{
Object source = event.getSource();
if (source == tableViewer)
{
changeButtonEnablement();
}
}
};
/**
* Constructor of the part without section flags
* @see ValidateableTableSectionPart#TableSectionPart(Composite, String, String, FormToolkit, int)
*/
public ValidateableTableSectionPart(Composite composite, String title, String description, FormToolkit toolkit,
BasicFormPage page, String sectionName)
{
this(composite, title, description, toolkit, Section.DESCRIPTION | Section.TITLE_BAR, page, sectionName);
}
/**
* Constructs the section part
* @param composite, parent composite
* @param title, part title
* @param description, part description
* @param toolkit, a toolkit for building controls
* @param sectionFlags, flags to be passed to the part during construction
* @param sectionName name of the section
*/
public ValidateableTableSectionPart(Composite composite, String title, String description, FormToolkit toolkit,
int sectionFlags, BasicFormPage page, String sectionName)
{
super(FormHelper.createSectionComposite(composite, title, description, toolkit, sectionFlags, null));
this.page = page;
page.getDataBindingManager().bindSection(this, sectionName, page.getId());
}
/**
* Initialize the section
*/
public void initialize(IManagedForm form)
{
super.initialize(form);
sectionInitialize(form.getToolkit());
}
public void commit(boolean onSave)
{
// commit the part on save, but not on other events
if (onSave)
{
super.commit(onSave);
}
}
/**
* Constructs the section content
* @param toolkit
*/
protected void sectionInitialize(FormToolkit toolkit)
{
GridData gd;
// create the composite
Composite sectionArea = (Composite) getSection().getClient();
sectionArea.setLayout(new GridLayout(2, false));
// The section grabs the entire space
gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessVerticalSpace = true;
getSection().setLayoutData(gd);
// create the table
Table table = createTable(sectionArea, toolkit);
// The table grabs the entire space in the section
gd = new GridData(GridData.FILL_BOTH);
gd.grabExcessHorizontalSpace = true;
gd.grabExcessVerticalSpace = true;
// span for the buttons
gd.verticalSpan = 3;
table.setLayoutData(gd);
// create the table viewer
tableViewer = createTableViewer(table);
// create buttons
createButtons(sectionArea, toolkit, true, true, true);
// setup the buttons
changeButtonEnablement();
}
/**
* @param table
* @return
*/
protected TableViewer createTableViewer(Table table)
{
// create
CheckboxTableViewer tableViewer = new CheckboxTableViewer(table);
tableViewer.setLabelProvider(new FormulaLabelProvider());
// represent formulas in the view
tableViewer.setContentProvider(new FormulaContentProvider());
// on changed selection change button enablement
tableViewer.addSelectionChangedListener(fSelectionChangedListener);
// edit on double-click
tableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event)
{
doEdit();
}
});
// mark model dirty on checking / un-checking
tableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event)
{
doCheck();
}
});
return tableViewer;
}
/**
* Creates the table to be put into the tableviewer
* @param sectionArea
* @return
*/
protected Table createTable(Composite sectionArea, FormToolkit toolkit)
{
Table table = toolkit.createTable(sectionArea, SWT.MULTI | SWT.CHECK | SWT.V_SCROLL | SWT.H_SCROLL
| SWT.FULL_SELECTION);
table.setLinesVisible(false);
table.setHeaderVisible(false);
return table;
}
/**
* Creates buttons
* <br>
* Subclasses might override this method if they intend to change the buttons. For actual implementation see
* {@link ValidateableTableSectionPart#doCreateButtons(Composite, FormToolkit, boolean, boolean, boolean)}
*/
protected void createButtons(Composite sectionArea, FormToolkit toolkit, boolean add, boolean edit, boolean remove)
{
doCreateButtons(sectionArea, toolkit, add, edit, remove);
}
/**
* Create up to three buttons in the section area
* @param sectionArea
* @param toolkit
* @param add
* @param edit
* @param remove
*/
protected void doCreateButtons(Composite sectionArea, FormToolkit toolkit, boolean add, boolean edit, boolean remove)
{
GridData gd;
int added = 0;
if (add)
{
// add button
buttonAdd = toolkit.createButton(sectionArea, "Add", SWT.PUSH);
buttonAdd.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonAdd.setLayoutData(gd);
added++;
}
if (edit)
{
// edit button
buttonEdit = toolkit.createButton(sectionArea, "Edit", SWT.PUSH);
buttonEdit.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonEdit.setLayoutData(gd);
added++;
}
if (remove)
{
// remove button
buttonRemove = toolkit.createButton(sectionArea, "Remove", SWT.PUSH);
buttonRemove.addSelectionListener(fSelectionListener);
gd = new GridData();
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
buttonRemove.setLayoutData(gd);
added++;
}
if (added < 3)
{
Composite span = toolkit.createComposite(sectionArea);
gd = new GridData();
gd.verticalSpan = 3 - added;
gd.verticalAlignment = SWT.TOP;
gd.widthHint = 70;
span.setLayoutData(gd);
}
}
/**
* Retrieves the table viewer
* @return
*/
public TableViewer getTableViewer()
{
return tableViewer;
}
/**
* Remove the selected formulas
*/
protected void doRemove()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Vector input = (Vector) tableViewer.getInput();
input.removeAll(selection.toList());
tableViewer.setInput(input);
this.doMakeDirty();
}
/**
* Add a formula to the list
*/
protected void doAdd()
{
Formula formula = doEditFormula(null);
// add a formula
if (formula != null)
{
Vector input = ((Vector) tableViewer.getInput());
input.add(formula);
tableViewer.setInput(input);
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
this.doMakeDirty();
}
}
/**
* Edit selected formula
*/
protected void doEdit()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
Formula formula = (Formula) selection.getFirstElement();
Formula editedFormula = doEditFormula(formula);
if (editedFormula != null)
{
formula.setFormula(editedFormula.getFormula());
if (tableViewer instanceof CheckboxTableViewer)
{
((CheckboxTableViewer) tableViewer).setChecked(formula, true);
}
this.doMakeDirty();
tableViewer.refresh();
}
}
/**
* React on formula been checked or un-checked
*/
protected void doCheck()
{
this.doMakeDirty();
}
/**
*
*/
protected void changeButtonEnablement()
{
IStructuredSelection selection = (IStructuredSelection) tableViewer.getSelection();
if (buttonRemove != null)
{
buttonRemove.setEnabled(!selection.isEmpty());
}
if (buttonEdit != null)
{
buttonEdit.setEnabled(selection.size() == 1);
}
}
/**
* Opens a dialog for formula processing and returns the edited formula
* @param formula initial formula, can be <code>null</code>
* @return result of editing or <code>null</code>, if editing canceled
*/
protected Formula doEditFormula(Formula formula)
{
// Create the wizard
FormulaWizard wizard = new FormulaWizard(getSection().getText(), getSection().getDescription());
wizard.setFormula(formula);
// Create the wizard dialog
WizardDialog dialog = new WizardDialog(getTableViewer().getTable().getShell(), wizard);
dialog.setHelpAvailable(true);
// Open the wizard dialog
if (Window.OK == dialog.open())
{
return wizard.getFormula();
} else
{
return null;
}
}
/**
* Marks the part dirty and hooks the validation method of the page
*/
protected void doMakeDirty()
{
this.validate();
this.markDirty();
}
/* (non-Javadoc)
* @see org.lamport.tla.toolbox.tool.tlc.ui.editor.validator.IValidateble#validate(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void validate()
{
page.validatePage(false);
}
}
| Logically revert commit d787626d6f699f9faaae0c03d3f3ce517136403a
except for GTK where behaviour is fine.
[Refactor][Toolbox]
| org.lamport.tla.toolbox.tool.tlc.ui/src/org/lamport/tla/toolbox/tool/tlc/ui/editor/part/ValidateableTableSectionPart.java | Logically revert commit d787626d6f699f9faaae0c03d3f3ce517136403a except for GTK where behaviour is fine. |
|
Java | mit | 8fd9fe28e3f127932fae8252cc822c265f1af115 | 0 | PescaditoTeam/jrpg-2017a-dominio | package dominio;
/**
* Un tipo de raza que hereda las caracteristicas de Casta.
*
*/
public class Asesino extends Casta {
public Asesino(double prob_crit, double evasion, double daño_crit) {
super(prob_crit, evasion, daño_crit);
this.nombreCasta = "Asesino";
}
public Asesino() {
super();
this.nombreCasta = "Asesino";
habilidadesCasta = new String[3];
habilidadesCasta[0] = "Golpe Critico";
habilidadesCasta[1] = "Aumentar Evasion";
habilidadesCasta[2] = "Robar";
}
// Golpe Crítico
/*
* (non-Javadoc)
*
* @see dominio.Casta#habilidad1(dominio.Personaje, dominio.Peleable) Devuelve
* si el personaje que le pasamos tiene la habilidad pedida
*/
@Override
public boolean habilidad1(Personaje caster, Peleable atacado) {
if (caster.getEnergia() > 10) {
caster.setEnergia(caster.getEnergia() - 10);
if (atacado.serAtacado((int) (caster.ataque * caster.getCasta().getDañoCritico())) > 0) {
return true;
}
}
return false;
}
// Aumentar Evasion
@Override
public boolean habilidad2(Personaje caster, Peleable atacado) {
if (caster.getEnergia() > 10) {
caster.setEnergia(caster.getEnergia() - 10);
if ((this.getProbabilidadEvitarDaño() + 0.15) < 0.5) {
this.probabilidadEvitarDaño += 0.15;
} else {
this.probabilidadEvitarDaño = 0.5;
}
return true;
}
return false;
}
// Robar
@Override
public boolean habilidad3(Personaje caster, Peleable atacado) {
return false;
}
}
| src/main/java/dominio/Asesino.java | package dominio;
/**
* Un tipo de raza que hereda las caracteristicas de Casta
*
*/
public class Asesino extends Casta {
public Asesino(double prob_crit, double evasion, double daño_crit) {
super(prob_crit, evasion, daño_crit);
this.nombreCasta="Asesino";
}
public Asesino() {
super();
this.nombreCasta="Asesino";
habilidadesCasta = new String[3];
habilidadesCasta[0] = "Golpe Critico";
habilidadesCasta[1] = "Aumentar Evasion";
habilidadesCasta[2] = "Robar";
}
// Golpe Crítico
/* (non-Javadoc)
* @see dominio.Casta#habilidad1(dominio.Personaje, dominio.Peleable)
* Devuelve si el personaje que le pasamos tiene la habilidad pedida
*/
public boolean habilidad1(Personaje caster, Peleable atacado) {
if (caster.getEnergia() > 10) {
caster.setEnergia(caster.getEnergia() - 10);
if (atacado.serAtacado((int) (caster.ataque * caster.getCasta().getDañoCritico())) > 0)
return true;
}
return false;
}
// Aumentar Evasion
public boolean habilidad2(Personaje caster, Peleable atacado) {
if (caster.getEnergia() > 10) {
caster.setEnergia(caster.getEnergia() - 10);
if (this.getProbabilidadEvitarDaño() + 0.15 < 0.5)
this.probabilidadEvitarDaño += 0.15;
else
this.probabilidadEvitarDaño = 0.5;
return true;
}
return false;
}
// Robar
public boolean habilidad3(Personaje caster, Peleable atacado) {
return false;
}
}
| Check Asesino
| src/main/java/dominio/Asesino.java | Check Asesino |
|
Java | mit | 77b949dc9f83c649af750407b7fb3546bd638bd1 | 0 | SuperiozDE/MCUsernameChecker | package de.superioz.mcuc.scenes;
import de.superioz.mcuc.Main;
import de.superioz.mcuc.PremiumChecker;
import de.superioz.mcuc.UsernameVerifier;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import java.util.Timer;
import java.util.TimerTask;
/**
* Class created on 06.02.2015 at 20:14
*/
public class FunctionController {
// variables
public Main app;
// FXML variables
@FXML
private TextField textField;
@FXML
private Label resultLabel;
@FXML
private ProgressIndicator progressIndicator;
// setting mainapp to use
public void setMain(Main main){
this.app = main;
}
/*
checking if name is premium
*/
@FXML
public void handleCheckUsername(){
String givenName = textField.getText();
if(givenName.isEmpty()){
this.app.showError("Falsche Eingabe!", "Das Textfeld darf nicht leer bleiben, sonst kann nicht überprüft werden, ob der Spieler wirklich ein Premium User ist. Drücke 'Ok' um zur Applikation zurück zu kehren.");
return;
}
else if(!(UsernameVerifier.verifyUsername(givenName, this.app))){
return;
}
progressIndicator.setVisible(true);
final boolean[] isPremium = {false};
// setting timer to fade in text and chec the username in other thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
isPremium[0] = PremiumChecker.checkUsername(givenName, app);
// setting progress unvisible
progressIndicator.setVisible(false);
Platform.runLater(() -> {
// setting the result label
resultLabel.setVisible(true);
setResultLabel(isPremium[0]);
});
}
}, 60*25);
// setting timer to
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> resultLabel.setVisible(false));
}
}, 60*100);
}
public void setResultLabel(boolean isPremium){
if(isPremium){
resultLabel.setText("Der Username ist bereits vergeben.");
resultLabel.setTextFill(Color.RED);
}
else{
resultLabel.setText("Der Username ist noch frei.");
resultLabel.setTextFill(Color.GREEN);
}
}
}
| src/de/superioz/mcuc/scenes/FunctionController.java | package de.superioz.mcuc.scenes;
import de.superioz.mcuc.Main;
import de.superioz.mcuc.PremiumChecker;
import de.superioz.mcuc.UsernameVerifier;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import java.util.Timer;
import java.util.TimerTask;
/**
* Class created on 06.02.2015 at 20:14
*/
public class FunctionController {
// variables
public Main app;
// FXML variables
@FXML
private TextField textField;
@FXML
private Label resultLabel;
@FXML
private ProgressIndicator progressIndicator;
// Übergebe die Mainapp zum bearbeiten
public void setMain(Main main){
this.app = main;
}
/*
checking if name is premium
*/
@FXML
public void handleCheckUsername(){
String givenName = textField.getText();
if(givenName.isEmpty()){
this.app.showError("Falsche Eingabe!", "Das Textfeld darf nicht leer bleiben, sonst kann nicht überprüft werden, ob der Spieler wirklich ein Premium User ist. Drücke 'Ok' um zur Applikation zurück zu kehren.");
return;
}
else if(!(UsernameVerifier.verifyUsername(givenName, this.app))){
return;
}
progressIndicator.setVisible(true);
final boolean[] isPremium = {false};
// setting timer to fade in text and chec the username in other thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
isPremium[0] = PremiumChecker.checkUsername(givenName, app);
// setting progress unvisible
progressIndicator.setVisible(false);
Platform.runLater(() -> {
// setting the result label
resultLabel.setVisible(true);
setResultLabel(isPremium[0]);
});
}
}, 60*25);
// setting timer to
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> resultLabel.setVisible(false));
}
}, 60*100);
}
public void setResultLabel(boolean isPremium){
if(isPremium){
resultLabel.setText("Der Username ist bereits vergeben.");
resultLabel.setTextFill(Color.RED);
}
else{
resultLabel.setText("Der Username ist noch frei.");
resultLabel.setTextFill(Color.GREEN);
}
}
}
| Changed comments to english, for better understand.
| src/de/superioz/mcuc/scenes/FunctionController.java | Changed comments to english, for better understand. |
|
Java | mit | 55cc5116ce04d9d02b1f658eadb3ebe59f3e8dfb | 0 | weisJ/darklaf,weisJ/darklaf,weisJ/darklaf,weisJ/darklaf | /*
* MIT License
*
* Copyright (c) 2021 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.github.weisj.darklaf.properties.icons;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import com.github.weisj.darklaf.properties.PropertyLoader;
import com.github.weisj.darklaf.properties.parser.ParseResult;
import com.github.weisj.darklaf.properties.parser.Parser;
import com.github.weisj.darklaf.properties.parser.ParserContext;
import com.github.weisj.darklaf.util.ColorUtil;
import com.github.weisj.darklaf.util.LogUtil;
import com.github.weisj.darklaf.util.Pair;
import com.github.weisj.darklaf.util.Types;
import com.kitfox.svg.*;
import com.kitfox.svg.animation.AnimationElement;
import com.kitfox.svg.app.beans.SVGIcon;
import com.kitfox.svg.xml.StyleAttribute;
/** @author Jannis Weis */
public final class IconColorMapper {
private static final String INLINE_VALUE_PREFIX = "%";
private static final Logger LOGGER = LogUtil.getLogger(IconLoader.class);
private static final Color FALLBACK_COLOR = Color.RED;
public static void patchColors(final SVGIcon svgIcon) {
patchColors(svgIcon, UIManager.getDefaults());
}
public static void patchColors(final SVGIcon svgIcon, final Map<Object, Object> contextDefaults) {
patchColors(svgIcon, contextDefaults, null);
}
public static void patchColors(final SVGIcon svgIcon, final Map<Object, Object> defaults,
final Map<Object, Object> contextDefaults) {
SVGUniverse universe = svgIcon.getSvgUniverse();
SVGDiagram diagram = universe.getDiagram(svgIcon.getSvgURI());
LOGGER.finer(() -> "Patching colors of icon " + svgIcon.getSvgURI());
try {
loadColors(diagram, defaults, contextDefaults);
} catch (final SVGElementException e) {
LOGGER.log(Level.SEVERE, "Failed patching colors. " + e.getMessage(), e);
}
}
private static void loadColors(final SVGDiagram diagram, final Map<Object, Object> defaults,
final Map<Object, Object> contextDefaults)
throws SVGElementException {
SVGRoot root = diagram.getRoot();
SVGElement defs = diagram.getElement("colors");
if (defs == null) {
LOGGER.info(() -> {
String uri = diagram.getXMLBase().toASCIIString();
String name = uri.substring(Math.min(uri.lastIndexOf('/') + 1, uri.length() - 1));
return "Themed icon '" + name
+ "' has no color definitions. Consider loading it as a standard icon or add missing definitions";
});
return;
}
List<SVGElement> children = defs.getChildren(null);
root.removeChild(defs);
Defs themedDefs = new Defs();
themedDefs.addAttribute("id", AnimationElement.AT_XML, "colors");
root.loaderAddChild(null, themedDefs);
for (SVGElement child : children) {
if (child instanceof LinearGradient) {
LinearGradient grad = (LinearGradient) child;
String id = grad.getId();
StyleAttribute colorFallbacks = getAttribute("fallback", grad);
StyleAttribute opacityFallbacks = getAttribute("opacity-fallback", grad);
String opacityKey = getOpacityKey(grad);
float opacity = getOpacity(opacityKey, getFallbacks(opacityFallbacks), defaults, contextDefaults);
float opacity1 = opacity;
float opacity2 = opacity;
if (opacity < 0) {
opacity = 1;
int childCount = grad.getNumChildren();
if (childCount > 0) {
SVGElement elem = grad.getChild(0);
if (elem instanceof Stop) {
opacity1 = getStopOpacity((Stop) elem);
}
}
if (childCount > 1) {
SVGElement elem = grad.getChild(1);
if (elem instanceof Stop) {
opacity2 = getStopOpacity((Stop) elem);
}
}
if (opacity1 < 0) opacity1 = opacity;
if (opacity2 < 0) opacity2 = opacity;
}
Color c = resolveColor(id, getFallbacks(colorFallbacks), FALLBACK_COLOR, defaults, contextDefaults);
float finalOpacity1 = opacity1;
float finalOpacity2 = opacity2;
LOGGER.finest(() -> "Color: " + c + " opacity1: " + finalOpacity1 + " opacity2: " + finalOpacity2);
ColorResult result =
createColor(c, id, opacityKey, new StyleAttribute[] {colorFallbacks, opacityFallbacks},
finalOpacity2, opacity2);
themedDefs.loaderAddChild(null, result.gradient);
result.finalizer.run();
int resultRGB = ColorUtil.rgbNoAlpha(result.gradient.getStopColors()[0]);
int expectedRGB = ColorUtil.rgbNoAlpha(result.color);
if (expectedRGB != resultRGB) {
throw new IllegalStateException("Color not applied. Expected " + result.color + " but received "
+ result.gradient.getStopColors()[0] + " (rgb " + expectedRGB + " != " + resultRGB + ")");
}
LOGGER.finest(() -> Arrays.toString(result.gradient.getStopColors()));
}
}
LOGGER.fine("Patching done");
}
public static float getOpacity(final LinearGradient gradient, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
String opacityKey = getOpacityKey(gradient);
return getOpacity(opacityKey, null, propertyMap, contextDefaults);
}
public static Color getColor(final LinearGradient gradient, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
String id = (gradient).getId();
StyleAttribute fallbacks = getAttribute("fallback", gradient);
return resolveColor(id, getFallbacks(fallbacks), FALLBACK_COLOR, propertyMap, contextDefaults);
}
private static Color resolveColor(final String key, final String[] fallbacks, final Color fallbackColor,
final Map<Object, Object> propertyMap, final Map<Object, Object> contextDefaults) {
Color color = get(propertyMap, contextDefaults, key, fallbacks, Color.class);
if (color == null) {
color = fallbackColor;
LOGGER.warning("Could not load color with id '" + key + "' fallbacks" + Arrays.toString(fallbacks)
+ ". Using color '" + fallbackColor + "' instead.");
}
return color;
}
private static StyleAttribute getAttribute(final String key, final SVGElement child) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName(key);
try {
child.getStyle(attribute);
} catch (final SVGException e) {
return null;
}
return attribute;
}
private static float getStopOpacity(final Stop stop) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName("stop-opacity");
try {
stop.getStyle(attribute);
} catch (final SVGException e) {
return -1;
}
return !attribute.getStringValue().isEmpty() ? attribute.getFloatValue() : -1;
}
private static String[] getFallbacks(final StyleAttribute fallbacks) {
if (fallbacks == null) return new String[0];
return fallbacks.getStringList();
}
private static float getOpacity(final String key, final String[] fallbacks, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
if ((key == null || key.isEmpty()) && (fallbacks == null || fallbacks.length == 0)) return -1;
// UIManager defaults to 0, if the value isn't an integer (or null).
Number obj = get(propertyMap, contextDefaults, key, fallbacks, Number.class);
if (obj instanceof Integer) {
return obj.intValue() / 100.0f;
} else if (obj instanceof Long) {
return obj.intValue() / 100.0f;
} else if (obj instanceof Float) {
return obj.floatValue();
} else if (obj instanceof Double) {
return obj.floatValue();
}
LOGGER.warning(obj + " is an invalid opacity value. Key = '" + key + "'");
// In this case we default to -1.
return -1;
}
private static String getOpacityKey(final LinearGradient child) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName("opacity");
try {
child.getStyle(attribute);
} catch (final SVGException e) {
e.printStackTrace();
return null;
}
return attribute.getStringValue();
}
private static class ColorResult {
private final LinearGradient gradient;
private final Runnable finalizer;
private final Color color;
private ColorResult(LinearGradient gradient, Runnable finalizer, Color color) {
this.gradient = gradient;
this.finalizer = finalizer;
this.color = color;
}
}
private static ColorResult createColor(final Color c, final String name, final String opacityKey,
final StyleAttribute[] extraAttributes, final float opacity1, final float opacity2)
throws SVGElementException {
LinearGradient grad = new LinearGradient();
grad.addAttribute("id", AnimationElement.AT_XML, name);
if (opacityKey != null && !opacityKey.isEmpty()) {
grad.addAttribute("opacity", AnimationElement.AT_XML, opacityKey);
}
if (extraAttributes != null) {
for (StyleAttribute attribute : extraAttributes) {
if (attribute != null && !attribute.getStringValue().isEmpty()) {
grad.addAttribute(attribute.getName(), AnimationElement.AT_XML, attribute.getStringValue());
}
}
}
return new ColorResult(grad, () -> {
String color = toHexString(c);
BuildableStop stop1 = new BuildableStop(color);
BuildableStop stop2 = new BuildableStop(color);
try {
stop1.addAttribute("stop-color", AnimationElement.AT_XML, color);
stop1.addAttribute("offset", AnimationElement.AT_XML, "0");
stop2.addAttribute("stop-color", AnimationElement.AT_XML, color);
stop2.addAttribute("offset", AnimationElement.AT_XML, "1");
if (opacity1 != 1) {
stop1.addAttribute("stop-opacity", AnimationElement.AT_XML, String.valueOf(opacity1));
}
if (opacity2 != 1) {
stop2.addAttribute("stop-opacity", AnimationElement.AT_XML, String.valueOf(opacity2));
}
grad.loaderAddChild(null, stop1);
grad.loaderAddChild(null, stop2);
stop1.build();
stop2.build();
} catch (final SVGException e) {
throw new RuntimeException(e);
}
}, ColorUtil.toAlpha(c, opacity1));
}
private static class BuildableStop extends Stop {
private final String color;
private BuildableStop(final String color) {
this.color = color;
}
@Override
public boolean getStyle(StyleAttribute attrib, boolean recursive, boolean evalAnimation) throws SVGException {
if ("stop-color".equals(attrib.getName())) {
attrib.setStringValue(color);
return true;
}
return super.getStyle(attrib, recursive, evalAnimation);
}
@Override
protected void build() throws SVGException {
super.build();
}
}
public static Map<Object, Object> getProperties(final SVGIcon svgIcon) {
SVGUniverse universe = svgIcon.getSvgUniverse();
SVGDiagram diagram = universe.getDiagram(svgIcon.getSvgURI());
SVGElement defs = diagram.getElement("colors");
Map<Object, Object> values = new HashMap<>();
if (defs != null) {
List<SVGElement> children = defs.getChildren(null);
for (SVGElement child : children) {
if (child instanceof LinearGradient) {
LinearGradient grad = (LinearGradient) child;
String colorKey = grad.getId();
String opacityKey = getOpacityKey(grad);
SVGElement c = grad.getChild(0);
if (c instanceof Stop) {
Stop stop = (Stop) c;
StyleAttribute colorAttr = getAttribute("stop-color", stop);
Color color = colorAttr != null ? colorAttr.getColorValue() : null;
values.put(colorKey, color != null ? color : Color.BLACK);
if (opacityKey != null && !opacityKey.isEmpty()) {
StyleAttribute opacityAttr = getAttribute("stop-opacity", stop);
int opacity = opacityAttr != null ? (int) (100 * opacityAttr.getFloatValue()) : 100;
values.put(opacityKey, opacity);
}
}
}
}
}
return values;
}
public static <T> Pair<Object, T> getEntry(final Map<Object, Object> map, final Map<Object, Object> contextDefaults,
final Object key, final Object[] fallbacks, final Class<T> type) {
Object obj = null;
String refPrefix = PropertyLoader.getReferencePrefix();
Set<Object> seen = new HashSet<>();
Object currentKey = key;
int max = fallbacks != null ? fallbacks.length : 0;
outer: for (int i = -1; i < max; i++) {
currentKey = i < 0 ? key : fallbacks[i];
int retryCount = 5;
if (i >= 0 && currentKey instanceof String && ((String) currentKey).startsWith(INLINE_VALUE_PREFIX)) {
ParseResult p = Parser.parse(
Parser.createParseResult(Objects.toString(key),
((String) currentKey).substring(INLINE_VALUE_PREFIX.length())),
new ParserContext(map, contextDefaults, IconLoader.get()));
obj = Types.safeCast(p.result, type);
}
do {
if (obj == null) {
obj = map.get(currentKey);
}
if (contextDefaults != null && (obj == null || seen.contains(obj))) {
obj = contextDefaults.get(currentKey);
}
seen.add(obj);
if (obj instanceof String && obj.toString().startsWith(refPrefix)) {
currentKey = obj.toString().substring(refPrefix.length());
obj = null;
} else {
if (type.isInstance(obj)) {
// We found the value
break outer;
} else {
// Further search won't find anything.
// The value doesn't explicitly reference other keys.
continue outer;
}
}
retryCount--;
} while (retryCount > 0);
}
return new Pair<>(currentKey, type.cast(obj));
}
public static <T> T get(final Map<Object, Object> map, final Map<Object, Object> contextDefaults, final Object key,
final Object[] fallbacks, final Class<T> type) {
return getEntry(map, contextDefaults, key, fallbacks, type).getSecond();
}
private static String toHexString(final Color color) {
return "#" + ColorUtil.toHex(color);
}
}
| property-loader/src/main/java/com/github/weisj/darklaf/properties/icons/IconColorMapper.java | /*
* MIT License
*
* Copyright (c) 2021 Jannis Weis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.github.weisj.darklaf.properties.icons;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import com.github.weisj.darklaf.properties.PropertyLoader;
import com.github.weisj.darklaf.properties.parser.ParseResult;
import com.github.weisj.darklaf.properties.parser.Parser;
import com.github.weisj.darklaf.properties.parser.ParserContext;
import com.github.weisj.darklaf.util.ColorUtil;
import com.github.weisj.darklaf.util.LogUtil;
import com.github.weisj.darklaf.util.Pair;
import com.github.weisj.darklaf.util.Types;
import com.kitfox.svg.*;
import com.kitfox.svg.animation.AnimationElement;
import com.kitfox.svg.app.beans.SVGIcon;
import com.kitfox.svg.xml.StyleAttribute;
/** @author Jannis Weis */
public final class IconColorMapper {
private static final String INLINE_VALUE_PREFIX = "%";
private static final Logger LOGGER = LogUtil.getLogger(IconLoader.class);
private static final Color FALLBACK_COLOR = Color.RED;
public static void patchColors(final SVGIcon svgIcon) {
patchColors(svgIcon, UIManager.getDefaults());
}
public static void patchColors(final SVGIcon svgIcon, final Map<Object, Object> contextDefaults) {
patchColors(svgIcon, contextDefaults, null);
}
public static void patchColors(final SVGIcon svgIcon, final Map<Object, Object> defaults,
final Map<Object, Object> contextDefaults) {
SVGUniverse universe = svgIcon.getSvgUniverse();
SVGDiagram diagram = universe.getDiagram(svgIcon.getSvgURI());
LOGGER.finer(() -> "Patching colors of icon " + svgIcon.getSvgURI());
try {
loadColors(diagram, defaults, contextDefaults);
} catch (final SVGElementException e) {
LOGGER.log(Level.SEVERE, "Failed patching colors. " + e.getMessage(), e);
}
}
private static void loadColors(final SVGDiagram diagram, final Map<Object, Object> defaults,
final Map<Object, Object> contextDefaults)
throws SVGElementException {
SVGRoot root = diagram.getRoot();
SVGElement defs = diagram.getElement("colors");
if (defs == null) {
LOGGER.info(() -> {
String uri = diagram.getXMLBase().toASCIIString();
String name = uri.substring(Math.min(uri.lastIndexOf('/') + 1, uri.length() - 1));
return "Themed icon '" + name
+ "' has no color definitions. Consider loading it as a standard icon or add missing definitions";
});
return;
}
List<SVGElement> children = defs.getChildren(null);
root.removeChild(defs);
Defs themedDefs = new Defs();
themedDefs.addAttribute("id", AnimationElement.AT_XML, "colors");
root.loaderAddChild(null, themedDefs);
for (SVGElement child : children) {
if (child instanceof LinearGradient) {
LinearGradient grad = (LinearGradient) child;
String id = grad.getId();
StyleAttribute colorFallbacks = getAttribute("fallback", grad);
StyleAttribute opacityFallbacks = getAttribute("opacity-fallback", grad);
String opacityKey = getOpacityKey(grad);
float opacity = getOpacity(opacityKey, getFallbacks(opacityFallbacks), defaults, contextDefaults);
float opacity1 = opacity;
float opacity2 = opacity;
if (opacity < 0) {
opacity = 1;
int childCount = grad.getNumChildren();
if (childCount > 0) {
SVGElement elem = grad.getChild(0);
if (elem instanceof Stop) {
opacity1 = getStopOpacity((Stop) elem);
}
}
if (childCount > 1) {
SVGElement elem = grad.getChild(1);
if (elem instanceof Stop) {
opacity2 = getStopOpacity((Stop) elem);
}
}
if (opacity1 < 0) opacity1 = opacity;
if (opacity2 < 0) opacity2 = opacity;
}
Color c = resolveColor(id, getFallbacks(colorFallbacks), FALLBACK_COLOR, defaults, contextDefaults);
float finalOpacity1 = opacity1;
float finalOpacity2 = opacity2;
LOGGER.finest(() -> "Color: " + c + " opacity1: " + finalOpacity1 + " opacity2: " + finalOpacity2);
ColorResult result =
createColor(c, id, opacityKey, new StyleAttribute[] {colorFallbacks, opacityFallbacks},
finalOpacity2, opacity2);
themedDefs.loaderAddChild(null, result.gradient);
result.finalizer.run();
int resultRGB = ColorUtil.rgbNoAlpha(result.gradient.getStopColors()[0]);
int expectedRGB = ColorUtil.rgbNoAlpha(result.color);
if (expectedRGB != resultRGB) {
throw new IllegalStateException("Color not applied. Expected " + result.color + " but received "
+ result.gradient.getStopColors()[0] + " (rgb " + expectedRGB + " != " + resultRGB + ")");
}
LOGGER.finest(() -> Arrays.toString(result.gradient.getStopColors()));
}
}
LOGGER.fine("Patching done");
}
public static float getOpacity(final LinearGradient gradient, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
String opacityKey = getOpacityKey(gradient);
return getOpacity(opacityKey, null, propertyMap, contextDefaults);
}
public static Color getColor(final LinearGradient gradient, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
String id = (gradient).getId();
StyleAttribute fallbacks = getAttribute("fallback", gradient);
return resolveColor(id, getFallbacks(fallbacks), FALLBACK_COLOR, propertyMap, contextDefaults);
}
private static Color resolveColor(final String key, final String[] fallbacks, final Color fallbackColor,
final Map<Object, Object> propertyMap, final Map<Object, Object> contextDefaults) {
Color color = get(propertyMap, contextDefaults, key, fallbacks, Color.class);
if (color == null) {
color = fallbackColor;
LOGGER.warning("Could not load color with id '" + key + "' fallbacks" + Arrays.toString(fallbacks)
+ ". Using color '" + fallbackColor + "' instead.");
}
return color;
}
private static StyleAttribute getAttribute(final String key, final SVGElement child) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName(key);
try {
child.getStyle(attribute);
} catch (final SVGException e) {
return null;
}
return attribute;
}
private static float getStopOpacity(final Stop stop) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName("stop-opacity");
try {
stop.getStyle(attribute);
} catch (final SVGException e) {
return -1;
}
return !attribute.getStringValue().isEmpty() ? attribute.getFloatValue() : -1;
}
private static String[] getFallbacks(final StyleAttribute fallbacks) {
if (fallbacks == null) return new String[0];
return fallbacks.getStringList();
}
private static float getOpacity(final String key, final String[] fallbacks, final Map<Object, Object> propertyMap,
final Map<Object, Object> contextDefaults) {
if ((key == null || key.isEmpty()) && (fallbacks == null || fallbacks.length == 0)) return -1;
// UIManager defaults to 0, if the value isn't an integer (or null).
Number obj = get(propertyMap, contextDefaults, key, fallbacks, Number.class);
if (obj instanceof Integer) {
return obj.intValue() / 100.0f;
} else if (obj instanceof Long) {
return obj.intValue() / 100.0f;
} else if (obj instanceof Float) {
return obj.floatValue();
} else if (obj instanceof Double) {
return obj.floatValue();
}
LOGGER.warning(obj + " is an invalid opacity value. Key = '" + key + "'");
// In this case we default to -1.
return -1;
}
private static String getOpacityKey(final LinearGradient child) {
StyleAttribute attribute = new StyleAttribute();
attribute.setName("opacity");
try {
child.getStyle(attribute);
} catch (final SVGException e) {
e.printStackTrace();
return null;
}
return attribute.getStringValue();
}
private static class ColorResult {
private final LinearGradient gradient;
private final Runnable finalizer;
private final Color color;
private ColorResult(LinearGradient gradient, Runnable finalizer, Color color) {
this.gradient = gradient;
this.finalizer = finalizer;
this.color = color;
}
}
private static ColorResult createColor(final Color c, final String name, final String opacityKey,
final StyleAttribute[] extraAttributes, final float opacity1, final float opacity2)
throws SVGElementException {
LinearGradient grad = new LinearGradient();
grad.addAttribute("id", AnimationElement.AT_XML, name);
if (opacityKey != null && !opacityKey.isEmpty()) {
grad.addAttribute("opacity", AnimationElement.AT_XML, opacityKey);
}
if (extraAttributes != null) {
for (StyleAttribute attribute : extraAttributes) {
if (attribute != null && !attribute.getStringValue().isEmpty()) {
grad.addAttribute(attribute.getName(), AnimationElement.AT_XML, attribute.getStringValue());
}
}
}
return new ColorResult(grad, () -> {
String color = toHexString(c);
BuildableStop stop1 = new BuildableStop(color);
BuildableStop stop2 = new BuildableStop(color);
try {
stop1.addAttribute("stop-color", AnimationElement.AT_XML, color);
stop1.addAttribute("offset", AnimationElement.AT_XML, "0");
stop2.addAttribute("stop-color", AnimationElement.AT_XML, color);
stop2.addAttribute("offset", AnimationElement.AT_XML, "1");
if (opacity1 != 1) {
stop1.addAttribute("stop-opacity", AnimationElement.AT_XML, String.valueOf(opacity1));
}
if (opacity2 != 1) {
stop2.addAttribute("stop-opacity", AnimationElement.AT_XML, String.valueOf(opacity2));
}
grad.loaderAddChild(null, stop1);
grad.loaderAddChild(null, stop2);
stop1.build();
stop2.build();
} catch (final SVGException e) {
throw new RuntimeException(e);
}
}, ColorUtil.toAlpha(c, opacity1));
}
private static class BuildableStop extends Stop {
private final String color;
private BuildableStop(final String color) {
this.color = color;
}
@Override
public boolean getStyle(StyleAttribute attrib, boolean recursive, boolean evalAnimation) throws SVGException {
if ("stop-color".equals(attrib.getName())) {
attrib.setStringValue(color);
return true;
}
return super.getStyle(attrib, recursive, evalAnimation);
}
@Override
protected void build() throws SVGException {
super.build();
}
}
public static Map<Object, Object> getProperties(final SVGIcon svgIcon) {
SVGUniverse universe = svgIcon.getSvgUniverse();
SVGDiagram diagram = universe.getDiagram(svgIcon.getSvgURI());
SVGElement defs = diagram.getElement("colors");
Map<Object, Object> values = new HashMap<>();
if (defs != null) {
List<SVGElement> children = defs.getChildren(null);
for (SVGElement child : children) {
if (child instanceof LinearGradient) {
LinearGradient grad = (LinearGradient) child;
String colorKey = grad.getId();
String opacityKey = getOpacityKey(grad);
SVGElement c = grad.getChild(0);
if (c instanceof Stop) {
Stop stop = (Stop) c;
StyleAttribute colorAttr = getAttribute("stop-color", stop);
Color color = colorAttr != null ? colorAttr.getColorValue() : null;
values.put(colorKey, color != null ? color : Color.BLACK);
if (opacityKey != null && !opacityKey.isEmpty()) {
StyleAttribute opacityAttr = getAttribute("stop-opacity", stop);
int opacity = opacityAttr != null ? (int) (100 * opacityAttr.getFloatValue()) : 100;
values.put(opacityKey, opacity);
}
}
}
}
}
return values;
}
public static <T> Pair<Object, T> getEntry(final Map<Object, Object> map, final Map<Object, Object> contextDefaults,
final Object key, final Object[] fallbacks, final Class<T> type) {
Object obj = null;
String refPrefix = PropertyLoader.getReferencePrefix();
Set<Object> seen = new HashSet<>();
Object currentKey = key;
int max = fallbacks != null ? fallbacks.length : 0;
for (int i = -1; i < max; i++) {
currentKey = i < 0 ? key : fallbacks[i];
int retryCount = 5;
if (i >= 0 && currentKey instanceof String && ((String) currentKey).startsWith(INLINE_VALUE_PREFIX)) {
ParseResult p = Parser.parse(
Parser.createParseResult(Objects.toString(key),
((String) currentKey).substring(INLINE_VALUE_PREFIX.length())),
new ParserContext(map, contextDefaults, IconLoader.get()));
obj = Types.safeCast(p.result, type);
}
do {
if (obj == null) {
obj = map.get(currentKey);
}
if (contextDefaults != null && (obj == null || seen.contains(obj))) {
obj = contextDefaults.get(currentKey);
}
seen.add(obj);
if (obj instanceof String && obj.toString().startsWith(refPrefix)) {
currentKey = obj.toString().substring(refPrefix.length());
obj = null;
}
retryCount--;
} while (!(type.isInstance(obj)) && retryCount > 0);
if (retryCount > 0) break;
}
return new Pair<>(currentKey, type.cast(obj));
}
public static <T> T get(final Map<Object, Object> map, final Map<Object, Object> contextDefaults, final Object key,
final Object[] fallbacks, final Class<T> type) {
return getEntry(map, contextDefaults, key, fallbacks, type).getSecond();
}
private static String toHexString(final Color color) {
return "#" + ColorUtil.toHex(color);
}
}
| Icon: Break early if no value match is found
| property-loader/src/main/java/com/github/weisj/darklaf/properties/icons/IconColorMapper.java | Icon: Break early if no value match is found |
|
Java | mit | 0fc8c3dd4fb03de9292f9818710c007d992ff990 | 0 | michelfernandes/crescer-2016-1,michelfernandes/crescer-2016-1,michelfernandes/crescer-2016-1,michelfernandes/crescer-2016-1 | /**
* Escreva a descrição da classe Dwarf aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Dwarf
{
// variáveis de instância - substitua o exemplo abaixo pelo seu próprio
private String nome;
private int vida=110,experiencia=0;
private Status status = Status.VIVO;
private Inventario inv = new Inventario();
private DataTerceiraEra dataNascimento = new DataTerceiraEra(1,1,1);
public Dwarf(){
}
public Dwarf(String nome){
this.nome=nome;
}
public Dwarf(String nome, DataTerceiraEra data){
this.dataNascimento=data;
this.nome=nome;
}
public void anaoPerdeVida (){
double a = getNumeroSorte();
if(a<0){
this.experiencia += 2;
}else if(a<=100){
//não faz nada
}else{
if(status != Status.MORTO)this.vida = this.vida-10;
if(this.vida==0) status = Status.MORTO;
}
}
public void setNome(String novoNome){
this.nome=novoNome;
}
public String getNome(){
return this.nome;
}
public int getVida(){
return this.vida;
}
public Status getStatus(){
return status;
}
public int getDia(){
return dataNascimento.getDia();
}
public int getMes(){
return dataNascimento.getMes();
}
public int getAno(){
return dataNascimento.getAno();
}
public double getNumeroSorte(){
if(dataNascimento.ehBissexto()==true && this.vida>=80 && this.vida<=90){
return (-33*101.0);
}
if(dataNascimento.ehBissexto()==false && this.nome=="Seixas" || this.nome=="Meireles"){
return (101*33)%100;
}
return 101.0;
}
} | src/modulo-01-java-OO/projeto-lotr-bluej/Dwarf.java | /**
* Escreva a descrição da classe Dwarf aqui.
*
* @author (seu nome)
* @version (número de versão ou data)
*/
public class Dwarf
{
// variáveis de instância - substitua o exemplo abaixo pelo seu próprio
private String nome;
private int vida=110;
private Status status = Status.VIVO;
private Inventario inv = new Inventario();
private DataTerceiraEra dataNascimento = new DataTerceiraEra(1,1,1);
public Dwarf(){
}
public Dwarf(String nome){
this.nome=nome;
}
public Dwarf(String nome, DataTerceiraEra data){
this.dataNascimento=data;
this.nome=nome;
}
public void anaoPerdeVida (){
if(status != Status.MORTO)this.vida = this.vida-10;
if(this.vida==0) status = Status.MORTO;
}
public void setNome(String novoNome){
this.nome=novoNome;
}
public String getNome(){
return this.nome;
}
public int getVida(){
return this.vida;
}
public Status getStatus(){
return status;
}
public int getDia(){
return dataNascimento.getDia();
}
public int getMes(){
return dataNascimento.getMes();
}
public int getAno(){
return dataNascimento.getAno();
}
public double getNumeroSorte(){
if(dataNascimento.ehBissexto()==true && this.vida>=80 && this.vida<=90){
return (-33*101.0);
}
if(dataNascimento.ehBissexto()==false && this.nome=="Seixas" || this.nome=="Meireles"){
return (101*33)%100;
}
return 101.0;
}
} | feat(Dwarf): implementar chamada do método getNumeroSorte dentro do método anaoPerdeVida
| src/modulo-01-java-OO/projeto-lotr-bluej/Dwarf.java | feat(Dwarf): implementar chamada do método getNumeroSorte dentro do método anaoPerdeVida |
|
Java | epl-1.0 | 858a0b24590e30ebb8f2f788bc3580ee64bab991 | 0 | my76128/controller,Johnson-Chou/test,my76128/controller,opendaylight/controller,Sushma7785/OpenDayLight-Load-Balancer,aryantaheri/monitoring-controller,inocybe/odl-controller,mandeepdhami/controller,mandeepdhami/controller,tx1103mark/controller,aryantaheri/monitoring-controller,my76128/controller,mandeepdhami/controller,522986491/controller,aryantaheri/monitoring-controller,522986491/controller,my76128/controller,tx1103mark/controller,Johnson-Chou/test,tx1103mark/controller,mandeepdhami/controller,inocybe/odl-controller,Sushma7785/OpenDayLight-Load-Balancer,aryantaheri/monitoring-controller,tx1103mark/controller | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.binding.impl;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException;
import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper;
import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.binding.BaseIdentity;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
// cache of proxy objects where each value in the map corresponds to a specific RpcService
private final LoadingCache<Class<? extends RpcService>, RpcService> publicProxies = CacheBuilder.newBuilder().weakKeys().
build(new CacheLoader<Class<? extends RpcService>, RpcService>() {
@Override
public RpcService load(final Class<? extends RpcService> type) {
final RpcService proxy = rpcFactory.getDirectProxyFor(type);
LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
return proxy;
}
});
private final Cache<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = CacheBuilder.newBuilder().weakKeys()
.build();
private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
.create();
private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
private final String name;
private final ListenerRegistry<GlobalRpcRegistrationListener> globalRpcListeners = ListenerRegistry.create();
public String getName() {
return name;
}
public RpcProviderRegistryImpl(final String name) {
super();
this.name = name;
}
@Override
public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(final Class<T> type,
final T implementation) throws IllegalStateException {
return getRpcRouter(type).addRoutedRpcImplementation(implementation);
}
@Override
public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation)
throws IllegalStateException {
// FIXME: This should be well documented - addRpcImplementation for
// routed RPCs
try {
// Note: If RPC is really global, expected count of registrations
// of this method is really low.
RpcRouter<T> potentialRouter = getRpcRouter(type);
checkState(potentialRouter.getDefaultService() == null,
"Default service for routed RPC already registered.");
return potentialRouter.registerDefaultService(implementation);
} catch (RpcIsNotRoutedException e) {
// NOOP - we could safely continue, since RPC is not routed
// so we fallback to global routing.
LOG.debug("RPC is not routed. Using global registration.",e);
}
T publicProxy = getRpcService(type);
RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
checkState(currentDelegate == null, "Rpc service is already registered");
LOG.debug("Registering {} as global implementation of {} in {}", implementation, type.getSimpleName(), this);
RuntimeCodeHelper.setDelegate(publicProxy, implementation);
notifyGlobalRpcAdded(type);
return new RpcProxyRegistration<T>(type, implementation, this);
}
@SuppressWarnings("unchecked")
@Override
public final <T extends RpcService> T getRpcService(final Class<T> type) {
return (T) publicProxies.getUnchecked(type);
}
public <T extends RpcService> RpcRouter<T> getRpcRouter(final Class<T> type) {
try {
final AtomicBoolean created = new AtomicBoolean(false);
@SuppressWarnings( "unchecked")
// LoadingCache is unsuitable for RpcRouter since we need to distinguish
// first creation of RPC Router, so that is why
// we are using normal cache with load API and shared AtomicBoolean
// for this call, which will be set to true if router was created.
RpcRouter<T> router = (RpcRouter<T>) rpcRouters.get(type,new Callable<RpcRouter<?>>() {
@Override
public org.opendaylight.controller.sal.binding.api.rpc.RpcRouter<?> call() {
RpcRouter<?> router = rpcFactory.getRouterFor(type, name);
router.registerRouteChangeListener(new RouteChangeForwarder<T>(type));
LOG.debug("Registering router {} as global implementation of {} in {}", router, type.getSimpleName(), this);
RuntimeCodeHelper.setDelegate(getRpcService(type), router.getInvocationProxy());
created.set(true);
return router;
}
});
if(created.get()) {
notifyListenersRoutedCreated(router);
}
return router;
} catch (ExecutionException | UncheckedExecutionException e) {
// We rethrow Runtime Exceptions which were wrapped by
// Execution Exceptions
// otherwise we throw IllegalStateException with original
Throwables.propagateIfPossible(e.getCause());
throw new IllegalStateException("Could not load RPC Router for "+type.getName(),e);
}
}
private void notifyGlobalRpcAdded(final Class<? extends RpcService> type) {
for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
try {
listener.getInstance().onGlobalRpcRegistered(type);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
}
}
private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
try {
listener.getInstance().onRpcRouterCreated(router);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
}
}
public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
final RouterInstantiationListener listener) {
ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
try {
for (RpcRouter<?> router : rpcRouters.asMap().values()) {
listener.onRpcRouterCreated(router);
}
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
return reg;
}
@SuppressWarnings("unchecked")
@Override
public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
final L listener) {
return (ListenerRegistration<L>) routeChangeListeners.register(listener);
}
public RuntimeCodeGenerator getRpcFactory() {
return rpcFactory;
}
public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
this.rpcFactory = rpcFactory;
}
public interface RouterInstantiationListener extends EventListener {
void onRpcRouterCreated(RpcRouter<?> router);
}
public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(final GlobalRpcRegistrationListener listener) {
return globalRpcListeners.register(listener);
}
public interface GlobalRpcRegistrationListener extends EventListener {
void onGlobalRpcRegistered(Class<? extends RpcService> cls);
void onGlobalRpcUnregistered(Class<? extends RpcService> cls);
}
private final class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
private final Class<T> type;
RouteChangeForwarder(final Class<T> type) {
this.type = type;
}
@Override
public void onRouteChange(final RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
.entrySet()) {
RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
announcements.put(key, entry.getValue());
}
Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
.entrySet()) {
RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
removals.put(key, entry.getValue());
}
RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
.<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
try {
listener.getInstance().onRouteChange(toPublish);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener",listener.getInstance(),e);
}
}
}
}
private static final class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
private final RpcProviderRegistryImpl registry;
private final Class<T> serviceType;
RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
super(service);
this.registry = Preconditions.checkNotNull(registry);
this.serviceType = type;
}
@Override
public Class<T> getServiceType() {
return serviceType;
}
@Override
protected void removeRegistration() {
T publicProxy = registry.getRpcService(serviceType);
RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
if (currentDelegate == getInstance()) {
RuntimeCodeHelper.setDelegate(publicProxy, null);
}
}
}
}
| opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RpcProviderRegistryImpl.java | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.binding.impl;
import static com.google.common.base.Preconditions.checkState;
import java.util.EventListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
import org.opendaylight.controller.sal.binding.codegen.RpcIsNotRoutedException;
import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator;
import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper;
import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.util.ListenerRegistry;
import org.opendaylight.yangtools.yang.binding.BaseIdentity;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;
public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
// cache of proxy objects where each value in the map corresponds to a specific RpcService
private final LoadingCache<Class<? extends RpcService>, RpcService> publicProxies = CacheBuilder.newBuilder().weakKeys().
build(new CacheLoader<Class<? extends RpcService>, RpcService>() {
@Override
public RpcService load(final Class<? extends RpcService> type) {
final RpcService proxy = rpcFactory.getDirectProxyFor(type);
LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
return proxy;
}
});
private final Cache<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = CacheBuilder.newBuilder().weakKeys()
.build();
private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
.create();
private final ListenerRegistry<RouterInstantiationListener> routerInstantiationListener = ListenerRegistry.create();
private final static Logger LOG = LoggerFactory.getLogger(RpcProviderRegistryImpl.class);
private final String name;
private final ListenerRegistry<GlobalRpcRegistrationListener> globalRpcListeners = ListenerRegistry.create();
public String getName() {
return name;
}
public RpcProviderRegistryImpl(final String name) {
super();
this.name = name;
}
@Override
public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(final Class<T> type,
final T implementation) throws IllegalStateException {
return getRpcRouter(type).addRoutedRpcImplementation(implementation);
}
@Override
public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation)
throws IllegalStateException {
// FIXME: This should be well documented - addRpcImplementation for
// routed RPCs
try {
// Note: If RPC is really global, expected count of registrations
// of this method is really low.
RpcRouter<T> potentialRouter = getRpcRouter(type);
checkState(potentialRouter.getDefaultService() == null,
"Default service for routed RPC already registered.");
return potentialRouter.registerDefaultService(implementation);
} catch (RpcIsNotRoutedException e) {
// NOOP - we could safely continue, since RPC is not routed
// so we fallback to global routing.
LOG.debug("RPC is not routed. Using global registration.",e);
}
T publicProxy = getRpcService(type);
RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
checkState(currentDelegate == null, "Rpc service is already registered");
LOG.debug("Registering {} as global implementation of {} in {}", implementation, type.getSimpleName(), this);
RuntimeCodeHelper.setDelegate(publicProxy, implementation);
notifyGlobalRpcAdded(type);
return new RpcProxyRegistration<T>(type, implementation, this);
}
@SuppressWarnings("unchecked")
@Override
public final <T extends RpcService> T getRpcService(final Class<T> type) {
return (T) publicProxies.getUnchecked(type);
}
public <T extends RpcService> RpcRouter<T> getRpcRouter(final Class<T> type) {
try {
final AtomicBoolean created = new AtomicBoolean(false);
@SuppressWarnings( "unchecked")
// LoadingCache is unsuitable for RpcRouter since we need to distinguish
// first creation of RPC Router, so that is why
// we are using normal cache with load API and shared AtomicBoolean
// for this call, which will be set to true if router was created.
RpcRouter<T> router = (RpcRouter<T>) rpcRouters.get(type,new Callable<RpcRouter<?>>() {
@Override
public org.opendaylight.controller.sal.binding.api.rpc.RpcRouter<?> call() {
RpcRouter<?> router = rpcFactory.getRouterFor(type, name);
router.registerRouteChangeListener(new RouteChangeForwarder<T>(type));
LOG.debug("Registering router {} as global implementation of {} in {}", router, type.getSimpleName(), this);
RuntimeCodeHelper.setDelegate(getRpcService(type), router.getInvocationProxy());
created.set(true);
return router;
}
});
if(created.get()) {
notifyListenersRoutedCreated(router);
}
return router;
} catch (ExecutionException | UncheckedExecutionException e) {
// We rethrow Runtime Exceptions which were wrapped by
// Execution Exceptions
// otherwise we throw IllegalStateException with original
Throwables.propagateIfPossible(e.getCause());
throw new IllegalStateException("Could not load RPC Router for "+type.getName(),e);
}
}
private void notifyGlobalRpcAdded(final Class<? extends RpcService> type) {
for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
try {
listener.getInstance().onGlobalRpcRegistered(type);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
}
}
private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
try {
listener.getInstance().onRpcRouterCreated(router);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
}
}
public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
final RouterInstantiationListener listener) {
ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
try {
for (RpcRouter<?> router : rpcRouters.asMap().values()) {
listener.onRpcRouterCreated(router);
}
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener {}", e);
}
return reg;
}
@SuppressWarnings("unchecked")
@Override
public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
final L listener) {
return (ListenerRegistration<L>) routeChangeListeners.register(listener);
}
public RuntimeCodeGenerator getRpcFactory() {
return rpcFactory;
}
public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
this.rpcFactory = rpcFactory;
}
public interface RouterInstantiationListener extends EventListener {
void onRpcRouterCreated(RpcRouter<?> router);
}
public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(final GlobalRpcRegistrationListener listener) {
return globalRpcListeners.register(listener);
}
public interface GlobalRpcRegistrationListener extends EventListener {
void onGlobalRpcRegistered(Class<? extends RpcService> cls);
void onGlobalRpcUnregistered(Class<? extends RpcService> cls);
}
private class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
private final Class<T> type;
public RouteChangeForwarder(final Class<T> type) {
this.type = type;
}
@Override
public void onRouteChange(final RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
.entrySet()) {
RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
announcements.put(key, entry.getValue());
}
Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> removals = new HashMap<>();
for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getRemovals()
.entrySet()) {
RpcContextIdentifier key = RpcContextIdentifier.contextFor(type, entry.getKey());
removals.put(key, entry.getValue());
}
RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> toPublish = RoutingUtils
.<RpcContextIdentifier, InstanceIdentifier<?>> change(announcements, removals);
for (ListenerRegistration<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> listener : routeChangeListeners) {
try {
listener.getInstance().onRouteChange(toPublish);
} catch (Exception e) {
LOG.error("Unhandled exception during invoking listener",listener.getInstance(),e);
}
}
}
}
public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
private final Class<T> serviceType;
private RpcProviderRegistryImpl registry;
public RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
super(service);
this.serviceType = type;
this.registry = registry;
}
@Override
public Class<T> getServiceType() {
return serviceType;
}
@Override
protected void removeRegistration() {
if (registry != null) {
T publicProxy = registry.getRpcService(serviceType);
RpcService currentDelegate = RuntimeCodeHelper.getDelegate(publicProxy);
if (currentDelegate == getInstance()) {
RuntimeCodeHelper.setDelegate(publicProxy, null);
}
registry = null;
}
}
}
}
| Registry instance cannot be null in RpcProxyRegistration
removeRegistration() is guaranteed to be invoked at most once, and
registry cannot be null. Make it final and remove the safety check.
Change-Id: Ie8f2da7430c076d0bec71eb8b58a4adc2af25adf
Signed-off-by: Robert Varga <[email protected]>
| opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RpcProviderRegistryImpl.java | Registry instance cannot be null in RpcProxyRegistration |
|
Java | agpl-3.0 | 89892284fceaba68bd87792ba68332f781bc23a5 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | f47030fa-2e5f-11e5-9284-b827eb9e62be | hello.java | f46aa964-2e5f-11e5-9284-b827eb9e62be | f47030fa-2e5f-11e5-9284-b827eb9e62be | hello.java | f47030fa-2e5f-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | a64631932ce901625b4e9bb96044e1a666e8e517 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | a1ed2eb4-2e5f-11e5-9284-b827eb9e62be | hello.java | a1e7c6fe-2e5f-11e5-9284-b827eb9e62be | a1ed2eb4-2e5f-11e5-9284-b827eb9e62be | hello.java | a1ed2eb4-2e5f-11e5-9284-b827eb9e62be |
|
Java | agpl-3.0 | e1cc1aa2db4ad3dae603f69cc1d31b699a682319 | 0 | Asqatasun/Asqatasun,Asqatasun/Asqatasun,Tanaguru/Tanaguru,dzc34/Asqatasun,medsob/Tanaguru,dzc34/Asqatasun,medsob/Tanaguru,Tanaguru/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,medsob/Tanaguru,Tanaguru/Tanaguru,dzc34/Asqatasun,Tanaguru/Tanaguru,Asqatasun/Asqatasun,medsob/Tanaguru,Asqatasun/Asqatasun | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2013 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.controller;
import java.io.IOException;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.AuditStatus;
import org.opens.tanaguru.entity.audit.ProcessResult;
import org.opens.tanaguru.entity.audit.SSP;
import org.opens.tanaguru.entity.reference.Criterion;
import org.opens.tanaguru.entity.reference.Test;
import org.opens.tanaguru.entity.service.audit.AuditDataService;
import org.opens.tanaguru.entity.service.audit.ProcessResultDataService;
import org.opens.tanaguru.entity.service.reference.CriterionDataService;
import org.opens.tanaguru.entity.service.statistics.CriterionStatisticsDataService;
import org.opens.tanaguru.entity.subject.Page;
import org.opens.tanaguru.entity.subject.Site;
import org.opens.tanaguru.entity.subject.WebResource;
import org.opens.tgol.action.voter.ActionHandler;
import org.opens.tgol.command.AuditResultSortCommand;
import org.opens.tgol.command.ManualAuditCommand;
import org.opens.tgol.command.factory.AuditResultSortCommandFactory;
import org.opens.tgol.command.factory.AuditSetUpCommandFactory;
import org.opens.tgol.entity.contract.Act;
import org.opens.tgol.entity.contract.Contract;
import org.opens.tgol.entity.contract.ScopeEnum;
import org.opens.tgol.entity.functionality.Functionality;
import org.opens.tgol.exception.ForbiddenPageException;
import org.opens.tgol.exception.ForbiddenUserException;
import org.opens.tgol.exception.LostInSpaceException;
import org.opens.tgol.form.CheckboxElement;
import org.opens.tgol.form.CheckboxFormFieldImpl;
import org.opens.tgol.form.FormField;
import org.opens.tgol.form.builder.FormFieldBuilder;
import org.opens.tgol.presentation.data.AuditStatistics;
import org.opens.tgol.presentation.data.TestResult;
import org.opens.tgol.presentation.factory.CriterionResultFactory;
import org.opens.tgol.presentation.factory.TestResultFactory;
import org.opens.tgol.presentation.highlighter.HtmlHighlighter;
import org.opens.tgol.util.HttpStatusCodeFamily;
import org.opens.tgol.util.TgolKeyStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
* @author jkowalczyk
*/
@Controller
public class AuditResultController extends AuditDataHandlerController {
private static final Logger LOGGER = Logger
.getLogger(AuditResultController.class);
private static final String CRITERION_RESULT_PAGE_KEY = "criterion-result";
private static final String REFERER_HEADER_KEY = "referer";
List<FormFieldBuilder> sortFormFieldBuilderList;
public final void setFormFieldBuilderList(
final List<FormFieldBuilder> formFieldBuilderList) {
this.sortFormFieldBuilderList = formFieldBuilderList;
}
private ActionHandler actionHandler;
public ActionHandler getActionHandler() {
return actionHandler;
}
public void setActionHandler(ActionHandler contractActionHandler) {
this.actionHandler = contractActionHandler;
}
private String themeSortKey;
public String getThemeSortKey() {
return themeSortKey;
}
public void setThemeSortKey(String themeSortKey) {
this.themeSortKey = themeSortKey;
}
private String testResultSortKey;
public String getTestResultSortKey() {
return testResultSortKey;
}
public void setTestResultSortKey(String testResultSortKey) {
this.testResultSortKey = testResultSortKey;
}
private String referentialCode = "referential";
public String getReferentialCode() {
return referentialCode;
}
public void setReferentialCode(String referentialCode) {
this.referentialCode = referentialCode;
}
private String levelParameterCode = "LEVEL";
public String getLevelParameterCode() {
return levelParameterCode;
}
public void setLevelParameterCode(String levelParameterCode) {
this.levelParameterCode = levelParameterCode;
}
private List<String> authorizedRefForCriterionViewList;
public List<String> getAuthorizedRefForCriterionViewList() {
return authorizedRefForCriterionViewList;
}
public void setAuthorizedRefForCriterionViewList(
List<String> authorizedRefForCriterionViewList) {
this.authorizedRefForCriterionViewList = authorizedRefForCriterionViewList;
}
private CriterionDataService criterionDataService;
public CriterionDataService getCriterionDataService() {
return criterionDataService;
}
@Autowired
public void setCriterionDataService(
CriterionDataService criterionDataService) {
this.criterionDataService = criterionDataService;
}
private CriterionStatisticsDataService criterionStatisticsDataService;
public CriterionStatisticsDataService getCriterionStatisticsDataService() {
return criterionStatisticsDataService;
}
@Autowired
public void setCriterionStatisticsDataService(
CriterionStatisticsDataService criterionStatisticsDataService) {
this.criterionStatisticsDataService = criterionStatisticsDataService;
}
@Autowired
private ProcessResultDataService processResultDataService;
public void setCriterionStatisticsDataService(
ProcessResultDataService processResultDataService) {
this.processResultDataService = processResultDataService;
}
@Autowired
private AuditDataService auditDataService;
public void setAudittDataService(
AuditDataService auditDataService) {
this.auditDataService = auditDataService;
}
/**
* The Html hightlighter.
*/
private HtmlHighlighter highlighter;
@Autowired
public void setHtmlHighlighter(HtmlHighlighter highlighter) {
this.highlighter = highlighter;
}
public AuditResultController() {
super();
}
/**
* General router when receive audit-result request. Regarding the scope of
* the audit, the returned page may differ.
*
* @param auditId
* @param request
* @param model
* @return
*/
@RequestMapping(value = TgolKeyStore.AUDIT_RESULT_CONTRACT_URL, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displayAuditResultFromContract(
@RequestParam(TgolKeyStore.AUDIT_ID_KEY) String auditId,
@RequestParam(value = TgolKeyStore.IS_MANUAL_AUDIT_KEY, required = false, defaultValue = "false") boolean manual,
HttpServletRequest request, Model model) {
try {
Audit audit = getAuditDataService().read(Long.valueOf(auditId));
Act act = getActDataService().getActFromAudit(audit);
switch (act.getScope().getCode()) {
case FILE:
case PAGE:
model.addAttribute(TgolKeyStore.WEBRESOURCE_ID_KEY, audit
.getSubject().getId());
model.addAttribute(TgolKeyStore.IS_MANUAL_AUDIT_KEY, manual);
if (manual) {
// appel au service
Contract contract = getContractDataService().read(
act.getContract().getId());
// controle sur le user si option manuel est activé
for (Functionality func : contract.getFunctionalitySet()) {
if (func.getId() == 5)
// model.addAttribute("resultAuditManualCommand",new
// ResultAuditManualCommand());
return TgolKeyStore.RESULT_PAGE_VIEW_REDIRECT_NAME;
}
return TgolKeyStore.ACCESS_DENIED_VIEW_NAME;
}
return TgolKeyStore.RESULT_PAGE_VIEW_REDIRECT_NAME;
case DOMAIN:
case SCENARIO:
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, auditId);
return TgolKeyStore.SYNTHESIS_SITE_VIEW_REDIRECT_NAME;
case GROUPOFFILES:
case GROUPOFPAGES:
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, auditId);
model.addAttribute(TgolKeyStore.STATUS_KEY,
HttpStatusCodeFamily.f2xx.name());
return TgolKeyStore.PAGE_LIST_XXX_VIEW_REDIRECT_NAME;
default:
throw new ForbiddenPageException();
}
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
}
/**
* @param webresourceId
* @param request
* @param model
* @return
*/
@RequestMapping(value = { TgolKeyStore.PAGE_RESULT_CONTRACT_URL,
TgolKeyStore.SITE_RESULT_CONTRACT_URL }, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displayPageResultFromContract(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(value = TgolKeyStore.IS_MANUAL_AUDIT_KEY) boolean manual,
HttpServletRequest request, Model model) {
Long webResourceIdValue;
try {
webResourceIdValue = Long.valueOf(webresourceId);
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
return dispatchDisplayResultRequest(webResourceIdValue, null, model,
request, manual);
}
/**
* @param manualAuditCommand
* @param auditResultSortCommand
* @param result
* @param model
* @param request
* @param webresourceId
* @return
*/
@RequestMapping(value=TgolKeyStore.PAGE_RESULT_CONTRACT_URL, method = RequestMethod.POST)
@Secured({TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY})
protected String submitPageResultSorter(
@ModelAttribute(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY) AuditResultSortCommand auditResultSortCommand,
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@ModelAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY) ManualAuditCommand manualAuditCommand,
BindingResult result,
Model model,
HttpServletRequest request) {
if(manualAuditCommand !=null){
return dispatchSubmitManualAuditValues(webresourceId,manualAuditCommand,result,model,request);
}else{
return dispatchDisplayResultRequest(
auditResultSortCommand.getWebResourceId(),
auditResultSortCommand,
model,
request,false);
}
}
private String dispatchSubmitManualAuditValues(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@ModelAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY) ManualAuditCommand manualAuditCommand,
BindingResult result,
Model model,
HttpServletRequest request) {
WebResource webResource;
try {
webResource = getWebResourceDataService().ligthRead(Long.valueOf(webresourceId));
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
if (webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)){
List<ProcessResult> processResultList=TestResultFactory.getInstance().getProcessResultListFromTestsResult(
new LinkedList<TestResult>(manualAuditCommand.getModifiedTestResultMap().values()), webResource);
processResultDataService.saveOrUpdate(processResultList);
/**
* if save the manual audit for the first time save
* we set the manual audit start time and status to MANUAL_INITIALIZING
*/
if(audit.getManualAuditDateOfCreation()==null){
audit.setManualAuditDateOfCreation(Calendar.getInstance().getTime());
audit.setStatus(AuditStatus.MANUAL_INITIALIZING);
auditDataService.update(audit);
}
return dispatchDisplayResultRequest(
webResource.getId(),
null,
model,
request,true);
}
else
throw new ForbiddenPageException();
}
/**
*
* @param webresourceId
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value = TgolKeyStore.SOURCE_CODE_CONTRACT_URL, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displaySourceCodeFromContract(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
HttpServletRequest request, HttpServletResponse response,
Model model) {
WebResource webResource;
try {
webResource = getWebResourceDataService().ligthRead(
Long.valueOf(webresourceId));
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
if (webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Page page = (Page) webResource;
SSP ssp = getContentDataService().findSSP(page, page.getURL());
model.addAttribute(TgolKeyStore.SOURCE_CODE_KEY,
highlightSourceCode(ssp));
ScopeEnum scope = getActDataService().getActFromAudit(audit)
.getScope().getCode();
if (scope.equals(ScopeEnum.GROUPOFPAGES)
|| scope.equals(ScopeEnum.PAGE)) {
model.addAttribute(TgolKeyStore.IS_GENERATED_HTML_KEY, true);
}
return TgolKeyStore.SOURCE_CODE_PAGE_VIEW_NAME;
} else {
throw new ForbiddenUserException(getCurrentUser());
}
}
/**
*
* @param model
* @return the test-result view name
*/
@RequestMapping(value = TgolKeyStore.CRITERION_RESULT_CONTRACT_URL, method = RequestMethod.GET)
public String displayCriterionResult(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(TgolKeyStore.CRITERION_CODE_KEY) String criterionId,
Model model) {
Long wrId;
Long critId;
try {
wrId = Long.valueOf(webresourceId);
critId = Long.valueOf(criterionId);
} catch (NumberFormatException nfe) {
throw new ForbiddenUserException(getCurrentUser());
}
WebResource webResource = getWebResourceDataService().ligthRead(wrId);
if (webResource == null || webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Contract contract = retrieveContractFromAudit(audit);
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY,
contract.getLabel());
model.addAttribute(TgolKeyStore.URL_KEY, webResource.getURL());
Criterion crit = criterionDataService.read(critId);
model.addAttribute(TgolKeyStore.CRITERION_LABEL_KEY,
crit.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
model.addAttribute(TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance()
.getTestResultListFromCriterion(webResource, crit));
return TgolKeyStore.CRITERION_RESULT_VIEW_NAME;
} else {
throw new ForbiddenPageException();
}
}
/**
*
* @param model
* @return the test-result view name
*/
@RequestMapping(value = TgolKeyStore.TEST_RESULT_CONTRACT_URL, method = RequestMethod.GET)
public String displayTestResult(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(TgolKeyStore.TEST_CODE_KEY) String testId, Model model) {
Long wrId;
Long tstId;
try {
wrId = Long.valueOf(webresourceId);
tstId = Long.valueOf(testId);
} catch (NumberFormatException nfe) {
throw new ForbiddenUserException(getCurrentUser());
}
WebResource webResource = getWebResourceDataService().ligthRead(wrId);
if (webResource == null) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Contract contract = retrieveContractFromAudit(audit);
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY,
contract.getLabel());
model.addAttribute(TgolKeyStore.URL_KEY, webResource.getURL());
Test test = getTestDataService().read(tstId);
model.addAttribute(TgolKeyStore.TEST_LABEL_KEY, test.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
if (!test.getScope().equals(getPageScope())) {
model.addAttribute(TgolKeyStore.SITE_SCOPE_TEST_DETAILS_KEY,
true);
} else {
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
}
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance().getTestResultListFromTest(
webResource, test));
return TgolKeyStore.TEST_RESULT_VIEW_NAME;
} else {
throw new ForbiddenPageException();
}
}
/**
* Regarding the page type, this method collects data, set them up and
* display the appropriate result page.
*
* @param webResourceId
* @param auditResultSortCommand
* @param model
* @param displayScope
* @param request
* @return
*/
private String dispatchDisplayResultRequest(Long webResourceId,
AuditResultSortCommand auditResultSortCommand, Model model,
HttpServletRequest request, boolean isManualAudit) {
// We first check that the current user is allowed to display the result
// of this audit
WebResource webResource = getWebResourceDataService().ligthRead(
webResourceId);
if (webResource == null) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
// If the Id given in argument correspond to a webResource,
// data are retrieved to be prepared and displayed
if (isUserAllowedToDisplayResult(audit)) {
this.callGc(webResource);
String displayScope = computeDisplayScope(request,
auditResultSortCommand);
// first we add statistics meta-data to model
addAuditStatisticsToModel(webResource, model, displayScope);
// The page is displayed with sort option. Form needs to be set up
prepareDataForSortConsole(webResourceId, displayScope,
auditResultSortCommand, model, isManualAudit);
// Data need to be prepared regarding the audit type
return prepareSuccessfullAuditData(webResource, audit, model,
displayScope, getLocaleResolver().resolveLocale(request),
isManualAudit);
} else {
throw new ForbiddenUserException(getCurrentUser());
}
}
/**
* This method prepares the data to be displayed in the sort (referential,
* theme, result types) console of the result page.
*
* @param webResourceId
* @param displayScope
* @param auditResultSortCommand
* @param model
* @param isManualAuit
*/
private void prepareDataForSortConsole(Long webResourceId,
String displayScope, AuditResultSortCommand auditResultSortCommand,
Model model, boolean isManualAuit) {
// Meta-statistics have been added to the method previously
String referentialParameter = ((AuditStatistics) model.asMap().get(
TgolKeyStore.STATISTICS_KEY)).getParametersMap().get(
referentialCode);
AuditResultSortCommand asuc;
List<FormField> formFieldList;
if (auditResultSortCommand == null) {
formFieldList = AuditResultSortCommandFactory.getInstance()
.getFormFieldBuilderCopy(referentialParameter,
sortFormFieldBuilderList);
if (isManualAuit) {
CheckboxFormFieldImpl ObjectList = (CheckboxFormFieldImpl) formFieldList
.get(1);
List<CheckboxElement> checkboxElementList = ObjectList
.getCheckboxElementList();
for (CheckboxElement checkboxElement : checkboxElementList) {
if (checkboxElement.getI18nKey().equals("nt")) {
checkboxElement.setSelected(true);
}
}
}
asuc = AuditResultSortCommandFactory.getInstance()
.getInitialisedAuditResultSortCommand(
webResourceId,
displayScope,
isCriterionViewAccessible(webResourceId,
referentialParameter), formFieldList);
} else {
formFieldList = AuditResultSortCommandFactory.getInstance()
.getFormFieldBuilderCopy(referentialParameter,
sortFormFieldBuilderList, auditResultSortCommand);
asuc = auditResultSortCommand;
}
model.addAttribute(TgolKeyStore.AUDIT_RESULT_SORT_FIELD_LIST_KEY,
formFieldList);
model.addAttribute(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY, asuc);
}
/**
*
* @param webResourceId
* @param referentialParameter
* @return whether the criterion view is accessible for the given
* referential
*/
private boolean isCriterionViewAccessible(Long webResourceId,
String referentialParameter) {
return authorizedRefForCriterionViewList.contains(referentialParameter)
&& criterionStatisticsDataService
.getCriterionStatisticsCountByWebResource(webResourceId) > 0;
}
/**
* Regarding the audit type, collect data needed by the view.
*
* @param webResource
* @param audit
* @param model
* @param locale
* @param exportFormat
* @return
* @throws IOException
*/
private String prepareSuccessfullAuditData(WebResource webResource,
Audit audit, Model model, String displayScope, Locale locale,
boolean isManualAudit) {
model.addAttribute(TgolKeyStore.LOCALE_KEY, locale);
if (webResource instanceof Site) {
return prepareSuccessfullSiteData((Site) webResource, audit, model);
} else if (webResource instanceof Page) {
// In case of display page result page, we need all data related
// with
// the page, that's why a deepRead is needed
return prepareSuccessfullPageData((Page) webResource, audit, model,
displayScope, isManualAudit);
}
throw new LostInSpaceException();
}
/**
* This methods handles audit data in case of the audit is of site type
*
* @param site
* @param audit
* @param model
* @return
* @throws IOException
*/
private String prepareSuccessfullSiteData(Site site, Audit audit,
Model model) {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model.asMap()
.get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance().getTestResultSortedByThemeMap(
site, getSiteScope(),
asuc.getSortOptionMap().get(themeSortKey).toString(),
getTestResultSortSelection(asuc)));
// Attributes for breadcrumb
Contract contract = retrieveContractFromAudit(audit);
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY, contract.getLabel());
model.addAttribute(TgolKeyStore.RESULT_ACTION_LIST_KEY,
actionHandler.getActionList("EXPORT"));
return TgolKeyStore.RESULT_SITE_VIEW_NAME;
}
/**
* This methods handles audit data in case of page type audit
*
* @param page
* @param audit
* @param model
* @param displayScope
* @return
* @throws IOException
*/
private String prepareSuccessfullPageData(Page page, Audit audit,
Model model, String displayScope, boolean isManualAudit) {
Contract contract = retrieveContractFromAudit(audit);
if (!audit.getStatus().equals(AuditStatus.COMPLETED)) {
return prepareFailedAuditData(audit, model);
}
model.addAttribute(TgolKeyStore.STATUS_KEY, computeAuditStatus(audit));
model.addAttribute(TgolKeyStore.RESULT_ACTION_LIST_KEY,
actionHandler.getActionList("EXPORT"));
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY, contract.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
// Add a command to relaunch the audit from the result page
model.addAttribute(
TgolKeyStore.AUDIT_SET_UP_COMMAND_KEY,
AuditSetUpCommandFactory.getInstance()
.getPageAuditSetUpCommand(
contract,
page.getURL(),
getParameterDataService()
.getParameterSetFromAudit(audit)));
if (StringUtils.equalsIgnoreCase(displayScope,
TgolKeyStore.TEST_DISPLAY_SCOPE_VALUE)) {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model
.asMap().get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance()
.getTestResultSortedByThemeMap(
page,
getPageScope(),
asuc.getSortOptionMap().get(themeSortKey)
.toString(),
getTestResultSortSelection(asuc)));
if (isManualAudit) {
ManualAuditCommand manualAudit=new ManualAuditCommand();
manualAudit.setModifedTestResultMap(TestResultFactory.getInstance().getTestResultMap(
page,
getPageScope(),
asuc.getSortOptionMap().get(themeSortKey).toString(),
getTestResultSortSelection(asuc)));
model.addAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY,manualAudit);
}
return TgolKeyStore.RESULT_PAGE_VIEW_NAME;
} else {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model
.asMap().get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.CRITERION_RESULT_LIST_KEY,
CriterionResultFactory.getInstance()
.getCriterionResultSortedByThemeMap(
page,
asuc.getSortOptionMap().get(themeSortKey)
.toString(),
getTestResultSortSelection(asuc)));
return TgolKeyStore.RESULT_PAGE_BY_CRITERION_VIEW_NAME;
}
}
private Collection<String> getTestResultSortSelection(
AuditResultSortCommand asuc) {
Collection<String> selectedValues = new HashSet<String>();
if ((asuc.getSortOptionMap().get(testResultSortKey)) instanceof Object[]) {
CollectionUtils.addAll(selectedValues, ((Object[]) asuc
.getSortOptionMap().get(testResultSortKey)));
} else if ((asuc.getSortOptionMap().get(testResultSortKey)) instanceof String) {
selectedValues.add((String) asuc.getSortOptionMap().get(
testResultSortKey));
}
return selectedValues;
}
/**
* This methods enforces the call of the Garbarge collector.
*
* @param webresource
*/
private void callGc(WebResource webresource) {
if (webresource != null && (webresource.getId() % 10) == 0) {
System.gc();
}
}
/**
* This methods call the highlighter service and returns the highlighted
* code.
*
* @param ssp
* @return
* @throws IOException
*/
private String highlightSourceCode(SSP ssp) {
if (ssp != null && StringUtils.isNotBlank(ssp.getDoctype())) {
return highlighter.highlightSourceCode(ssp.getDoctype(),
ssp.getAdaptedContent());
} else {
return highlighter.highlightSourceCode(ssp.getAdaptedContent());
}
}
/**
* Extract from the audit parameter the referential. Regarding this value,
* the returned page displays results sorted by tests or criterion
*
* @param request
* @param arsc
* @return
*/
private String computeDisplayScope(HttpServletRequest request,
AuditResultSortCommand arsc) {
if (StringUtils.contains(request.getHeader(REFERER_HEADER_KEY),
CRITERION_RESULT_PAGE_KEY)) {
return TgolKeyStore.CRITERION_DISPLAY_SCOPE_VALUE;
}
if (arsc != null) {
return arsc.getDisplayScope();
}
return TgolKeyStore.TEST_DISPLAY_SCOPE_VALUE;
}
} | web-app/tgol-web-app/src/main/java/org/opens/tgol/controller/AuditResultController.java | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2013 Open-S Company
*
* This file is part of Tanaguru.
*
* Tanaguru is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: open-s AT open-s DOT com
*/
package org.opens.tgol.controller;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.opens.tanaguru.entity.audit.Audit;
import org.opens.tanaguru.entity.audit.AuditStatus;
import org.opens.tanaguru.entity.audit.ProcessResult;
import org.opens.tanaguru.entity.audit.SSP;
import org.opens.tanaguru.entity.reference.Criterion;
import org.opens.tanaguru.entity.reference.Test;
import org.opens.tanaguru.entity.service.audit.ProcessResultDataService;
import org.opens.tanaguru.entity.service.reference.CriterionDataService;
import org.opens.tanaguru.entity.service.statistics.CriterionStatisticsDataService;
import org.opens.tanaguru.entity.subject.Page;
import org.opens.tanaguru.entity.subject.Site;
import org.opens.tanaguru.entity.subject.WebResource;
import org.opens.tgol.action.voter.ActionHandler;
import org.opens.tgol.command.AuditResultSortCommand;
import org.opens.tgol.command.ManualAuditCommand;
import org.opens.tgol.command.factory.AuditResultSortCommandFactory;
import org.opens.tgol.command.factory.AuditSetUpCommandFactory;
import org.opens.tgol.entity.contract.Act;
import org.opens.tgol.entity.contract.Contract;
import org.opens.tgol.entity.contract.ScopeEnum;
import org.opens.tgol.entity.functionality.Functionality;
import org.opens.tgol.exception.ForbiddenPageException;
import org.opens.tgol.exception.ForbiddenUserException;
import org.opens.tgol.exception.LostInSpaceException;
import org.opens.tgol.form.CheckboxElement;
import org.opens.tgol.form.CheckboxFormFieldImpl;
import org.opens.tgol.form.FormField;
import org.opens.tgol.form.builder.FormFieldBuilder;
import org.opens.tgol.presentation.data.AuditStatistics;
import org.opens.tgol.presentation.data.TestResult;
import org.opens.tgol.presentation.factory.CriterionResultFactory;
import org.opens.tgol.presentation.factory.TestResultFactory;
import org.opens.tgol.presentation.highlighter.HtmlHighlighter;
import org.opens.tgol.util.HttpStatusCodeFamily;
import org.opens.tgol.util.TgolKeyStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
*
* @author jkowalczyk
*/
@Controller
public class AuditResultController extends AuditDataHandlerController {
private static final Logger LOGGER = Logger
.getLogger(AuditResultController.class);
private static final String CRITERION_RESULT_PAGE_KEY = "criterion-result";
private static final String REFERER_HEADER_KEY = "referer";
List<FormFieldBuilder> sortFormFieldBuilderList;
public final void setFormFieldBuilderList(
final List<FormFieldBuilder> formFieldBuilderList) {
this.sortFormFieldBuilderList = formFieldBuilderList;
}
private ActionHandler actionHandler;
public ActionHandler getActionHandler() {
return actionHandler;
}
public void setActionHandler(ActionHandler contractActionHandler) {
this.actionHandler = contractActionHandler;
}
private String themeSortKey;
public String getThemeSortKey() {
return themeSortKey;
}
public void setThemeSortKey(String themeSortKey) {
this.themeSortKey = themeSortKey;
}
private String testResultSortKey;
public String getTestResultSortKey() {
return testResultSortKey;
}
public void setTestResultSortKey(String testResultSortKey) {
this.testResultSortKey = testResultSortKey;
}
private String referentialCode = "referential";
public String getReferentialCode() {
return referentialCode;
}
public void setReferentialCode(String referentialCode) {
this.referentialCode = referentialCode;
}
private String levelParameterCode = "LEVEL";
public String getLevelParameterCode() {
return levelParameterCode;
}
public void setLevelParameterCode(String levelParameterCode) {
this.levelParameterCode = levelParameterCode;
}
private List<String> authorizedRefForCriterionViewList;
public List<String> getAuthorizedRefForCriterionViewList() {
return authorizedRefForCriterionViewList;
}
public void setAuthorizedRefForCriterionViewList(
List<String> authorizedRefForCriterionViewList) {
this.authorizedRefForCriterionViewList = authorizedRefForCriterionViewList;
}
private CriterionDataService criterionDataService;
public CriterionDataService getCriterionDataService() {
return criterionDataService;
}
@Autowired
public void setCriterionDataService(
CriterionDataService criterionDataService) {
this.criterionDataService = criterionDataService;
}
private CriterionStatisticsDataService criterionStatisticsDataService;
public CriterionStatisticsDataService getCriterionStatisticsDataService() {
return criterionStatisticsDataService;
}
@Autowired
public void setCriterionStatisticsDataService(
CriterionStatisticsDataService criterionStatisticsDataService) {
this.criterionStatisticsDataService = criterionStatisticsDataService;
}
@Autowired
private ProcessResultDataService processResultDataService;
public void setCriterionStatisticsDataService(
ProcessResultDataService processResultDataService) {
this.processResultDataService = processResultDataService;
}
/**
* The Html hightlighter.
*/
private HtmlHighlighter highlighter;
@Autowired
public void setHtmlHighlighter(HtmlHighlighter highlighter) {
this.highlighter = highlighter;
}
public AuditResultController() {
super();
}
/**
* General router when receive audit-result request. Regarding the scope of
* the audit, the returned page may differ.
*
* @param auditId
* @param request
* @param model
* @return
*/
@RequestMapping(value = TgolKeyStore.AUDIT_RESULT_CONTRACT_URL, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displayAuditResultFromContract(
@RequestParam(TgolKeyStore.AUDIT_ID_KEY) String auditId,
@RequestParam(value = TgolKeyStore.IS_MANUAL_AUDIT_KEY, required = false, defaultValue = "false") boolean manual,
HttpServletRequest request, Model model) {
try {
Audit audit = getAuditDataService().read(Long.valueOf(auditId));
Act act = getActDataService().getActFromAudit(audit);
switch (act.getScope().getCode()) {
case FILE:
case PAGE:
model.addAttribute(TgolKeyStore.WEBRESOURCE_ID_KEY, audit
.getSubject().getId());
model.addAttribute(TgolKeyStore.IS_MANUAL_AUDIT_KEY, manual);
if (manual) {
// appel au service
Contract contract = getContractDataService().read(
act.getContract().getId());
// controle sur le user si option manuel est activé
for (Functionality func : contract.getFunctionalitySet()) {
if (func.getId() == 5)
// model.addAttribute("resultAuditManualCommand",new
// ResultAuditManualCommand());
return TgolKeyStore.RESULT_PAGE_VIEW_REDIRECT_NAME;
}
return TgolKeyStore.ACCESS_DENIED_VIEW_NAME;
}
return TgolKeyStore.RESULT_PAGE_VIEW_REDIRECT_NAME;
case DOMAIN:
case SCENARIO:
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, auditId);
return TgolKeyStore.SYNTHESIS_SITE_VIEW_REDIRECT_NAME;
case GROUPOFFILES:
case GROUPOFPAGES:
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, auditId);
model.addAttribute(TgolKeyStore.STATUS_KEY,
HttpStatusCodeFamily.f2xx.name());
return TgolKeyStore.PAGE_LIST_XXX_VIEW_REDIRECT_NAME;
default:
throw new ForbiddenPageException();
}
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
}
/**
* @param webresourceId
* @param request
* @param model
* @return
*/
@RequestMapping(value = { TgolKeyStore.PAGE_RESULT_CONTRACT_URL,
TgolKeyStore.SITE_RESULT_CONTRACT_URL }, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displayPageResultFromContract(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(value = TgolKeyStore.IS_MANUAL_AUDIT_KEY) boolean manual,
HttpServletRequest request, Model model) {
Long webResourceIdValue;
try {
webResourceIdValue = Long.valueOf(webresourceId);
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
return dispatchDisplayResultRequest(webResourceIdValue, null, model,
request, manual);
}
/**
* @param manualAuditCommand
* @param auditResultSortCommand
* @param result
* @param model
* @param request
* @param webresourceId
* @return
*/
@RequestMapping(value=TgolKeyStore.PAGE_RESULT_CONTRACT_URL, method = RequestMethod.POST)
@Secured({TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY})
protected String submitPageResultSorter(
@ModelAttribute(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY) AuditResultSortCommand auditResultSortCommand,
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@ModelAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY) ManualAuditCommand manualAuditCommand,
BindingResult result,
Model model,
HttpServletRequest request) {
if(manualAuditCommand !=null){
return dispatchSubmitManualAuditValues(webresourceId,manualAuditCommand,result,model,request);
}else{
return dispatchDisplayResultRequest(
auditResultSortCommand.getWebResourceId(),
auditResultSortCommand,
model,
request,false);
}
}
private String dispatchSubmitManualAuditValues(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@ModelAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY) ManualAuditCommand manualAuditCommand,
BindingResult result,
Model model,
HttpServletRequest request) {
WebResource webResource;
try {
webResource = getWebResourceDataService().ligthRead(Long.valueOf(webresourceId));
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
if (webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)){
List<ProcessResult> processResultList=TestResultFactory.getInstance().getProcessResultListFromTestsResult(
new LinkedList<TestResult>(manualAuditCommand.getModifiedTestResultMap().values()), webResource);
processResultDataService.saveOrUpdate(processResultList);
return dispatchDisplayResultRequest(
webResource.getId(),
null,
model,
request,true);
}
else
throw new ForbiddenPageException();
}
/**
*
* @param webresourceId
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value = TgolKeyStore.SOURCE_CODE_CONTRACT_URL, method = RequestMethod.GET)
@Secured({ TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY })
public String displaySourceCodeFromContract(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
HttpServletRequest request, HttpServletResponse response,
Model model) {
WebResource webResource;
try {
webResource = getWebResourceDataService().ligthRead(
Long.valueOf(webresourceId));
} catch (NumberFormatException nfe) {
throw new ForbiddenPageException();
}
if (webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Page page = (Page) webResource;
SSP ssp = getContentDataService().findSSP(page, page.getURL());
model.addAttribute(TgolKeyStore.SOURCE_CODE_KEY,
highlightSourceCode(ssp));
ScopeEnum scope = getActDataService().getActFromAudit(audit)
.getScope().getCode();
if (scope.equals(ScopeEnum.GROUPOFPAGES)
|| scope.equals(ScopeEnum.PAGE)) {
model.addAttribute(TgolKeyStore.IS_GENERATED_HTML_KEY, true);
}
return TgolKeyStore.SOURCE_CODE_PAGE_VIEW_NAME;
} else {
throw new ForbiddenUserException(getCurrentUser());
}
}
/**
*
* @param model
* @return the test-result view name
*/
@RequestMapping(value = TgolKeyStore.CRITERION_RESULT_CONTRACT_URL, method = RequestMethod.GET)
public String displayCriterionResult(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(TgolKeyStore.CRITERION_CODE_KEY) String criterionId,
Model model) {
Long wrId;
Long critId;
try {
wrId = Long.valueOf(webresourceId);
critId = Long.valueOf(criterionId);
} catch (NumberFormatException nfe) {
throw new ForbiddenUserException(getCurrentUser());
}
WebResource webResource = getWebResourceDataService().ligthRead(wrId);
if (webResource == null || webResource instanceof Site) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Contract contract = retrieveContractFromAudit(audit);
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY,
contract.getLabel());
model.addAttribute(TgolKeyStore.URL_KEY, webResource.getURL());
Criterion crit = criterionDataService.read(critId);
model.addAttribute(TgolKeyStore.CRITERION_LABEL_KEY,
crit.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
model.addAttribute(TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance()
.getTestResultListFromCriterion(webResource, crit));
return TgolKeyStore.CRITERION_RESULT_VIEW_NAME;
} else {
throw new ForbiddenPageException();
}
}
/**
*
* @param model
* @return the test-result view name
*/
@RequestMapping(value = TgolKeyStore.TEST_RESULT_CONTRACT_URL, method = RequestMethod.GET)
public String displayTestResult(
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
@RequestParam(TgolKeyStore.TEST_CODE_KEY) String testId, Model model) {
Long wrId;
Long tstId;
try {
wrId = Long.valueOf(webresourceId);
tstId = Long.valueOf(testId);
} catch (NumberFormatException nfe) {
throw new ForbiddenUserException(getCurrentUser());
}
WebResource webResource = getWebResourceDataService().ligthRead(wrId);
if (webResource == null) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
if (isUserAllowedToDisplayResult(audit)) {
Contract contract = retrieveContractFromAudit(audit);
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY,
contract.getLabel());
model.addAttribute(TgolKeyStore.URL_KEY, webResource.getURL());
Test test = getTestDataService().read(tstId);
model.addAttribute(TgolKeyStore.TEST_LABEL_KEY, test.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
if (!test.getScope().equals(getPageScope())) {
model.addAttribute(TgolKeyStore.SITE_SCOPE_TEST_DETAILS_KEY,
true);
} else {
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
}
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance().getTestResultListFromTest(
webResource, test));
return TgolKeyStore.TEST_RESULT_VIEW_NAME;
} else {
throw new ForbiddenPageException();
}
}
/**
* Regarding the page type, this method collects data, set them up and
* display the appropriate result page.
*
* @param webResourceId
* @param auditResultSortCommand
* @param model
* @param displayScope
* @param request
* @return
*/
private String dispatchDisplayResultRequest(Long webResourceId,
AuditResultSortCommand auditResultSortCommand, Model model,
HttpServletRequest request, boolean isManualAudit) {
// We first check that the current user is allowed to display the result
// of this audit
WebResource webResource = getWebResourceDataService().ligthRead(
webResourceId);
if (webResource == null) {
throw new ForbiddenPageException();
}
Audit audit = getAuditFromWebResource(webResource);
// If the Id given in argument correspond to a webResource,
// data are retrieved to be prepared and displayed
if (isUserAllowedToDisplayResult(audit)) {
this.callGc(webResource);
String displayScope = computeDisplayScope(request,
auditResultSortCommand);
// first we add statistics meta-data to model
addAuditStatisticsToModel(webResource, model, displayScope);
// The page is displayed with sort option. Form needs to be set up
prepareDataForSortConsole(webResourceId, displayScope,
auditResultSortCommand, model, isManualAudit);
// Data need to be prepared regarding the audit type
return prepareSuccessfullAuditData(webResource, audit, model,
displayScope, getLocaleResolver().resolveLocale(request),
isManualAudit);
} else {
throw new ForbiddenUserException(getCurrentUser());
}
}
/**
* This method prepares the data to be displayed in the sort (referential,
* theme, result types) console of the result page.
*
* @param webResourceId
* @param displayScope
* @param auditResultSortCommand
* @param model
* @param isManualAuit
*/
private void prepareDataForSortConsole(Long webResourceId,
String displayScope, AuditResultSortCommand auditResultSortCommand,
Model model, boolean isManualAuit) {
// Meta-statistics have been added to the method previously
String referentialParameter = ((AuditStatistics) model.asMap().get(
TgolKeyStore.STATISTICS_KEY)).getParametersMap().get(
referentialCode);
AuditResultSortCommand asuc;
List<FormField> formFieldList;
if (auditResultSortCommand == null) {
formFieldList = AuditResultSortCommandFactory.getInstance()
.getFormFieldBuilderCopy(referentialParameter,
sortFormFieldBuilderList);
if (isManualAuit) {
CheckboxFormFieldImpl ObjectList = (CheckboxFormFieldImpl) formFieldList
.get(1);
List<CheckboxElement> checkboxElementList = ObjectList
.getCheckboxElementList();
for (CheckboxElement checkboxElement : checkboxElementList) {
if (checkboxElement.getI18nKey().equals("nt")) {
checkboxElement.setSelected(true);
}
}
}
asuc = AuditResultSortCommandFactory.getInstance()
.getInitialisedAuditResultSortCommand(
webResourceId,
displayScope,
isCriterionViewAccessible(webResourceId,
referentialParameter), formFieldList);
} else {
formFieldList = AuditResultSortCommandFactory.getInstance()
.getFormFieldBuilderCopy(referentialParameter,
sortFormFieldBuilderList, auditResultSortCommand);
asuc = auditResultSortCommand;
}
model.addAttribute(TgolKeyStore.AUDIT_RESULT_SORT_FIELD_LIST_KEY,
formFieldList);
model.addAttribute(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY, asuc);
}
/**
*
* @param webResourceId
* @param referentialParameter
* @return whether the criterion view is accessible for the given
* referential
*/
private boolean isCriterionViewAccessible(Long webResourceId,
String referentialParameter) {
return authorizedRefForCriterionViewList.contains(referentialParameter)
&& criterionStatisticsDataService
.getCriterionStatisticsCountByWebResource(webResourceId) > 0;
}
/**
* Regarding the audit type, collect data needed by the view.
*
* @param webResource
* @param audit
* @param model
* @param locale
* @param exportFormat
* @return
* @throws IOException
*/
private String prepareSuccessfullAuditData(WebResource webResource,
Audit audit, Model model, String displayScope, Locale locale,
boolean isManualAudit) {
model.addAttribute(TgolKeyStore.LOCALE_KEY, locale);
if (webResource instanceof Site) {
return prepareSuccessfullSiteData((Site) webResource, audit, model);
} else if (webResource instanceof Page) {
// In case of display page result page, we need all data related
// with
// the page, that's why a deepRead is needed
return prepareSuccessfullPageData((Page) webResource, audit, model,
displayScope, isManualAudit);
}
throw new LostInSpaceException();
}
/**
* This methods handles audit data in case of the audit is of site type
*
* @param site
* @param audit
* @param model
* @return
* @throws IOException
*/
private String prepareSuccessfullSiteData(Site site, Audit audit,
Model model) {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model.asMap()
.get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance().getTestResultSortedByThemeMap(
site, getSiteScope(),
asuc.getSortOptionMap().get(themeSortKey).toString(),
getTestResultSortSelection(asuc)));
// Attributes for breadcrumb
Contract contract = retrieveContractFromAudit(audit);
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY, contract.getLabel());
model.addAttribute(TgolKeyStore.RESULT_ACTION_LIST_KEY,
actionHandler.getActionList("EXPORT"));
return TgolKeyStore.RESULT_SITE_VIEW_NAME;
}
/**
* This methods handles audit data in case of page type audit
*
* @param page
* @param audit
* @param model
* @param displayScope
* @return
* @throws IOException
*/
private String prepareSuccessfullPageData(Page page, Audit audit,
Model model, String displayScope, boolean isManualAudit) {
Contract contract = retrieveContractFromAudit(audit);
if (!audit.getStatus().equals(AuditStatus.COMPLETED)) {
return prepareFailedAuditData(audit, model);
}
model.addAttribute(TgolKeyStore.STATUS_KEY, computeAuditStatus(audit));
model.addAttribute(TgolKeyStore.RESULT_ACTION_LIST_KEY,
actionHandler.getActionList("EXPORT"));
// Attributes for breadcrumb
model.addAttribute(TgolKeyStore.CONTRACT_ID_KEY, contract.getId());
model.addAttribute(TgolKeyStore.CONTRACT_NAME_KEY, contract.getLabel());
model.addAttribute(TgolKeyStore.AUDIT_ID_KEY, audit.getId());
// Add a boolean used to display the breadcrumb.
model.addAttribute(TgolKeyStore.AUTHORIZED_SCOPE_FOR_PAGE_LIST,
isAuthorizedScopeForPageList(audit));
// Add a command to relaunch the audit from the result page
model.addAttribute(
TgolKeyStore.AUDIT_SET_UP_COMMAND_KEY,
AuditSetUpCommandFactory.getInstance()
.getPageAuditSetUpCommand(
contract,
page.getURL(),
getParameterDataService()
.getParameterSetFromAudit(audit)));
if (StringUtils.equalsIgnoreCase(displayScope,
TgolKeyStore.TEST_DISPLAY_SCOPE_VALUE)) {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model
.asMap().get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.TEST_RESULT_LIST_KEY,
TestResultFactory.getInstance()
.getTestResultSortedByThemeMap(
page,
getPageScope(),
asuc.getSortOptionMap().get(themeSortKey)
.toString(),
getTestResultSortSelection(asuc)));
//hack to force manual audit to be removed later
isManualAudit=true;
if (isManualAudit) {
ManualAuditCommand manualAudit=new ManualAuditCommand();
manualAudit.setModifedTestResultMap(TestResultFactory.getInstance().getTestResultMap(
page,
getPageScope(),
asuc.getSortOptionMap().get(themeSortKey).toString(),
getTestResultSortSelection(asuc)));
model.addAttribute(TgolKeyStore.MANUAL_AUDIT_COMMAND_KEY,manualAudit);
}
return TgolKeyStore.RESULT_PAGE_VIEW_NAME;
} else {
AuditResultSortCommand asuc = ((AuditResultSortCommand) model
.asMap().get(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY));
model.addAttribute(
TgolKeyStore.CRITERION_RESULT_LIST_KEY,
CriterionResultFactory.getInstance()
.getCriterionResultSortedByThemeMap(
page,
asuc.getSortOptionMap().get(themeSortKey)
.toString(),
getTestResultSortSelection(asuc)));
return TgolKeyStore.RESULT_PAGE_BY_CRITERION_VIEW_NAME;
}
}
private Collection<String> getTestResultSortSelection(
AuditResultSortCommand asuc) {
Collection<String> selectedValues = new HashSet<String>();
if ((asuc.getSortOptionMap().get(testResultSortKey)) instanceof Object[]) {
CollectionUtils.addAll(selectedValues, ((Object[]) asuc
.getSortOptionMap().get(testResultSortKey)));
} else if ((asuc.getSortOptionMap().get(testResultSortKey)) instanceof String) {
selectedValues.add((String) asuc.getSortOptionMap().get(
testResultSortKey));
}
return selectedValues;
}
/**
* This methods enforces the call of the Garbarge collector.
*
* @param webresource
*/
private void callGc(WebResource webresource) {
if (webresource != null && (webresource.getId() % 10) == 0) {
System.gc();
}
}
/**
* This methods call the highlighter service and returns the highlighted
* code.
*
* @param ssp
* @return
* @throws IOException
*/
private String highlightSourceCode(SSP ssp) {
if (ssp != null && StringUtils.isNotBlank(ssp.getDoctype())) {
return highlighter.highlightSourceCode(ssp.getDoctype(),
ssp.getAdaptedContent());
} else {
return highlighter.highlightSourceCode(ssp.getAdaptedContent());
}
}
/**
* Extract from the audit parameter the referential. Regarding this value,
* the returned page displays results sorted by tests or criterion
*
* @param request
* @param arsc
* @return
*/
private String computeDisplayScope(HttpServletRequest request,
AuditResultSortCommand arsc) {
if (StringUtils.contains(request.getHeader(REFERER_HEADER_KEY),
CRITERION_RESULT_PAGE_KEY)) {
return TgolKeyStore.CRITERION_DISPLAY_SCOPE_VALUE;
}
if (arsc != null) {
return arsc.getDisplayScope();
}
return TgolKeyStore.TEST_DISPLAY_SCOPE_VALUE;
}
} | Manual audit IHM + save and load values | web-app/tgol-web-app/src/main/java/org/opens/tgol/controller/AuditResultController.java | Manual audit IHM + save and load values |
|
Java | lgpl-2.1 | b87fe88de8e19e2952d6253b70490ca81c53e72a | 0 | brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty | /*
* libbrlapi - A library providing access to braille terminals for applications.
*
* Copyright (C) 2006-2020 by
* Samuel Thibault <[email protected]>
* Sébastien Hinderer <[email protected]>
*
* libbrlapi comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU Lesser General Public License, as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any
* later version. Please see the file LICENSE-LGPL for details.
*
* Web Page: http://brltty.app/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
package org.a11y.brlapi.clients;
import org.a11y.brlapi.*;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeoutException;
public class ApiExceptionClient extends PauseClient {
public ApiExceptionClient (String... arguments) {
super(arguments);
}
@Override
protected final void runClient (Connection connection)
throws ProgramException
{
ttyMode(
connection, false,
(tty) -> {
WriteArguments arguments = new WriteArguments()
.setRegion(1, (tty.getCellCount() + 1))
.setText("This should fail because the region size is too big.");
tty.write(arguments);
String label = "API exception";
String result = null;
try {
if (pause(tty)) {
result = String.format("wait for %s timed out", label);
} else {
result = String.format("wait for %s interrupted", label);
}
} catch (APIException exception) {
result = String.format("%s received", label);
}
printf("%s\n", result);
}
);
}
}
| Bindings/Java/clients/ApiExceptionClient.java | /*
* libbrlapi - A library providing access to braille terminals for applications.
*
* Copyright (C) 2006-2020 by
* Samuel Thibault <[email protected]>
* Sébastien Hinderer <[email protected]>
*
* libbrlapi comes with ABSOLUTELY NO WARRANTY.
*
* This is free software, placed under the terms of the
* GNU Lesser General Public License, as published by the Free Software
* Foundation; either version 2.1 of the License, or (at your option) any
* later version. Please see the file LICENSE-LGPL for details.
*
* Web Page: http://brltty.app/
*
* This software is maintained by Dave Mielke <[email protected]>.
*/
package org.a11y.brlapi.clients;
import org.a11y.brlapi.*;
import java.io.InterruptedIOException;
import java.util.concurrent.TimeoutException;
public class ApiExceptionClient extends PauseClient {
public ApiExceptionClient (String... arguments) {
super(arguments);
}
@Override
protected final void runClient (Connection connection)
throws ProgramException
{
ttyMode(
connection, false,
(tty) -> {
WriteArguments arguments = new WriteArguments()
.setRegion(1, (tty.getCellCount() + 1))
.setText("This should fail because the region size is too big.");
tty.write(arguments);
String label = "API exception";
String result = null;
try {
tty.readKeyWithTimeout(getWaitTime());
result = String.format("%s not thrown", label);
} catch (APIException exception) {
result = String.format("%s received", label);
} catch (InterruptedIOException exception) {
result = String.format("wait for %s interrupted", label);
} catch (TimeoutException exception) {
result = String.format("wait for %s timed out", label);
}
printf("%s\n", result);
}
);
}
}
| Java bindings: The Pause client can use pause (instead of readKeyWithTimeout). (dm)
| Bindings/Java/clients/ApiExceptionClient.java | Java bindings: The Pause client can use pause (instead of readKeyWithTimeout). (dm) |
|
Java | lgpl-2.1 | 6b27baf9d523833a2789b038d86d2b41031ffbfb | 0 | cwarden/kettle,juanmjacobs/kettle,ontometrics/ontokettle,ontometrics/ontokettle,cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,ontometrics/ontokettle,cwarden/kettle | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.mergejoin;
import java.util.ArrayList;
import java.util.Iterator;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Merge rows from 2 sorted streams and output joined rows with matched key fields.
* Use this instead of hash join is both your input streams are too big to fit in
* memory. Note that both the inputs must be sorted on the join key.
*
* This is a first prototype implementation that only handles two streams and
* inner join. It also always outputs all values from both streams. Ideally, we should:
* 1) Support any number of incoming streams
* 2) Allow user to choose the join type (inner, outer) for each stream
* 3) Allow user to choose which fields to push to next step
* 4) Have multiple output ports as follows:
* a) Containing matched records
* b) Unmatched records for each input port
* 5) Support incoming rows to be sorted either on ascending or descending order.
* The currently implementation only supports ascending
* @author Biswapesh
* @since 24-nov-2006
*/
public class MergeJoin extends BaseStep implements StepInterface
{
private MergeJoinMeta meta;
private MergeJoinData data;
public MergeJoin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
int compare;
if (first)
{
first = false;
data.one=getRowFrom(meta.getStepName1());
data.two=getRowFrom(meta.getStepName2());
if (!isInputLayoutValid(data.one, data.two))
{
throw new KettleException(Messages.getString("MergeJoin.Exception.InvalidLayoutDetected"));
}
if (data.one!=null)
{
// Find the key indexes:
data.keyNrs1 = new int[meta.getKeyFields1().length];
for (int i=0;i<data.keyNrs1.length;i++)
{
data.keyNrs1[i] = data.one.searchValueIndex(meta.getKeyFields1()[i]);
if (data.keyNrs1[i]<0)
{
String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]); //$NON-NLS-1$ //$NON-NLS-2$
logError(message);
throw new KettleStepException(message);
}
}
}
if (data.two!=null)
{
// Find the key indexes:
data.keyNrs2 = new int[meta.getKeyFields2().length];
for (int i=0;i<data.keyNrs2.length;i++)
{
data.keyNrs2[i] = data.two.searchValueIndex(meta.getKeyFields2()[i]);
if (data.keyNrs2[i]<0)
{
String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]); //$NON-NLS-1$ //$NON-NLS-2$
logError(message);
throw new KettleStepException(message);
}
}
}
Value v;
data.one_dummy = new Row(data.one);
for (int i=0; i < data.one_dummy.size(); ++i)
{
v = data.one_dummy.getValue(i);
v.setNull();
data.one_dummy.setValue(i, v);
}
data.two_dummy = new Row(data.two);
for (int i=0; i < data.two_dummy.size(); ++i)
{
v = data.two_dummy.getValue(i);
v.setNull();
data.two_dummy.setValue(i, v);
}
}
if (log.isRowLevel()) logRowlevel(Messages.getString("MergeJoin.Log.DataInfo",data.one+"")+data.two); //$NON-NLS-1$ //$NON-NLS-2$
/*
* We can stop processing if any of the following is true:
* a) Both streams are empty
* b) First stream is empty and join type is INNER or LEFT OUTER
* c) Second stream is empty and join type is INNER or RIGHT OUTER
*/
if ((data.one == null && data.two == null) ||
(data.one == null && data.one_optional == false) ||
(data.two == null && data.two_optional == false))
{
setOutputDone();
return false;
}
if (data.one == null)
{
compare = -1;
}
else
{
if (data.two == null)
{
compare = 1;
}
else
{
int cmp = data.one.compare(data.two, data.keyNrs1, data.keyNrs2, null, null);
compare = cmp>0?1 : cmp<0?-1 : 0;
}
}
switch (compare)
{
case 0:
/*
* We've got a match. This is what we do next (to handle duplicate keys correctly):
* Read the next record from both streams
* If any of the keys match, this means we have duplicates. We therefore
* Create an array of all rows that have the same keys
* Push a cartesian product of the two arrays to output
* Else
* Just push the combined rowset to output
*/
data.one_next = getRowFrom(meta.getStepName1());
data.two_next = getRowFrom(meta.getStepName2());
int compare1 = (data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null);
int compare2 = (data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null);
if (compare1 == 0 || compare2 == 0) // Duplicate keys
{
if (data.ones == null)
data.ones = new ArrayList();
else
data.ones.clear();
if (data.twos == null)
data.twos = new ArrayList();
else
data.twos.clear();
data.ones.add(data.one);
if (compare1 == 0) // First stream has duplicates
{
data.ones.add(data.one_next);
for (;;)
{
data.one_next = getRowFrom(meta.getStepName1());
if (0 != ((data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null)))
break;
data.ones.add(data.one_next);
}
}
data.twos.add(data.two);
if (compare2 == 0) // Second stream has duplicates
{
data.twos.add(data.two_next);
for (;;)
{
data.two_next = getRowFrom(meta.getStepName2());
if (0 != ((data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null)))
break;
data.twos.add(data.two_next);
}
}
Iterator one_iter = data.ones.iterator();
while (one_iter.hasNext())
{
Row one = (Row) one_iter.next();
Iterator two_iter = data.twos.iterator();
while (two_iter.hasNext())
{
Row combi = new Row(one);
combi.addRow((Row) two_iter.next());
putRow(combi);
}
}
data.ones.clear();
data.twos.clear();
}
else // No duplicates
{
data.one.addRow(data.two);
putRow(data.one);
}
data.one = data.one_next;
data.two = data.two_next;
break;
case 1:
logDebug("First stream has missing key");
/*
* First stream is greater than the second stream. This means:
* a) This key is missing in the first stream
* b) Second stream may have finished
* So, if full/right outer join is set and 2nd stream is not null,
* we push a record to output with only the values for the second
* row populated. Next, if 2nd stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.one_optional == true)
{
if (data.two != null)
{
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
else if (data.two_optional == false)
{
/*
* If we are doing right outer join then we are done since
* there are no more rows in the second set
*/
setOutputDone();
return false;
}
else
{
/*
* We are doing full outer join so print the 1st stream and
* get the next row from 1st stream
*/
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
}
else if (data.two == null && data.two_optional == true)
{
/**
* We have reached the end of stream 2 and there are records
* present in the first stream. Also, join is left or full outer.
* So, create a row with just the values in the first stream
* and push it forward
*/
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
else if (data.two != null)
{
/*
* We are doing an inner or left outer join, so throw this row away
* from the 2nd stream
*/
data.two = getRowFrom(meta.getStepName2());
}
break;
case -1:
logDebug("Second stream has missing key");
/*
* Second stream is greater than the first stream. This means:
* a) This key is missing in the second stream
* b) First stream may have finished
* So, if full/left outer join is set and 1st stream is not null,
* we push a record to output with only the values for the first
* row populated. Next, if 1st stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.two_optional == true)
{
if (data.one != null)
{
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
else if (data.one_optional == false)
{
/*
* We are doing a left outer join and there are no more rows
* in the first stream; so we are done
*/
setOutputDone();
return false;
}
else
{
/*
* We are doing a full outer join so print the 2nd stream and
* get the next row from the 2nd stream
*/
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
}
else if (data.one == null && data.one_optional == true)
{
/*
* We have reached the end of stream 1 and there are records
* present in the second stream. Also, join is right or full outer.
* So, create a row with just the values in the 2nd stream
* and push it forward
*/
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
else if (data.one != null)
{
/*
* We are doing an inner or right outer join so a non-matching row
* in the first stream is of no use to us - throw it away and get the
* next row
*/
data.one = getRowFrom(meta.getStepName1());
}
break;
default:
logDebug("We shouldn't be here!!");
// Make sure we do not go into an infinite loop by continuing to read data
data.one = getRowFrom(meta.getStepName1());
data.two = getRowFrom(meta.getStepName2());
break;
}
if (checkFeedback(linesRead)) logBasic(Messages.getString("MergeJoin.LineNumber")+linesRead); //$NON-NLS-1$
return true;
}
/**
* @see StepInterface#init( be.ibridge.kettle.trans.step.StepMetaInterface , be.ibridge.kettle.trans.step.StepDataInterface)
*/
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
if (super.init(smi, sdi))
{
if (meta.getStepName1()==null || meta.getStepName2()==null)
{
logError(Messages.getString("MergeJoin.Log.BothTrueAndFalseNeeded")); //$NON-NLS-1$
return false;
}
String joinType = meta.getJoinType();
for (int i = 0; i < MergeJoinMeta.join_types.length; ++i)
{
if (joinType.equalsIgnoreCase(MergeJoinMeta.join_types[i]))
{
data.one_optional = MergeJoinMeta.one_optionals[i];
data.two_optional = MergeJoinMeta.two_optionals[i];
return true;
}
}
logError(Messages.getString("MergeJoin.Log.InvalidJoinType", meta.getJoinType())); //$NON-NLS-1$
return false;
}
return true;
}
/**
* Checks whether incoming rows are join compatible. This essentially
* means that the keys being compared should be of the same datatype
* and both rows should have the same number of keys specified
* @param row1 Reference row
* @param row2 Row to compare to
*
* @return true when templates are compatible.
*/
protected boolean isInputLayoutValid(Row row1, Row row2)
{
if (row1!=null && row2!=null)
{
// Compare the key types
String keyFields1[] = meta.getKeyFields1();
int nrKeyFields1 = keyFields1.length;
String keyFields2[] = meta.getKeyFields2();
int nrKeyFields2 = keyFields2.length;
if (nrKeyFields1 != nrKeyFields2)
{
logError("Number of keys do not match " + nrKeyFields1 + " vs " + nrKeyFields2);
return false;
}
for (int i=0;i<nrKeyFields1;i++)
{
Value v1 = row1.searchValue(keyFields1[i]);
if (v1 == null)
{
return false;
}
Value v2 = row2.searchValue(keyFields2[i]);
if (v2 == null)
{
return false;
}
if ( ! v1.equalValueType(v2, true) )
{
return false;
}
}
}
// we got here, all seems to be ok.
return true;
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic(Messages.getString("MergeJoin.Log.StartingToRun")); //$NON-NLS-1$
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError(Messages.getString("MergeJoin.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.mergejoin;
import java.util.ArrayList;
import java.util.Iterator;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Merge rows from 2 sorted streams and output joined rows with matched key fields.
* Use this instead of hash join is both your input streams are too big to fit in
* memory. Note that both the inputs must be sorted on the join key.
*
* This is a first prototype implementation that only handles two streams and
* inner join. It also always outputs all values from both streams. Ideally, we should:
* 1) Support any number of incoming streams
* 2) Allow user to choose the join type (inner, outer) for each stream
* 3) Allow user to choose which fields to push to next step
* 4) Have multiple output ports as follows:
* a) Containing matched records
* b) Unmatched records for each input port
* 5) Support incoming rows to be sorted either on ascending or descending order.
* The currently implementation only supports ascending
* @author Biswapesh
* @since 24-nov-2006
*/
public class MergeJoin extends BaseStep implements StepInterface
{
private MergeJoinMeta meta;
private MergeJoinData data;
public MergeJoin(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
int compare;
if (first)
{
first = false;
data.one=getRowFrom(meta.getStepName1());
data.two=getRowFrom(meta.getStepName2());
if (!isInputLayoutValid(data.one, data.two))
{
throw new KettleException(Messages.getString("MergeJoin.Exception.InvalidLayoutDetected"));
}
if (data.one!=null)
{
// Find the key indexes:
data.keyNrs1 = new int[meta.getKeyFields1().length];
for (int i=0;i<data.keyNrs1.length;i++)
{
data.keyNrs1[i] = data.one.searchValueIndex(meta.getKeyFields1()[i]);
if (data.keyNrs1[i]<0)
{
String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields1()[i]); //$NON-NLS-1$ //$NON-NLS-2$
logError(message);
throw new KettleStepException(message);
}
}
}
if (data.two!=null)
{
// Find the key indexes:
data.keyNrs2 = new int[meta.getKeyFields2().length];
for (int i=0;i<data.keyNrs2.length;i++)
{
data.keyNrs2[i] = data.two.searchValueIndex(meta.getKeyFields2()[i]);
if (data.keyNrs2[i]<0)
{
String message = Messages.getString("MergeJoin.Exception.UnableToFindFieldInReferenceStream",meta.getKeyFields2()[i]); //$NON-NLS-1$ //$NON-NLS-2$
logError(message);
throw new KettleStepException(message);
}
}
}
Value v;
data.one_dummy = new Row(data.one);
for (int i=0; i < data.one_dummy.size(); ++i)
{
v = data.one_dummy.getValue(i);
v.setNull();
data.one_dummy.setValue(i, v);
}
data.two_dummy = new Row(data.two);
for (int i=0; i < data.two_dummy.size(); ++i)
{
v = data.two_dummy.getValue(i);
v.setNull();
data.two_dummy.setValue(i, v);
}
}
if (log.isRowLevel()) logRowlevel(Messages.getString("MergeJoin.Log.DataInfo",data.one+"")+data.two); //$NON-NLS-1$ //$NON-NLS-2$
/*
* We can stop processing if any of the following is true:
* a) Both streams are empty
* b) First stream is empty and join type is INNER or LEFT OUTER
* c) Second stream is empty and join type is INNER or RIGHT OUTER
*/
if ((data.one==null && data.two==null) ||
(data.one == null && data.one_optional == false) ||
(data.two == null && data.two_optional == false))
{
setOutputDone();
return false;
}
if (data.one == null)
compare = -1;
else if (data.two == null)
compare = 1;
else
compare = data.one.compare(data.two, data.keyNrs1, data.keyNrs2, null, null);
switch (compare)
{
case 0:
/*
* We've got a match. This is what we do next (to handle duplicate keys correctly):
* Read the next record from both streams
* If any of the keys match, this means we have duplicates. We therefore
* Create an array of all rows that have the same keys
* Push a cartesian product of the two arrays to output
* Else
* Just push the combined rowset to output
*/
data.one_next = getRowFrom(meta.getStepName1());
data.two_next = getRowFrom(meta.getStepName2());
int compare1 = (data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null);
int compare2 = (data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null);
if (compare1 == 0 || compare2 == 0) // Duplicate keys
{
if (data.ones == null)
data.ones = new ArrayList();
else
data.ones.clear();
if (data.twos == null)
data.twos = new ArrayList();
else
data.twos.clear();
data.ones.add(data.one);
if (compare1 == 0) // First stream has duplicates
{
data.ones.add(data.one_next);
for (;;)
{
data.one_next = getRowFrom(meta.getStepName1());
if (0 != ((data.one_next == null) ? -1 : data.one.compare(data.one_next, data.keyNrs1, data.keyNrs1, null, null)))
break;
data.ones.add(data.one_next);
}
}
data.twos.add(data.two);
if (compare2 == 0) // Second stream has duplicates
{
data.twos.add(data.two_next);
for (;;)
{
data.two_next = getRowFrom(meta.getStepName2());
if (0 != ((data.two_next == null) ? -1 : data.two.compare(data.two_next, data.keyNrs2, data.keyNrs2, null, null)))
break;
data.twos.add(data.two_next);
}
}
Iterator one_iter = data.ones.iterator();
while (one_iter.hasNext())
{
Row one = (Row) one_iter.next();
Iterator two_iter = data.twos.iterator();
while (two_iter.hasNext())
{
Row combi = new Row(one);
combi.addRow((Row) two_iter.next());
putRow(combi);
}
}
data.ones.clear();
data.twos.clear();
}
else // No duplicates
{
data.one.addRow(data.two);
putRow(data.one);
}
data.one = data.one_next;
data.two = data.two_next;
break;
case 1:
logDebug("First stream has missing key");
/*
* First stream is greater than the second stream. This means:
* a) This key is missing in the first stream
* b) Second stream may have finished
* So, if full/right outer join is set and 2nd stream is not null,
* we push a record to output with only the values for the second
* row populated. Next, if 2nd stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.one_optional == true)
{
if (data.two != null)
{
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
else if (data.two_optional == false)
{
/*
* If we are doing right outer join then we are done since
* there are no more rows in the second set
*/
setOutputDone();
return false;
}
else
{
/*
* We are doing full outer join so print the 1st stream and
* get the next row from 1st stream
*/
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
}
else if (data.two == null && data.two_optional == true)
{
/**
* We have reached the end of stream 2 and there are records
* present in the first stream. Also, join is left or full outer.
* So, create a row with just the values in the first stream
* and push it forward
*/
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
else if (data.two != null)
{
/*
* We are doing an inner or left outer join, so throw this row away
* from the 2nd stream
*/
data.two = getRowFrom(meta.getStepName2());
}
break;
case -1:
logDebug("Second stream has missing key");
/*
* Second stream is greater than the first stream. This means:
* a) This key is missing in the second stream
* b) First stream may have finished
* So, if full/left outer join is set and 1st stream is not null,
* we push a record to output with only the values for the first
* row populated. Next, if 1st stream is not finished, we get a row
* from it; otherwise signal that we are done
*/
if (data.two_optional == true)
{
if (data.one != null)
{
Row combi = new Row(data.one);
combi.addRow(data.two_dummy);
putRow(combi);
data.one = getRowFrom(meta.getStepName1());
}
else if (data.one_optional == false)
{
/*
* We are doing a left outer join and there are no more rows
* in the first stream; so we are done
*/
setOutputDone();
return false;
}
else
{
/*
* We are doing a full outer join so print the 2nd stream and
* get the next row from the 2nd stream
*/
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
}
else if (data.one == null && data.one_optional == true)
{
/*
* We have reached the end of stream 1 and there are records
* present in the second stream. Also, join is right or full outer.
* So, create a row with just the values in the 2nd stream
* and push it forward
*/
Row combi = new Row(data.one_dummy);
combi.addRow(data.two);
putRow(combi);
data.two = getRowFrom(meta.getStepName2());
}
else if (data.one != null)
{
/*
* We are doing an inner or right outer join so a non-matching row
* in the first stream is of no use to us - throw it away and get the
* next row
*/
data.one = getRowFrom(meta.getStepName1());
}
break;
default:
logDebug("We shouldn't be here!!");
// Make sure we do not go into an infinite loop by continuing to read data
data.one = getRowFrom(meta.getStepName1());
data.two = getRowFrom(meta.getStepName2());
break;
}
if (checkFeedback(linesRead)) logBasic(Messages.getString("MergeJoin.LineNumber")+linesRead); //$NON-NLS-1$
return true;
}
/**
* @see StepInterface#init( be.ibridge.kettle.trans.step.StepMetaInterface , be.ibridge.kettle.trans.step.StepDataInterface)
*/
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(MergeJoinMeta)smi;
data=(MergeJoinData)sdi;
if (super.init(smi, sdi))
{
if (meta.getStepName1()==null || meta.getStepName2()==null)
{
logError(Messages.getString("MergeJoin.Log.BothTrueAndFalseNeeded")); //$NON-NLS-1$
return false;
}
String joinType = meta.getJoinType();
for (int i = 0; i < MergeJoinMeta.join_types.length; ++i)
{
if (joinType.equalsIgnoreCase(MergeJoinMeta.join_types[i]))
{
data.one_optional = MergeJoinMeta.one_optionals[i];
data.two_optional = MergeJoinMeta.two_optionals[i];
return true;
}
}
logError(Messages.getString("MergeJoin.Log.InvalidJoinType", meta.getJoinType())); //$NON-NLS-1$
return false;
}
return true;
}
/**
* Checks whether incoming rows are join compatible. This essentially
* means that the keys being compared should be of the same datatype
* and both rows should have the same number of keys specified
* @param row1 Reference row
* @param row2 Row to compare to
*
* @return true when templates are compatible.
*/
protected boolean isInputLayoutValid(Row row1, Row row2)
{
if (row1!=null && row2!=null)
{
// Compare the key types
String keyFields1[] = meta.getKeyFields1();
int nrKeyFields1 = keyFields1.length;
String keyFields2[] = meta.getKeyFields2();
int nrKeyFields2 = keyFields2.length;
if (nrKeyFields1 != nrKeyFields2)
{
logError("Number of keys do not match " + nrKeyFields1 + " vs " + nrKeyFields2);
return false;
}
for (int i=0;i<nrKeyFields1;i++)
{
Value v1 = row1.searchValue(keyFields1[i]);
if (v1 == null)
{
return false;
}
Value v2 = row2.searchValue(keyFields2[i]);
if (v2 == null)
{
return false;
}
if ( ! v1.equalValueType(v2, true) )
{
return false;
}
}
}
// we got here, all seems to be ok.
return true;
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic(Messages.getString("MergeJoin.Log.StartingToRun")); //$NON-NLS-1$
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError(Messages.getString("MergeJoin.Log.UnexpectedError")+" : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| Fix for bug #4634
git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@2608 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/be/ibridge/kettle/trans/step/mergejoin/MergeJoin.java | Fix for bug #4634 |
|
Java | lgpl-2.1 | 9220d588b3968f8568bf4550fe5c1c0750c2b429 | 0 | SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.minliu;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
/**
* A simple utility to do hand measurements of velocity using mouse
*
* @author Tobi Delbruck
*/
@Description("A simple utility to do hand measurements of velocity using mouse")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class Speedometer extends EventFilter2DMouseAdaptor implements FrameAnnotater {
private int currentTimestamp = 0;
private TimePoint startPoint, endPoint;
private boolean firstPoint = true;
private float speed = 0, distance, deltaTimestamp;
EngineeringFormat engFmt = new EngineeringFormat();
TextRenderer textRenderer = null;
public Speedometer(AEChip chip) {
super(chip);
}
@Override
public EventPacket<?> filterPacket(EventPacket<?> in) {
if (in.getSize() > 2) {
currentTimestamp = (in.getLastTimestamp() + in.getFirstTimestamp()) / 2;
}
return in;
}
@Override
public void resetFilter() {
firstPoint = true;
}
@Override
public void initFilter() {
}
@Override
public void mouseClicked(MouseEvent e) {
if (firstPoint) {
startPoint = new TimePoint(getMousePixel(e), currentTimestamp);
endPoint = null;
} else {
endPoint = new TimePoint(getMousePixel(e), currentTimestamp);
}
if (startPoint != null && endPoint != null) {
distance = (float) (endPoint.distance(startPoint));
deltaTimestamp = endPoint.t - startPoint.t;
speed = 1e6f * distance / deltaTimestamp;
log.info(String.format("%s pps", engFmt.format(speed)));
}
firstPoint = !firstPoint;
}
private class TimePoint extends Point {
int t;
public TimePoint(int t, int xx, int yy) {
super(xx, yy);
this.t = t;
}
public TimePoint(Point p, int t) {
super(p.x, p.y);
this.t = t;
}
}
@Override
public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable); //To change body of generated methods, choose Tools | Templates.
GL2 gl = drawable.getGL().getGL2();
drawCursor(gl, startPoint, new float[]{0, 1, 0, 1});
drawCursor(gl, endPoint, new float[]{1, 0, 0, 1});
if (startPoint != null && endPoint != null) {
gl.glColor3f(1, 1, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(startPoint.x, startPoint.y);
gl.glVertex2f(endPoint.x, endPoint.y);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 24), true, false);
}
textRenderer.setColor(1, 1, 0, 1);
String s = String.format("%s pps (%.0fpix /%ss)", engFmt.format(speed), distance, engFmt.format(1e-6f * deltaTimestamp));
textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
// Rectangle2D r = textRenderer.getBounds(s);
textRenderer.draw(s, (startPoint.x+endPoint.x)/2,(startPoint.y+endPoint.y)/2 );
textRenderer.endRendering();
}
}
private void drawCursor(GL2 gl, Point p, float[] color) {
if (p == null) {
return;
}
checkBlend(gl);
gl.glColor4fv(color, 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL2.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glColor4f(0, 0, 0, 1);
gl.glBegin(GL2.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glPopMatrix();
}
}
| src/ch/unizh/ini/jaer/projects/minliu/Speedometer.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch.unizh.ini.jaer.projects.minliu;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import net.sf.jaer.Description;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.EngineeringFormat;
/**
* A simple utility to do hand measurements of velocity using mouse
*
* @author Tobi Delbruck
*/
@Description("A simple utility to do hand measurements of velocity using mouse")
public class Speedometer extends EventFilter2DMouseAdaptor implements FrameAnnotater {
private int currentTimestamp = 0;
private TimePoint startPoint, endPoint;
private boolean firstPoint = true;
private float speed = 0, distance, deltaTimestamp;
EngineeringFormat engFmt = new EngineeringFormat();
TextRenderer textRenderer = null;
public Speedometer(AEChip chip) {
super(chip);
}
@Override
public EventPacket<?> filterPacket(EventPacket<?> in) {
if (in.getSize() > 2) {
currentTimestamp = (in.getLastTimestamp() + in.getFirstTimestamp()) / 2;
}
return in;
}
@Override
public void resetFilter() {
firstPoint = true;
}
@Override
public void initFilter() {
}
@Override
public void mouseClicked(MouseEvent e) {
if (firstPoint) {
startPoint = new TimePoint(getMousePixel(e), currentTimestamp);
endPoint = null;
} else {
endPoint = new TimePoint(getMousePixel(e), currentTimestamp);
}
if (startPoint != null && endPoint != null) {
distance = (float) (endPoint.distance(startPoint));
deltaTimestamp = endPoint.t - startPoint.t;
speed = 1e6f * distance / deltaTimestamp;
log.info(String.format("%s pps", engFmt.format(speed)));
}
firstPoint = !firstPoint;
}
private class TimePoint extends Point {
int t;
public TimePoint(int t, int xx, int yy) {
super(xx, yy);
this.t = t;
}
public TimePoint(Point p, int t) {
super(p.x, p.y);
this.t = t;
}
}
@Override
public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable); //To change body of generated methods, choose Tools | Templates.
GL2 gl = drawable.getGL().getGL2();
drawCursor(gl, startPoint, new float[]{0, 1, 0, 1});
drawCursor(gl, endPoint, new float[]{1, 0, 0, 1});
if (startPoint != null && endPoint != null) {
gl.glColor3f(1, 1, 0);
gl.glBegin(GL.GL_LINES);
gl.glVertex2f(startPoint.x, startPoint.y);
gl.glVertex2f(endPoint.x, endPoint.y);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 24), true, false);
}
textRenderer.setColor(1, 1, 0, 1);
String s = String.format("%s pps (%.0fpix /%ss)", engFmt.format(speed), distance, engFmt.format(1e-6f * deltaTimestamp));
textRenderer.beginRendering(drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
// Rectangle2D r = textRenderer.getBounds(s);
textRenderer.draw(s, (startPoint.x+endPoint.x)/2,(startPoint.y+endPoint.y)/2 );
textRenderer.endRendering();
}
}
private void drawCursor(GL2 gl, Point p, float[] color) {
if (p == null) {
return;
}
checkBlend(gl);
gl.glColor4fv(color, 0);
gl.glLineWidth(3f);
gl.glPushMatrix();
gl.glTranslatef(p.x, p.y, 0);
gl.glBegin(GL2.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glTranslatef(.5f, -.5f, 0);
gl.glColor4f(0, 0, 0, 1);
gl.glBegin(GL2.GL_LINES);
gl.glVertex2f(0, -CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(0, +CURSOR_SIZE_CHIP_PIXELS / 2);
gl.glVertex2f(-CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glVertex2f(+CURSOR_SIZE_CHIP_PIXELS / 2, 0);
gl.glEnd();
gl.glPopMatrix();
}
}
| added DevelopmentStatus | src/ch/unizh/ini/jaer/projects/minliu/Speedometer.java | added DevelopmentStatus |
|
Java | apache-2.0 | aa62aa0ddeb4e0724d0717310d32e54893257a74 | 0 | javasoze/sensei,senseidb/sensei,DataDog/sensei,DataDog/sensei,senseidb/sensei,javasoze/sensei,DataDog/sensei,javasoze/sensei,senseidb/sensei,javasoze/sensei,DataDog/sensei,senseidb/sensei | package com.sensei.search.nodes;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import proj.zoie.api.IndexReaderFactory;
import proj.zoie.api.Zoie;
import proj.zoie.api.ZoieIndexReader;
import com.browseengine.bobo.api.BoboIndexReader;
import com.linkedin.norbert.javacompat.cluster.ClusterClient;
import com.linkedin.norbert.javacompat.cluster.ZooKeeperClusterClient;
import com.linkedin.norbert.javacompat.network.NetworkServer;
import com.sensei.search.svc.api.SenseiException;
public class SenseiServer {
private static final Logger logger = Logger.getLogger(SenseiServer.class);
private static final String DEFAULT_CONF_FILE = "sensei-node.spring";
private static final String AVAILABLE = "available";
private static final String UNAVAILABLE = "unavailable";
private int _id;
private int _port;
private int[] _partitions;
private String _partitionString;
private NetworkServer _networkServer;
private ClusterClient _clusterClient;
private SenseiZoieFactory<?,?> _zoieFactory;
private SenseiIndexLoaderFactory _indexLoaderFactory;
private SenseiQueryBuilderFactory _queryBuilderFactory;
private SenseiNode _node;
private final HashSet<Zoie<BoboIndexReader,?,?>> zoieSystems = new HashSet<Zoie<BoboIndexReader,?,?>>();
private final HashSet<SenseiIndexLoader> indexLoaders = new HashSet<SenseiIndexLoader>();
private final MBeanServer mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
private final List<ObjectName> _registeredMBeans;
public SenseiServer(int id, int port, int[] partitions,
NetworkServer networkServer,
ClusterClient clusterClient,
SenseiZoieFactory<?,?> zoieSystemFactory,
SenseiIndexLoaderFactory indexLoaderFactory,
SenseiQueryBuilderFactory queryBuilderFactory){
this(id,port,partitions,null,networkServer,clusterClient,zoieSystemFactory,indexLoaderFactory,queryBuilderFactory);
}
public SenseiServer(int id, int port, int[] partitions,
File extDir,
NetworkServer networkServer,
ClusterClient clusterClient,
SenseiZoieFactory<?,?> zoieSystemFactory,
SenseiIndexLoaderFactory indexLoaderFactory,
SenseiQueryBuilderFactory queryBuilderFactory)
{
_registeredMBeans = new LinkedList<ObjectName>();
if (extDir!=null){
loadJars(extDir);
}
_id = id;
_port = port;
_partitions = partitions;
StringBuffer sb = new StringBuffer();
if(partitions.length > 0) sb.append(String.valueOf(partitions[0]));
for(int i = 1; i < partitions.length; i++)
{
sb.append(',');
sb.append(String.valueOf(partitions[i]));
}
_partitionString = sb.toString();
_networkServer = networkServer;
_clusterClient = clusterClient;
_zoieFactory = zoieSystemFactory;
_indexLoaderFactory = indexLoaderFactory;
_queryBuilderFactory = queryBuilderFactory;
}
private static String help(){
StringBuffer buffer = new StringBuffer();
buffer.append("Usage: [id] [port] [partitions] [conf.dir] [availability]\n");
buffer.append("====================================\n");
buffer.append("id - node id (integer), required\n");
buffer.append("port - server port (integer), required\n");
buffer.append("partitions - comma separated list of partition numbers this node can serve, required\n");
buffer.append("conf.dir - server configuration directory, required\n");
buffer.append("availability - \"available\" or \"unavailable\", optional default is \"available\"\n");
buffer.append("====================================\n");
return buffer.toString();
}
public Collection<Zoie<BoboIndexReader,?,?>> getZoieSystems(){
return zoieSystems;
}
private static void loadJars(File extDir)
{
File[] jarfiles = extDir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
if (jarfiles!=null && jarfiles.length > 0){
try{
URL[] jarURLs = new URL[jarfiles.length];
ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
for (int i=0;i<jarfiles.length;++i){
jarURLs[i] = new URL("jar:file://" + jarfiles[i].getAbsolutePath() + "!/");
}
URLClassLoader classloader = new URLClassLoader(jarURLs,parentLoader);
Thread.currentThread().setContextClassLoader(classloader);
}
catch(MalformedURLException e){
logger.error("problem loading extension: "+e.getMessage(),e);
}
}
}
public void shutdown(){
logger.info("unregistering mbeans...");
try{
if (_registeredMBeans.size()>0){
for (ObjectName name : _registeredMBeans){
mbeanServer.unregisterMBean(name);
}
_registeredMBeans.clear();
}
}
catch(Exception e){
logger.error(e.getMessage(),e);
}
try {
_node.shutdown();
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
// shutdown the loaders
for(SenseiIndexLoader loader : indexLoaders)
{
try{
loader.shutdown();
}
catch(SenseiException se){
logger.error(se.getMessage(),se);
}
}
indexLoaders.clear();
// shutdown the zoieSystems
for(Zoie<BoboIndexReader,?,?> zoieSystem : zoieSystems)
{
zoieSystem.shutdown();
}
zoieSystems.clear();
}
public void start(boolean available) throws Exception
{
Map<Integer,SenseiQueryBuilderFactory> builderFactoryMap = new HashMap<Integer, SenseiQueryBuilderFactory>();
Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> readerFactoryMap =
new HashMap<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>>();
// ClusterClient clusterClient = ClusterClientFactory.newInstance().newZookeeperClient();
String clusterName = _clusterClient.getServiceName();
logger.info("ClusterName: " + clusterName);
logger.info("Cluster info: " + _clusterClient.toString());
for (int part : _partitions){
//in simple case query builder is the same for each partition
builderFactoryMap.put(part, _queryBuilderFactory);
Zoie<BoboIndexReader,?,?> zoieSystem = _zoieFactory.getZoieInstance(_id,part);
// register ZoieSystemAdminMBean
String[] mbeannames = zoieSystem.getStandardMBeanNames();
for(String name : mbeannames)
{
ObjectName oname = new ObjectName(clusterName, "name", name + "-" + part);
try
{
mbeanServer.registerMBean(zoieSystem.getStandardMBean(name), oname);
_registeredMBeans.add(oname);
logger.info("registered mbean " + oname);
} catch(Exception e)
{
logger.error(e.getMessage(),e);
if (e instanceof InstanceAlreadyExistsException)
{
_registeredMBeans.add(oname);
}
}
}
if(!zoieSystems.contains(zoieSystem))
{
zoieSystem.start();
zoieSystems.add(zoieSystem);
}
SenseiIndexLoader loader = _indexLoaderFactory.getIndexLoader(part, zoieSystem);
if(!indexLoaders.contains(loader))
{
loader.start();
indexLoaders.add(loader);
}
readerFactoryMap.put(part, zoieSystem);
}
SenseiSearchContext ctx = new SenseiSearchContext(builderFactoryMap, readerFactoryMap);
SenseiNodeMessageHandler msgHandler = new SenseiNodeMessageHandler(ctx);
// create the zookeeper cluster client
// SenseiClusterClientImpl senseiClusterClient = new SenseiClusterClientImpl(clusterName, zookeeperURL, zookeeperTimeout, false);
_node = new SenseiNode(_networkServer, _clusterClient, _id, _port, msgHandler, _partitions);
_node.startup(available);
ObjectName name = new ObjectName(clusterName, "name", "sensei-server-"+_id);
try{
SenseiServerAdminMBean mbean = getAdminMBean();
mbeanServer.registerMBean(new StandardMBean(mbean, SenseiServerAdminMBean.class),name);
_registeredMBeans.add(name);
}
catch(Exception e){
logger.error(e.getMessage(),e);
if (e instanceof InstanceAlreadyExistsException){
_registeredMBeans.add(name);
}
}
}
private SenseiServerAdminMBean getAdminMBean()
{
return new SenseiServerAdminMBean()
{
public int getId()
{
return _id;
}
public int getPort()
{
return _port;
}
public String getPartitions()
{
return _partitionString;
}
public boolean isAvailable()
{
return _node.isAvailable();
}
public void setAvailable(boolean available)
{
_node.setAvailable(available);
}
};
}
public static void main(String[] args) throws Exception{
if (args.length<4){
System.out.println(help());
System.exit(1);
}
int id = 0;
int port = 0;
int[] partitions = null;
String[] partString = null;
File confDir = null;
try{
id = Integer.parseInt(args[0]);
port = Integer.parseInt(args[1]);
partString = args[2].split(",");
confDir = new File(args[3]);
partitions = new int[partString.length];
for (int i=0;i<partString.length;++i){
partitions[i] = Integer.parseInt(partString[i]);
}
}
catch(Exception e){
System.out.println(help());
System.exit(0);
}
boolean available = true;
for(int i = 4; i < args.length; i++)
{
if(args[i] != null)
{
if(AVAILABLE.equalsIgnoreCase(args[i]))
{
available = true;
}
if(UNAVAILABLE.equalsIgnoreCase(args[i]))
{
available = false;
}
}
}
File confFile = new File(confDir,DEFAULT_CONF_FILE);
File extDir = new File(confDir,"ext");
ApplicationContext springCtx = new FileSystemXmlApplicationContext("file:"+confFile.getAbsolutePath());
NetworkServer networkServer = (NetworkServer)springCtx.getBean("network-server");
ClusterClient clusterClient = (ZooKeeperClusterClient)springCtx.getBean("cluster-client");
SenseiZoieSystemFactory<?,?> zoieSystemFactory = (SenseiZoieSystemFactory<?,?>)springCtx.getBean("zoie-system-factory");
SenseiIndexLoaderFactory<?,?> indexLoaderFactory = (SenseiIndexLoaderFactory)springCtx.getBean("index-loader-factory");
SenseiQueryBuilderFactory queryBuilderFactory = (SenseiQueryBuilderFactory)springCtx.getBean("query-builder-factory");
final SenseiServer server = new SenseiServer(id, port, partitions,
extDir,
networkServer,
clusterClient,
zoieSystemFactory,
indexLoaderFactory,
queryBuilderFactory);
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
server.shutdown();
}
});
server.start(available);
}
}
| src/com/sensei/search/nodes/SenseiServer.java | package com.sensei.search.nodes;
import java.io.File;
import java.io.FilenameFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import proj.zoie.api.IndexReaderFactory;
import proj.zoie.api.Zoie;
import proj.zoie.api.ZoieIndexReader;
import com.browseengine.bobo.api.BoboIndexReader;
import com.linkedin.norbert.javacompat.cluster.ClusterClient;
import com.linkedin.norbert.javacompat.cluster.ZooKeeperClusterClient;
import com.linkedin.norbert.javacompat.network.NetworkServer;
import com.sensei.search.svc.api.SenseiException;
public class SenseiServer {
private static final Logger logger = Logger.getLogger(SenseiServer.class);
private static final String DEFAULT_CONF_FILE = "sensei-node.spring";
private static final String AVAILABLE = "available";
private static final String UNAVAILABLE = "unavailable";
private int _id;
private int _port;
private int[] _partitions;
private String _partitionString;
private NetworkServer _networkServer;
private ClusterClient _clusterClient;
private SenseiZoieFactory<?,?> _zoieFactory;
private SenseiIndexLoaderFactory _indexLoaderFactory;
private SenseiQueryBuilderFactory _queryBuilderFactory;
private SenseiNode _node;
private final HashSet<Zoie<BoboIndexReader,?,?>> zoieSystems = new HashSet<Zoie<BoboIndexReader,?,?>>();
private final HashSet<SenseiIndexLoader> indexLoaders = new HashSet<SenseiIndexLoader>();
private final MBeanServer mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
private final List<ObjectName> _registeredMBeans;
public SenseiServer(int id, int port, int[] partitions,
NetworkServer networkServer,
ClusterClient clusterClient,
SenseiZoieFactory<?,?> zoieSystemFactory,
SenseiIndexLoaderFactory indexLoaderFactory,
SenseiQueryBuilderFactory queryBuilderFactory){
this(id,port,partitions,null,networkServer,clusterClient,zoieSystemFactory,indexLoaderFactory,queryBuilderFactory);
}
public SenseiServer(int id, int port, int[] partitions,
File extDir,
NetworkServer networkServer,
ClusterClient clusterClient,
SenseiZoieFactory<?,?> zoieSystemFactory,
SenseiIndexLoaderFactory indexLoaderFactory,
SenseiQueryBuilderFactory queryBuilderFactory)
{
_registeredMBeans = new LinkedList<ObjectName>();
if (extDir!=null){
loadJars(extDir);
}
_id = id;
_port = port;
_partitions = partitions;
StringBuffer sb = new StringBuffer();
if(partitions.length > 0) sb.append(String.valueOf(partitions[0]));
for(int i = 1; i < partitions.length; i++)
{
sb.append(',');
sb.append(String.valueOf(partitions[i]));
}
_partitionString = sb.toString();
_networkServer = networkServer;
_clusterClient = clusterClient;
_zoieFactory = zoieSystemFactory;
_indexLoaderFactory = indexLoaderFactory;
_queryBuilderFactory = queryBuilderFactory;
}
private static String help(){
StringBuffer buffer = new StringBuffer();
buffer.append("Usage: [id] [port] [partitions] [conf.dir] [availability]\n");
buffer.append("====================================\n");
buffer.append("id - node id (integer), required\n");
buffer.append("port - server port (integer), required\n");
buffer.append("partitions - comma separated list of partition numbers this node can serve, required\n");
buffer.append("conf.dir - server configuration directory, required\n");
buffer.append("availability - \"available\" or \"unavailable\", optional default is \"available\"\n");
buffer.append("====================================\n");
return buffer.toString();
}
public Collection<Zoie<BoboIndexReader,?,?>> getZoieSystems(){
return zoieSystems;
}
private static void loadJars(File extDir)
{
File[] jarfiles = extDir.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name) {
return name.endsWith(".jar");
}
});
if (jarfiles!=null && jarfiles.length > 0){
try{
URL[] jarURLs = new URL[jarfiles.length];
ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
for (int i=0;i<jarfiles.length;++i){
jarURLs[i] = new URL("jar:file://" + jarfiles[i].getAbsolutePath() + "!/");
}
URLClassLoader classloader = new URLClassLoader(jarURLs,parentLoader);
Thread.currentThread().setContextClassLoader(classloader);
}
catch(MalformedURLException e){
logger.error("problem loading extension: "+e.getMessage(),e);
}
}
}
public void shutdown(){
logger.info("unregistering mbeans...");
try{
if (_registeredMBeans.size()>0){
for (ObjectName name : _registeredMBeans){
mbeanServer.unregisterMBean(name);
}
_registeredMBeans.clear();
}
}
catch(Exception e){
logger.error(e.getMessage(),e);
}
try {
_node.shutdown();
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
// shutdown the loaders
for(SenseiIndexLoader loader : indexLoaders)
{
try{
loader.shutdown();
}
catch(SenseiException se){
logger.error(se.getMessage(),se);
}
}
indexLoaders.clear();
// shutdown the zoieSystems
for(Zoie<BoboIndexReader,?,?> zoieSystem : zoieSystems)
{
zoieSystem.shutdown();
}
zoieSystems.clear();
}
public void start(boolean available) throws Exception
{
Map<Integer,SenseiQueryBuilderFactory> builderFactoryMap = new HashMap<Integer, SenseiQueryBuilderFactory>();
Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> readerFactoryMap =
new HashMap<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>>();
// ClusterClient clusterClient = ClusterClientFactory.newInstance().newZookeeperClient();
String clusterName = _clusterClient.getServiceName();
logger.info("ClusterName: " + clusterName);
logger.info("Cluster info: " + _clusterClient.toString());
for (int part : _partitions){
//in simple case query builder is the same for each partition
builderFactoryMap.put(part, _queryBuilderFactory);
Zoie<BoboIndexReader,?,?> zoieSystem = _zoieFactory.getZoieInstance(_id,part);
// register ZoieSystemAdminMBean
String[] mbeannames = zoieSystem.getStandardMBeanNames();
for(String name : mbeannames)
{
ObjectName oname = new ObjectName(clusterName, "name", name + "-" + part);
try
{
mbeanServer.registerMBean(zoieSystem.getStandardMBean(name), oname);
logger.info("registered mbean " + oname);
} catch(Exception e)
{
logger.error(e.getMessage(),e);
if (e instanceof InstanceAlreadyExistsException)
{
_registeredMBeans.add(oname);
}
}
}
if(!zoieSystems.contains(zoieSystem))
{
zoieSystem.start();
zoieSystems.add(zoieSystem);
}
SenseiIndexLoader loader = _indexLoaderFactory.getIndexLoader(part, zoieSystem);
if(!indexLoaders.contains(loader))
{
loader.start();
indexLoaders.add(loader);
}
readerFactoryMap.put(part, zoieSystem);
}
SenseiSearchContext ctx = new SenseiSearchContext(builderFactoryMap, readerFactoryMap);
SenseiNodeMessageHandler msgHandler = new SenseiNodeMessageHandler(ctx);
// create the zookeeper cluster client
// SenseiClusterClientImpl senseiClusterClient = new SenseiClusterClientImpl(clusterName, zookeeperURL, zookeeperTimeout, false);
_node = new SenseiNode(_networkServer, _clusterClient, _id, _port, msgHandler, _partitions);
_node.startup(available);
ObjectName name = new ObjectName(clusterName, "name", "sensei-server-"+_id);
try{
SenseiServerAdminMBean mbean = getAdminMBean();
mbeanServer.registerMBean(new StandardMBean(mbean, SenseiServerAdminMBean.class),name);
_registeredMBeans.add(name);
}
catch(Exception e){
logger.error(e.getMessage(),e);
if (e instanceof InstanceAlreadyExistsException){
_registeredMBeans.add(name);
}
}
}
private SenseiServerAdminMBean getAdminMBean()
{
return new SenseiServerAdminMBean()
{
public int getId()
{
return _id;
}
public int getPort()
{
return _port;
}
public String getPartitions()
{
return _partitionString;
}
public boolean isAvailable()
{
return _node.isAvailable();
}
public void setAvailable(boolean available)
{
_node.setAvailable(available);
}
};
}
public static void main(String[] args) throws Exception{
if (args.length<4){
System.out.println(help());
System.exit(1);
}
int id = 0;
int port = 0;
int[] partitions = null;
String[] partString = null;
File confDir = null;
try{
id = Integer.parseInt(args[0]);
port = Integer.parseInt(args[1]);
partString = args[2].split(",");
confDir = new File(args[3]);
partitions = new int[partString.length];
for (int i=0;i<partString.length;++i){
partitions[i] = Integer.parseInt(partString[i]);
}
}
catch(Exception e){
System.out.println(help());
System.exit(0);
}
boolean available = true;
for(int i = 4; i < args.length; i++)
{
if(args[i] != null)
{
if(AVAILABLE.equalsIgnoreCase(args[i]))
{
available = true;
}
if(UNAVAILABLE.equalsIgnoreCase(args[i]))
{
available = false;
}
}
}
File confFile = new File(confDir,DEFAULT_CONF_FILE);
File extDir = new File(confDir,"ext");
ApplicationContext springCtx = new FileSystemXmlApplicationContext("file:"+confFile.getAbsolutePath());
NetworkServer networkServer = (NetworkServer)springCtx.getBean("network-server");
ClusterClient clusterClient = (ZooKeeperClusterClient)springCtx.getBean("cluster-client");
SenseiZoieSystemFactory<?,?> zoieSystemFactory = (SenseiZoieSystemFactory<?,?>)springCtx.getBean("zoie-system-factory");
SenseiIndexLoaderFactory<?,?> indexLoaderFactory = (SenseiIndexLoaderFactory)springCtx.getBean("index-loader-factory");
SenseiQueryBuilderFactory queryBuilderFactory = (SenseiQueryBuilderFactory)springCtx.getBean("query-builder-factory");
final SenseiServer server = new SenseiServer(id, port, partitions,
extDir,
networkServer,
clusterClient,
zoieSystemFactory,
indexLoaderFactory,
queryBuilderFactory);
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
server.shutdown();
}
});
server.start(available);
}
}
| fixed bug of unregistering mbean
| src/com/sensei/search/nodes/SenseiServer.java | fixed bug of unregistering mbean |
|
Java | apache-2.0 | 59d5b1b05a16a2b374c6300dcdd395570d34a149 | 0 | GideonLeGrange/panstamp-java | package me.legrange.panstamp.def;
/**
* A device param
* @author gideon
*/
public class Param {
Param(String name, Type type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public Type getType() {
return type;
}
public Position getPosition() {
return position;
}
void setPosition(Position position) {
this.position = position;
}
public Size getSize() {
return size;
}
void setSize(Size size) {
this.size = size;
}
public String getDef() {
return def;
}
void setDef(String def) {
this.def = def;
}
public String getVerif() {
return verif;
}
void setVerif(String verif) {
this.verif = verif;
}
private final String name;
private final Type type;
private Position position;
private Size size;
private String def;
private String verif;
}
| src/main/java/me/legrange/panstamp/def/Param.java | package me.legrange.panstamp.def;
import java.util.List;
/**
* A device param
* @author gideon
*/
public class Param {
Param(String name, Type type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public Type getType() {
return type;
}
public Position getPosition() {
return position;
}
void setPosition(Position position) {
this.position = position;
}
public Size getSize() {
return size;
}
void setSize(Size size) {
this.size = size;
}
public String getDef() {
return def;
}
void setDef(String def) {
this.def = def;
}
public String getVerif() {
return verif;
}
void setVerif(String verif) {
this.verif = verif;
}
private final String name;
private final Type type;
private Position position;
private Size size;
private String def;
private String verif;
}
| Removed stray import | src/main/java/me/legrange/panstamp/def/Param.java | Removed stray import |
|
Java | apache-2.0 | 53787f2fa2153d4de36981f4d718bb378a6b1944 | 0 | samanalysis/incubator-groovy,apache/incubator-groovy,i55ac/incubator-groovy,nobeans/incubator-groovy,alien11689/groovy-core,kenzanmedia/incubator-groovy,gillius/incubator-groovy,yukangguo/incubator-groovy,traneHead/groovy-core,rabbitcount/incubator-groovy,ebourg/incubator-groovy,tkruse/incubator-groovy,jwagenleitner/incubator-groovy,paulk-asert/incubator-groovy,alien11689/incubator-groovy,fpavageau/groovy,pickypg/incubator-groovy,tkruse/incubator-groovy,mariogarcia/groovy-core,antoaravinth/incubator-groovy,aim-for-better/incubator-groovy,nobeans/incubator-groovy,eginez/incubator-groovy,tkruse/incubator-groovy,apache/groovy,jwagenleitner/incubator-groovy,alien11689/incubator-groovy,paplorinc/incubator-groovy,kenzanmedia/incubator-groovy,i55ac/incubator-groovy,adjohnson916/incubator-groovy,russel/incubator-groovy,rlovtangen/groovy-core,sagarsane/incubator-groovy,ChanJLee/incubator-groovy,kenzanmedia/incubator-groovy,PascalSchumacher/incubator-groovy,paulk-asert/incubator-groovy,kidaa/incubator-groovy,yukangguo/incubator-groovy,paulk-asert/groovy,samanalysis/incubator-groovy,bsideup/groovy-core,PascalSchumacher/incubator-groovy,christoph-frick/groovy-core,russel/groovy,pledbrook/incubator-groovy,aaronzirbes/incubator-groovy,nobeans/incubator-groovy,sagarsane/incubator-groovy,paplorinc/incubator-groovy,taoguan/incubator-groovy,paulk-asert/incubator-groovy,adjohnson916/incubator-groovy,shils/groovy,genqiang/incubator-groovy,sagarsane/groovy-core,ebourg/groovy-core,alien11689/groovy-core,samanalysis/incubator-groovy,alien11689/groovy-core,alien11689/groovy-core,graemerocher/incubator-groovy,alien11689/incubator-groovy,apache/groovy,ebourg/groovy-core,christoph-frick/groovy-core,rlovtangen/groovy-core,graemerocher/incubator-groovy,aaronzirbes/incubator-groovy,apache/incubator-groovy,EPadronU/incubator-groovy,kidaa/incubator-groovy,pledbrook/incubator-groovy,mariogarcia/groovy-core,aaronzirbes/incubator-groovy,apache/groovy,shils/incubator-groovy,rlovtangen/groovy-core,adjohnson916/groovy-core,nkhuyu/incubator-groovy,russel/incubator-groovy,eginez/incubator-groovy,christoph-frick/groovy-core,gillius/incubator-groovy,groovy/groovy-core,kidaa/incubator-groovy,ChanJLee/incubator-groovy,armsargis/groovy,russel/groovy,adjohnson916/incubator-groovy,paulk-asert/incubator-groovy,adjohnson916/groovy-core,gillius/incubator-groovy,shils/incubator-groovy,taoguan/incubator-groovy,mariogarcia/groovy-core,graemerocher/incubator-groovy,antoaravinth/incubator-groovy,bsideup/incubator-groovy,shils/groovy,bsideup/incubator-groovy,guangying945/incubator-groovy,guangying945/incubator-groovy,taoguan/incubator-groovy,EPadronU/incubator-groovy,jwagenleitner/groovy,apache/incubator-groovy,adjohnson916/groovy-core,russel/incubator-groovy,shils/groovy,dpolivaev/groovy,PascalSchumacher/incubator-groovy,armsargis/groovy,pickypg/incubator-groovy,shils/incubator-groovy,groovy/groovy-core,taoguan/incubator-groovy,genqiang/incubator-groovy,pledbrook/incubator-groovy,rlovtangen/groovy-core,eginez/incubator-groovy,samanalysis/incubator-groovy,paulk-asert/groovy,apache/incubator-groovy,ebourg/groovy-core,jwagenleitner/incubator-groovy,adjohnson916/groovy-core,avafanasiev/groovy,i55ac/incubator-groovy,upadhyayap/incubator-groovy,jwagenleitner/incubator-groovy,bsideup/incubator-groovy,sagarsane/groovy-core,paulk-asert/incubator-groovy,sagarsane/groovy-core,kenzanmedia/incubator-groovy,groovy/groovy-core,groovy/groovy-core,pledbrook/incubator-groovy,sagarsane/incubator-groovy,pickypg/incubator-groovy,tkruse/incubator-groovy,ebourg/groovy-core,rabbitcount/incubator-groovy,dpolivaev/groovy,dpolivaev/groovy,traneHead/groovy-core,rlovtangen/groovy-core,aim-for-better/incubator-groovy,upadhyayap/incubator-groovy,traneHead/groovy-core,EPadronU/incubator-groovy,apache/groovy,upadhyayap/incubator-groovy,avafanasiev/groovy,sagarsane/groovy-core,guangying945/incubator-groovy,guangying945/incubator-groovy,jwagenleitner/groovy,avafanasiev/groovy,fpavageau/groovy,adjohnson916/groovy-core,shils/incubator-groovy,armsargis/groovy,PascalSchumacher/incubator-groovy,shils/groovy,jwagenleitner/groovy,upadhyayap/incubator-groovy,sagarsane/incubator-groovy,christoph-frick/groovy-core,kidaa/incubator-groovy,paplorinc/incubator-groovy,alien11689/groovy-core,genqiang/incubator-groovy,aim-for-better/incubator-groovy,armsargis/groovy,ebourg/incubator-groovy,adjohnson916/incubator-groovy,paplorinc/incubator-groovy,nkhuyu/incubator-groovy,yukangguo/incubator-groovy,rabbitcount/incubator-groovy,alien11689/incubator-groovy,mariogarcia/groovy-core,sagarsane/groovy-core,bsideup/groovy-core,i55ac/incubator-groovy,russel/incubator-groovy,ebourg/incubator-groovy,ChanJLee/incubator-groovy,aaronzirbes/incubator-groovy,nobeans/incubator-groovy,ebourg/incubator-groovy,nkhuyu/incubator-groovy,bsideup/groovy-core,bsideup/groovy-core,ChanJLee/incubator-groovy,rabbitcount/incubator-groovy,fpavageau/groovy,antoaravinth/incubator-groovy,fpavageau/groovy,ebourg/groovy-core,eginez/incubator-groovy,paulk-asert/groovy,gillius/incubator-groovy,aim-for-better/incubator-groovy,EPadronU/incubator-groovy,genqiang/incubator-groovy,dpolivaev/groovy,mariogarcia/groovy-core,pickypg/incubator-groovy,jwagenleitner/groovy,nkhuyu/incubator-groovy,bsideup/incubator-groovy,antoaravinth/incubator-groovy,russel/groovy,PascalSchumacher/incubator-groovy,groovy/groovy-core,paulk-asert/groovy,avafanasiev/groovy,traneHead/groovy-core,russel/groovy,graemerocher/incubator-groovy,christoph-frick/groovy-core,yukangguo/incubator-groovy | /*
* Copyright 2003-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.reflection;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaMethod;
import groovy.lang.MissingMethodException;
import org.codehaus.groovy.classgen.asm.BytecodeHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.codehaus.groovy.runtime.callsite.*;
import org.codehaus.groovy.runtime.metaclass.MethodHelper;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Alex.Tkachman
*/
public class CachedMethod extends MetaMethod implements Comparable {
public final CachedClass cachedClass;
private final Method cachedMethod;
private int hashCode;
private static MyComparator comparator = new MyComparator();
private SoftReference<Constructor> pogoCallSiteConstructor, pojoCallSiteConstructor, staticCallSiteConstructor;
private boolean skipCompiled;
public CachedMethod(CachedClass clazz, Method method) {
this.cachedMethod = method;
this.cachedClass = clazz;
}
public CachedMethod(Method method) {
this(ReflectionCache.getCachedClass(method.getDeclaringClass()),method);
}
public static CachedMethod find(Method method) {
CachedMethod[] methods = ReflectionCache.getCachedClass(method.getDeclaringClass()).getMethods();
// for (int i = 0; i < methods.length; i++) {
// CachedMethod cachedMethod = methods[i];
// if (cachedMethod.cachedMethod.equals(method))
// return cachedMethod;
// }
// return null;
int i = Arrays.binarySearch(methods, method, comparator);
if (i < 0)
return null;
return methods[i];
}
protected Class[] getPT() {
return cachedMethod.getParameterTypes();
}
public String getName() {
return cachedMethod.getName();
}
public String getDescriptor() {
return BytecodeHelper.getMethodDescriptor(getReturnType(), getNativeParameterTypes());
}
public CachedClass getDeclaringClass() {
return cachedClass;
}
public final Object invoke(Object object, Object[] arguments) {
try {
return cachedMethod.invoke(object, arguments);
} catch (IllegalArgumentException e) {
throw new InvokerInvocationException(e);
} catch (IllegalAccessException e) {
throw new InvokerInvocationException(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw (cause instanceof RuntimeException && !(cause instanceof MissingMethodException)) ?
(RuntimeException) cause : new InvokerInvocationException(e);
}
}
public ParameterTypes getParamTypes() {
return null;
}
public Class getReturnType() {
return cachedMethod.getReturnType();
}
public int getParamsCount() {
return getParameterTypes().length;
}
public int getModifiers() {
return cachedMethod.getModifiers();
}
public String getSignature() {
return getName() + getDescriptor();
}
public final Method setAccessible() {
// if (queuedToCompile.compareAndSet(false,true)) {
// if (isCompilable())
// CompileThread.addMethod(this);
// }
return cachedMethod;
}
public boolean isStatic() {
return MethodHelper.isStatic(cachedMethod);
}
public int compareTo(Object o) {
if (o instanceof CachedMethod)
return compareToCachedMethod((CachedMethod)o);
else
return compareToMethod((Method)o);
}
private int compareToCachedMethod(CachedMethod m) {
if (m == null)
return -1;
final int strComp = getName().compareTo(m.getName());
if (strComp != 0)
return strComp;
final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName());
if (retComp != 0)
return retComp;
CachedClass[] params = getParameterTypes();
CachedClass [] mparams = m.getParameterTypes();
final int pd = params.length - mparams.length;
if (pd != 0)
return pd;
for (int i = 0; i != params.length; ++i)
{
final int nameComp = params[i].getName().compareTo(mparams[i].getName());
if (nameComp != 0)
return nameComp;
}
throw new RuntimeException("Should never happen");
}
private int compareToMethod(Method m) {
if (m == null)
return -1;
final int strComp = getName().compareTo(m.getName());
if (strComp != 0)
return strComp;
final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName());
if (retComp != 0)
return retComp;
CachedClass[] params = getParameterTypes();
Class [] mparams = m.getParameterTypes();
final int pd = params.length - mparams.length;
if (pd != 0)
return pd;
for (int i = 0; i != params.length; ++i)
{
final int nameComp = params[i].getName().compareTo(mparams[i].getName());
if (nameComp != 0)
return nameComp;
}
return 0;
}
public boolean equals(Object o) {
return (o instanceof CachedMethod && cachedMethod.equals(((CachedMethod)o).cachedMethod))
|| (o instanceof Method && cachedMethod.equals(o));
}
public int hashCode() {
if (hashCode == 0) {
hashCode = cachedMethod.hashCode();
if (hashCode == 0)
hashCode = 0xcafebebe;
}
return hashCode;
}
public String toString() {
return cachedMethod.toString();
}
private Constructor getConstrcutor(SoftReference<Constructor> ref) {
if (ref==null) return null;
return ref.get();
}
public CallSite createPogoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(pogoCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compilePogoMethod(this);
}
if (constr != null) {
pogoCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new PogoMetaMethodSite.PogoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
public CallSite createPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(pojoCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compilePojoMethod(this);
}
if (constr != null) {
pojoCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new PojoMetaMethodSite.PojoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
public CallSite createStaticMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(staticCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compileStaticMethod(this);
}
if (constr != null) {
staticCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new StaticMetaMethodSite.StaticMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
@Deprecated
public boolean hasPogoCallSiteConstructor() {
return pogoCallSiteConstructor != null && pogoCallSiteConstructor.get() != null;
}
@Deprecated
public boolean hasPojoCallSiteConstructor() {
return pojoCallSiteConstructor != null && pojoCallSiteConstructor.get() != null;
}
@Deprecated()
public boolean hasStaticCallSiteConstructor() {
return staticCallSiteConstructor != null && staticCallSiteConstructor.get() != null;
}
private static class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 instanceof CachedMethod)
return ((CachedMethod)o1).compareTo(o2);
else if (o2 instanceof CachedMethod)
return -((CachedMethod)o2).compareTo(o1);
else
// really, this should never happen, it's evidence of corruption if it does
throw new ClassCastException("One of the two comparables must be a CachedMethod");
}
}
public Method getCachedMethod() {
return cachedMethod;
}
// private static class CompileThread extends Thread {
// static final LinkedBlockingQueue queue = new LinkedBlockingQueue();
//
// static {
// new CompileThread().start();
// }
//
// private CompileThread() {
// setDaemon(true);
// setPriority(Thread.MAX_PRIORITY-2);
// }
//
// public void run() {
// try {
// while (true) {
// final CachedMethod method = (CachedMethod) queue.take();
// if (method != null) {
// CallSiteGenerator.compilePogoMethod(method);
// }
// }
// }
// catch (InterruptedException e) {//
// }
// }
//
// public static void addMethod (CachedMethod method) {
// try {
// queue.put(method);
// } catch (InterruptedException e) {
// }
// }
// }
}
| src/main/org/codehaus/groovy/reflection/CachedMethod.java | /*
* Copyright 2003-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.reflection;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaMethod;
import groovy.lang.MissingMethodException;
import org.codehaus.groovy.classgen.asm.BytecodeHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.codehaus.groovy.runtime.callsite.*;
import org.codehaus.groovy.runtime.metaclass.MethodHelper;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Alex.Tkachman
*/
public class CachedMethod extends MetaMethod implements Comparable {
public final CachedClass cachedClass;
private final Method cachedMethod;
private int hashCode;
private static MyComparator comparator = new MyComparator();
private SoftReference<Constructor> pogoCallSiteConstructor, pojoCallSiteConstructor, staticCallSiteConstructor;
private boolean skipCompiled;
public CachedMethod(CachedClass clazz, Method method) {
this.cachedMethod = method;
this.cachedClass = clazz;
}
public CachedMethod(Method method) {
this(ReflectionCache.getCachedClass(method.getDeclaringClass()),method);
}
public static CachedMethod find(Method method) {
CachedMethod[] methods = ReflectionCache.getCachedClass(method.getDeclaringClass()).getMethods();
// for (int i = 0; i < methods.length; i++) {
// CachedMethod cachedMethod = methods[i];
// if (cachedMethod.cachedMethod.equals(method))
// return cachedMethod;
// }
// return null;
int i = Arrays.binarySearch(methods, method, comparator);
if (i < 0)
return null;
return methods[i];
}
protected Class[] getPT() {
return cachedMethod.getParameterTypes();
}
public String getName() {
return cachedMethod.getName();
}
public String getDescriptor() {
return BytecodeHelper.getMethodDescriptor(getReturnType(), getNativeParameterTypes());
}
public CachedClass getDeclaringClass() {
return cachedClass;
}
public final Object invoke(Object object, Object[] arguments) {
try {
return cachedMethod.invoke(object, arguments);
} catch (IllegalArgumentException e) {
throw new InvokerInvocationException(e);
} catch (IllegalAccessException e) {
throw new InvokerInvocationException(e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw (cause instanceof RuntimeException && !(cause instanceof MissingMethodException)) ?
(RuntimeException) cause : new InvokerInvocationException(e);
}
}
public ParameterTypes getParamTypes() {
return null;
}
public Class getReturnType() {
return cachedMethod.getReturnType();
}
public int getParamsCount() {
return getParameterTypes().length;
}
public int getModifiers() {
return cachedMethod.getModifiers();
}
public String getSignature() {
return getName() + getDescriptor();
}
public final Method setAccessible() {
// if (queuedToCompile.compareAndSet(false,true)) {
// if (isCompilable())
// CompileThread.addMethod(this);
// }
return cachedMethod;
}
public boolean isStatic() {
return MethodHelper.isStatic(cachedMethod);
}
public int compareTo(Object o) {
if (o instanceof CachedMethod)
return compareToCachedMethod((CachedMethod)o);
else
return compareToMethod((Method)o);
}
private int compareToCachedMethod(CachedMethod m) {
if (m == null)
return -1;
final int strComp = getName().compareTo(m.getName());
if (strComp != 0)
return strComp;
final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName());
if (retComp != 0)
return retComp;
CachedClass[] params = getParameterTypes();
CachedClass [] mparams = m.getParameterTypes();
final int pd = params.length - mparams.length;
if (pd != 0)
return pd;
for (int i = 0; i != params.length; ++i)
{
final int nameComp = params[i].getName().compareTo(mparams[i].getName());
if (nameComp != 0)
return nameComp;
}
throw new RuntimeException("Should never happen");
}
private int compareToMethod(Method m) {
if (m == null)
return -1;
final int strComp = getName().compareTo(m.getName());
if (strComp != 0)
return strComp;
final int retComp = getReturnType().getName().compareTo(m.getReturnType().getName());
if (retComp != 0)
return retComp;
CachedClass[] params = getParameterTypes();
Class [] mparams = m.getParameterTypes();
final int pd = params.length - mparams.length;
if (pd != 0)
return pd;
for (int i = 0; i != params.length; ++i)
{
final int nameComp = params[i].getName().compareTo(mparams[i].getName());
if (nameComp != 0)
return nameComp;
}
return 0;
}
public boolean equals(Object o) {
return (o instanceof CachedMethod && cachedMethod.equals(((CachedMethod)o).cachedMethod))
|| (o instanceof Method && cachedMethod.equals(o));
}
public int hashCode() {
if (hashCode == 0) {
hashCode = cachedMethod.hashCode();
if (hashCode == 0)
hashCode = 0xcafebebe;
}
return hashCode;
}
public String toString() {
return cachedMethod.toString();
}
private Constructor getConstrcutor(SoftReference<Constructor> ref) {
if (ref==null) return null;
return ref.get();
}
public CallSite createPogoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(pogoCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compilePogoMethod(this);
}
if (constr != null) {
pogoCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new PogoMetaMethodSite.PogoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
public CallSite createPojoMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(pojoCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compilePojoMethod(this);
}
if (constr != null) {
pojoCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new PojoMetaMethodSite.PojoCachedMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
public CallSite createStaticMetaMethodSite(CallSite site, MetaClassImpl metaClass, Class[] params) {
if (!skipCompiled) {
Constructor constr = getConstrcutor(staticCallSiteConstructor);
if (constr==null) {
if (CallSiteGenerator.isCompilable(this)) {
constr = CallSiteGenerator.compileStaticMethod(this);
}
if (constr != null) {
staticCallSiteConstructor = new SoftReference<Constructor> (constr);
} else {
skipCompiled = true;
}
}
if (constr!=null) {
try {
return (CallSite) constr.newInstance(site, metaClass, this, params, constr);
} catch (Error e) {
skipCompiled=true;
throw e;
} catch (Throwable e) {
skipCompiled=true;
}
}
}
return new StaticMetaMethodSite.StaticMetaMethodSiteNoUnwrapNoCoerce(site, metaClass, this, params);
}
//TODO: deprecate and remove this method
public boolean hasPogoCallSiteConstructor() {
return pogoCallSiteConstructor != null && pogoCallSiteConstructor.get() != null;
}
//TODO: deprecate and remove this method
public boolean hasPojoCallSiteConstructor() {
return pojoCallSiteConstructor != null && pojoCallSiteConstructor.get() != null;
}
//TODO: deprecate and remove this method
public boolean hasStaticCallSiteConstructor() {
return staticCallSiteConstructor != null && staticCallSiteConstructor.get() != null;
}
private static class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 instanceof CachedMethod)
return ((CachedMethod)o1).compareTo(o2);
else if (o2 instanceof CachedMethod)
return -((CachedMethod)o2).compareTo(o1);
else
// really, this should never happen, it's evidence of corruption if it does
throw new ClassCastException("One of the two comparables must be a CachedMethod");
}
}
public Method getCachedMethod() {
return cachedMethod;
}
// private static class CompileThread extends Thread {
// static final LinkedBlockingQueue queue = new LinkedBlockingQueue();
//
// static {
// new CompileThread().start();
// }
//
// private CompileThread() {
// setDaemon(true);
// setPriority(Thread.MAX_PRIORITY-2);
// }
//
// public void run() {
// try {
// while (true) {
// final CachedMethod method = (CachedMethod) queue.take();
// if (method != null) {
// CallSiteGenerator.compilePogoMethod(method);
// }
// }
// }
// catch (InterruptedException e) {//
// }
// }
//
// public static void addMethod (CachedMethod method) {
// try {
// queue.put(method);
// } catch (InterruptedException e) {
// }
// }
// }
}
| deprecate some methods that are now unused
git-svn-id: aa43ce4553b005588bb3cc6c16966320b011facb@21510 a5544e8c-8a19-0410-ba12-f9af4593a198
| src/main/org/codehaus/groovy/reflection/CachedMethod.java | deprecate some methods that are now unused |
|
Java | apache-2.0 | b3f5b9f96a61a9cf44676e047ccdb2876afa2546 | 0 | whorbowicz/intellij-scala,advancedxy/intellij-scala,double-y/translation-idea-plugin,jastice/intellij-scala,jeantil/intellij-scala,ghik/intellij-scala,jastice/intellij-scala,JetBrains/intellij-scala,triplequote/intellij-scala,ghik/intellij-scala,advancedxy/intellij-scala,jeantil/intellij-scala,whorbowicz/intellij-scala,jastice/intellij-scala,Im-dex/intellij-scala,ilinum/intellij-scala,igrocki/intellij-scala,double-y/translation-idea-plugin,katejim/intellij-scala,ghik/intellij-scala,JetBrains/intellij-scala,katejim/intellij-scala,Im-dex/intellij-scala,loskutov/intellij-scala,Im-dex/intellij-scala,double-y/translation-idea-plugin,ilinum/intellij-scala,loskutov/intellij-scala,advancedxy/intellij-scala,loskutov/intellij-scala,ilinum/intellij-scala,triplequote/intellij-scala,jastice/intellij-scala,katejim/intellij-scala,triplequote/intellij-scala,jeantil/intellij-scala,igrocki/intellij-scala,igrocki/intellij-scala,whorbowicz/intellij-scala | /*
* Copyright 2000-2008 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.scala;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import com.intellij.util.PairConsumer;
import org.jetbrains.annotations.NotNull;
/**
* @author ilyas
*/
public class ScalaFileTypeFactory extends FileTypeFactory {
public void createFileTypes(final @NotNull PairConsumer<FileType, String> consumer) {
consumer.consume(ScalaFileType.SCALA_FILE_TYPE, "scala");
}
//todo Uncomment after 28th August 2008 :)
/*public void createFileTypes(final @NotNull FileTypeConsumer consumer) {
consumer.consume(ScalaFileType.SCALA_FILE_TYPE, ScalaFileType.DEFAULT_EXTENSION);
}*/
} | src/org/jetbrains/plugins/scala/ScalaFileTypeFactory.java | /*
* Copyright 2000-2008 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.scala;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import com.intellij.util.PairConsumer;
import org.jetbrains.annotations.NotNull;
/**
* @author ilyas
*/
public class ScalaFileTypeFactory extends FileTypeFactory {
public void createFileTypes(final @NotNull PairConsumer<FileType, String> consumer) {
consumer.consume(ScalaFileType.SCALA_FILE_TYPE, "scala");
}
/*public void createFileTypes(final @NotNull FileTypeConsumer consumer) {
consumer.consume(ScalaFileType.SCALA_FILE_TYPE, ScalaFileType.DEFAULT_EXTENSION);
}*/
} |
git-svn-id: http://svn.jetbrains.org/idea/Trunk/scala@18784 59f64563-22e8-0310-8d2c-98a15e1539f2
| src/org/jetbrains/plugins/scala/ScalaFileTypeFactory.java | ||
Java | apache-2.0 | 5474df3534de0eedbe99a6197c4a791c72e45f1c | 0 | treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag,treasure-data/digdag | package acceptance;
import com.google.common.base.Throwables;
import org.junit.Rule;
import org.junit.Test;
import io.digdag.core.database.DataSourceProvider;
import utils.CommandStatus;
import utils.TemporaryDigdagServer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.sql.Connection;
import java.sql.Statement;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import static utils.TestUtils.expect;
import static utils.TestUtils.main;
public class ServerJmxIT
{
public static final Pattern JMX_PORT_PATTERN = Pattern.compile("\\s*JMX agent started on port (\\d+)\\s*");
@Rule
public TemporaryDigdagServer server = TemporaryDigdagServer.builder()
.inProcess(false)
.configuration(
"server.jmx.port=0",
"database.leakDetectionThreshold=60000",
"database.maximumPoolSize=3")
.build();
private static JMXConnector connectJmx(TemporaryDigdagServer server)
throws IOException
{
Matcher matcher = JMX_PORT_PATTERN.matcher(server.outUtf8());
assertThat(matcher.find(), is(true));
int port = Integer.parseInt(matcher.group(1));
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
return JMXConnectorFactory.connect(url, null);
}
catch (MalformedURLException ex) {
throw Throwables.propagate(ex);
}
}
@Test
public void verifyJmx()
throws Exception
{
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object uptime = beans.getAttribute(ObjectName.getInstance("java.lang", "type", "Runtime"), "Uptime");
assertThat(uptime, instanceOf(Long.class));
Object enqueueCount = beans.getAttribute(ObjectName.getInstance("io.digdag.core.workflow", "name", "TaskQueueDispatcher"), "EnqueueCount");
assertThat(enqueueCount, is(0L));
}
}
@Test
public void verifyHikariCP()
throws Exception
{
assumeThat(server.isRemoteDatabase(), is(true));
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object leakDetectionThreshold = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "PoolConfig (HikariPool-1)"), "LeakDetectionThreshold");
assertThat(leakDetectionThreshold, is(60000L));
Object numConnection = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "Pool (HikariPool-1)"), "TotalConnections");
assertTrue((int)numConnection >= 0);
}
}
@Test
public void verifyDigdagMetrics()
throws Exception
{
//To get specific metrics, we need to use it.
CommandStatus status = main("projects",
"-e", server.endpoint());
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object numMaxAcquire = beans.getAttribute(ObjectName.getInstance("io.digdag.agent", "name", "agent_mtag_NumMaxAcquire"), "Count");
assertTrue((long)numMaxAcquire >= 0);
Object getProjectsByName = beans.getAttribute(ObjectName.getInstance("io.digdag.api", "name", "api_GetProjectsByName"), "Count");
assertTrue((long)getProjectsByName >= 0);
Object findTasksByState = beans.getAttribute(ObjectName.getInstance("io.digdag.db", "name", "db_dssm_findRootTasksByStates"), "Count");
assertTrue((long)findTasksByState >= 0);
Object executor_LoopCount = beans.getAttribute(ObjectName.getInstance("io.digdag.executor", "name", "executor_LoopCount"), "Count");
assertTrue((long)executor_LoopCount >= 0);
}
}
@Test
public void verifyUncaughtErrorCount()
throws Exception
{
assumeThat(server.isRemoteDatabase(), is(true));
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object uncaughtErrorCount = beans.getAttribute(ObjectName.getInstance("io.digdag.core", "name", "ErrorReporter"), "UncaughtErrorCount");
assertThat(uncaughtErrorCount, is(0));
// oops, tasks table is broken!?
try (DataSourceProvider dsp = new DataSourceProvider(server.getRemoteTestDatabaseConfig())) {
Statement stmt = dsp.get().getConnection().createStatement();
stmt.execute("drop table tasks cascade");
}
// should increment uncaught exception count
expect(Duration.ofMinutes(5), () -> {
int count = (int) beans.getAttribute(ObjectName.getInstance("io.digdag.core", "name", "ErrorReporter"), "UncaughtErrorCount");
return count > 0;
});
}
}
}
| digdag-tests/src/test/java/acceptance/ServerJmxIT.java | package acceptance;
import com.google.common.base.Throwables;
import org.junit.Rule;
import org.junit.Test;
import io.digdag.core.database.DataSourceProvider;
import utils.TemporaryDigdagServer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.sql.Connection;
import java.sql.Statement;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
import static utils.TestUtils.expect;
public class ServerJmxIT
{
public static final Pattern JMX_PORT_PATTERN = Pattern.compile("\\s*JMX agent started on port (\\d+)\\s*");
@Rule
public TemporaryDigdagServer server = TemporaryDigdagServer.builder()
.inProcess(false)
.configuration(
"server.jmx.port=0",
"database.leakDetectionThreshold=60000",
"database.maximumPoolSize=3")
.build();
private static JMXConnector connectJmx(TemporaryDigdagServer server)
throws IOException
{
Matcher matcher = JMX_PORT_PATTERN.matcher(server.outUtf8());
assertThat(matcher.find(), is(true));
int port = Integer.parseInt(matcher.group(1));
try {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
return JMXConnectorFactory.connect(url, null);
}
catch (MalformedURLException ex) {
throw Throwables.propagate(ex);
}
}
@Test
public void verifyJmx()
throws Exception
{
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object uptime = beans.getAttribute(ObjectName.getInstance("java.lang", "type", "Runtime"), "Uptime");
assertThat(uptime, instanceOf(Long.class));
Object enqueueCount = beans.getAttribute(ObjectName.getInstance("io.digdag.core.workflow", "name", "TaskQueueDispatcher"), "EnqueueCount");
assertThat(enqueueCount, is(0L));
}
}
@Test
public void verifyHikariCP()
throws Exception
{
assumeThat(server.isRemoteDatabase(), is(true));
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object leakDetectionThreshold = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "PoolConfig (HikariPool-1)"), "LeakDetectionThreshold");
assertThat(leakDetectionThreshold, is(60000L));
Object numConnection = beans.getAttribute(ObjectName.getInstance("com.zaxxer.hikari", "type", "Pool (HikariPool-1)"), "TotalConnections");
assertTrue((int)numConnection >= 0);
}
}
@Test
public void verifyUncaughtErrorCount()
throws Exception
{
assumeThat(server.isRemoteDatabase(), is(true));
try (JMXConnector con = connectJmx(server)) {
MBeanServerConnection beans = con.getMBeanServerConnection();
Object uncaughtErrorCount = beans.getAttribute(ObjectName.getInstance("io.digdag.core", "name", "ErrorReporter"), "UncaughtErrorCount");
assertThat(uncaughtErrorCount, is(0));
// oops, tasks table is broken!?
try (DataSourceProvider dsp = new DataSourceProvider(server.getRemoteTestDatabaseConfig())) {
Statement stmt = dsp.get().getConnection().createStatement();
stmt.execute("drop table tasks cascade");
}
// should increment uncaught exception count
expect(Duration.ofMinutes(5), () -> {
int count = (int) beans.getAttribute(ObjectName.getInstance("io.digdag.core", "name", "ErrorReporter"), "UncaughtErrorCount");
return count > 0;
});
}
}
}
| Add tests.
| digdag-tests/src/test/java/acceptance/ServerJmxIT.java | Add tests. |
|
Java | apache-2.0 | 4efc11188b2cefbdf90b3273509bfc3dc90136b1 | 0 | andreaturli/legacy-brooklyn,bmwshop/brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,bmwshop/brooklyn,neykov/incubator-brooklyn,bmwshop/brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,neykov/incubator-brooklyn,andreaturli/legacy-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,aledsage/legacy-brooklyn,neykov/incubator-brooklyn,aledsage/legacy-brooklyn,andreaturli/legacy-brooklyn,bmwshop/brooklyn | /*
* Copyright 2012-2013 by Cloudsoft Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brooklyn.entity.nosql.couchdb;
import org.testng.annotations.Test;
import brooklyn.entity.proxying.EntitySpecs;
import brooklyn.entity.trait.Startable;
import brooklyn.test.EntityTestUtils;
import com.google.common.collect.ImmutableList;
/**
* CouchDB integration tests.
*
* Test the operation of the {@link CouchDBNode} class.
*/
public class CouchDBNodeIntegrationTest extends AbstractCouchDBNodeTest {
/**
* Test that a node starts and sets SERVICE_UP correctly.
*/
@Test(groups = {"Integration", "WIP"})
public void canStartupAndShutdown() {
couchdb = app.createAndManageChild(EntitySpecs.spec(CouchDBNode.class)
.configure("httpPort", "8000+"));
app.start(ImmutableList.of(testLocation));
EntityTestUtils.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);
couchdb.stop();
EntityTestUtils.assertAttributeEquals(couchdb, Startable.SERVICE_UP, false);
}
/**
* Test that a node can be used with jcouchdb client.
*/
@Test(groups = {"Integration", "WIP"})
public void testConnection() throws Exception {
couchdb = app.createAndManageChild(EntitySpecs.spec(CouchDBNode.class)
.configure("httpPort", "8000+"));
app.start(ImmutableList.of(testLocation));
EntityTestUtils.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);
JcouchdbSupport jcouchdb = new JcouchdbSupport(couchdb);
jcouchdb.jcouchdbTest();
}
}
| software/nosql/src/test/java/brooklyn/entity/nosql/couchdb/CouchDBNodeIntegrationTest.java | /*
* Copyright 2012-2013 by Cloudsoft Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brooklyn.entity.nosql.couchdb;
import org.testng.annotations.Test;
import brooklyn.entity.proxying.EntitySpecs;
import brooklyn.entity.trait.Startable;
import brooklyn.test.EntityTestUtils;
import com.google.common.collect.ImmutableList;
/**
* CouchDB integration tests.
*
* Test the operation of the {@link CouchDBNode} class.
*/
public class CouchDBNodeIntegrationTest extends AbstractCouchDBNodeTest {
/**
* Test that a node starts and sets SERVICE_UP correctly.
*/
@Test(groups = "Integration")
public void canStartupAndShutdown() {
couchdb = app.createAndManageChild(EntitySpecs.spec(CouchDBNode.class)
.configure("httpPort", "8000+"));
app.start(ImmutableList.of(testLocation));
EntityTestUtils.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);
couchdb.stop();
EntityTestUtils.assertAttributeEquals(couchdb, Startable.SERVICE_UP, false);
}
/**
* Test that a node can be used with jcouchdb client.
*/
@Test(groups = "Integration")
public void testConnection() throws Exception {
couchdb = app.createAndManageChild(EntitySpecs.spec(CouchDBNode.class)
.configure("httpPort", "8000+"));
app.start(ImmutableList.of(testLocation));
EntityTestUtils.assertAttributeEqualsEventually(couchdb, Startable.SERVICE_UP, true);
JcouchdbSupport jcouchdb = new JcouchdbSupport(couchdb);
jcouchdb.jcouchdbTest();
}
}
| Mark CouchDBNodeIntegrationTest as WIP | software/nosql/src/test/java/brooklyn/entity/nosql/couchdb/CouchDBNodeIntegrationTest.java | Mark CouchDBNodeIntegrationTest as WIP |
|
Java | apache-2.0 | 9f450f6b66b18277c7c266f6b8b0f916e87dcd8b | 0 | omindu/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework,omindu/carbon-identity-framework,omindu/carbon-identity-framework,wso2/carbon-identity-framework,wso2/carbon-identity-framework | /**
* WSO2 Identity Server Rest API - User
* This document specifies a **RESTful API** for WSO2 **Identity Server** . It is written with [swagger 2](http://swagger.io/).
* <p/>
* OpenAPI spec version: 0.9.0
* Contact: [email protected]
* <p/>
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.mgt.endpoint.util.client.api;
import com.sun.jersey.api.client.GenericType;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointConstants;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointUtil;
import org.wso2.carbon.identity.mgt.endpoint.util.client.ApiClient;
import org.wso2.carbon.identity.mgt.endpoint.util.client.ApiException;
import org.wso2.carbon.identity.mgt.endpoint.util.client.Configuration;
import org.wso2.carbon.identity.mgt.endpoint.util.client.Pair;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.CodeValidationRequest;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.Property;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.ResendCodeRequest;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.SelfUserRegistrationRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SelfRegisterApi {
String basePath = IdentityManagementEndpointUtil.buildEndpointUrl(IdentityManagementEndpointConstants
.UserInfoRecovery.USER_API_RELATIVE_PATH);
private ApiClient apiClient;
public SelfRegisterApi() {
this(Configuration.getDefaultApiClient());
}
public SelfRegisterApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* This API is used to user self registration.
*
* @param user It can be sent optional property parameters over email based on email template. (required)
* @return String
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public String mePostCall(SelfUserRegistrationRequest user, Map<String, String> headers) throws ApiException {
Object localVarPostBody = user;
// verify the required parameter 'user' is set
if (user == null) {
throw new ApiException(400, "Missing the required parameter 'user' when calling mePost");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (StringUtils.isNotBlank(user.getUser().getTenantDomain())) {
tenantDomain = user.getUser().getTenantDomain();
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/me".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<>();
if (headers != null) {
localVarHeaderParams.putAll(headers);
}
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* This API is used to resend confirmation code, if it is missing.
*
* @param user It can be sent optional property parameters over email based on email template. (required)
* @return String
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public String resendCodePostCall(ResendCodeRequest user) throws ApiException {
Object localVarPostBody = user;
// verify the required parameter 'user' is set
if (user == null) {
throw new ApiException(400, "Missing the required parameter 'user' when calling resendCodePost(Async)");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (StringUtils.isNotBlank(user.getUser().getTenantDomain())) {
tenantDomain = user.getUser().getTenantDomain();
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/resend-code".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* This API is used to validate code of self reigstered users
*
* @param code Code retried after user self registration and optional property parameters (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void validateCodePostCall(CodeValidationRequest code) throws ApiException {
Object localVarPostBody = code;
// verify the required parameter 'code' is set
if (code == null) {
throw new ApiException(400, "Missing the required parameter 'code' when calling validateCodePost(Async)");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
List<Property> properties = code.getProperties();
for (Property property : properties) {
if (StringUtils.isNotEmpty(property.getKey()) && MultitenantConstants.TENANT_DOMAIN
.equals(property.getKey())) {
tenantDomain = property.getValue();
}
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/validate-code".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* This API is used to validate code of self reigstered users
*
* @param code Code retried after user self registration and optional property parameters (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public User validateCodeUserPostCall(CodeValidationRequest code) throws ApiException {
Object localVarPostBody = code;
// verify the required parameter 'code' is set
if (code == null) {
throw new ApiException(400, "Missing the required parameter 'code' when calling validateCodePost(Async)");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
List<Property> properties = code.getProperties();
for (Property property : properties) {
if (StringUtils.isNotEmpty(property.getKey()) && MultitenantConstants.TENANT_DOMAIN
.equals(property.getKey())) {
tenantDomain = property.getValue();
}
}
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
basePath = IdentityManagementEndpointUtil.buildEndpointUrl("t/" + tenantDomain +
IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
}
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/validate-code".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<User> localVarReturnType = new GenericType<User>() {
};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody,
localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType,
localVarAuthNames, localVarReturnType);
}
}
| components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/api/SelfRegisterApi.java | /**
* WSO2 Identity Server Rest API - User
* This document specifies a **RESTful API** for WSO2 **Identity Server** . It is written with [swagger 2](http://swagger.io/).
* <p/>
* OpenAPI spec version: 0.9.0
* Contact: [email protected]
* <p/>
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.mgt.endpoint.util.client.api;
import com.sun.jersey.api.client.GenericType;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointConstants;
import org.wso2.carbon.identity.mgt.endpoint.util.IdentityManagementEndpointUtil;
import org.wso2.carbon.identity.mgt.endpoint.util.client.ApiClient;
import org.wso2.carbon.identity.mgt.endpoint.util.client.ApiException;
import org.wso2.carbon.identity.mgt.endpoint.util.client.Configuration;
import org.wso2.carbon.identity.mgt.endpoint.util.client.Pair;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.CodeValidationRequest;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.Property;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.ResendCodeRequest;
import org.wso2.carbon.identity.mgt.endpoint.util.client.model.SelfUserRegistrationRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SelfRegisterApi {
String basePath = IdentityManagementEndpointUtil.buildEndpointUrl(IdentityManagementEndpointConstants
.UserInfoRecovery.USER_API_RELATIVE_PATH);
private ApiClient apiClient;
public SelfRegisterApi() {
this(Configuration.getDefaultApiClient());
}
public SelfRegisterApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* This API is used to user self registration.
*
* @param user It can be sent optional property parameters over email based on email template. (required)
* @return String
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public String mePostCall(SelfUserRegistrationRequest user, Map<String, String> headers) throws ApiException {
Object localVarPostBody = user;
// verify the required parameter 'user' is set
if (user == null) {
throw new ApiException(400, "Missing the required parameter 'user' when calling mePost");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (StringUtils.isNotBlank(user.getUser().getTenantDomain())) {
tenantDomain = user.getUser().getTenantDomain();
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/me".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<>();
if (headers != null) {
localVarHeaderParams.putAll(headers);
}
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* This API is used to resend confirmation code, if it is missing.
*
* @param user It can be sent optional property parameters over email based on email template. (required)
* @return String
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public String resendCodePostCall(ResendCodeRequest user) throws ApiException {
Object localVarPostBody = user;
// verify the required parameter 'user' is set
if (user == null) {
throw new ApiException(400, "Missing the required parameter 'user' when calling resendCodePost(Async)");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
if (StringUtils.isNotBlank(user.getUser().getTenantDomain())) {
tenantDomain = user.getUser().getTenantDomain();
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/resend-code".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
/**
* This API is used to validate code of self reigstered users
*
* @param code Code retried after user self registration and optional property parameters (required)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void validateCodePostCall(CodeValidationRequest code) throws ApiException {
Object localVarPostBody = code;
// verify the required parameter 'code' is set
if (code == null) {
throw new ApiException(400, "Missing the required parameter 'code' when calling validateCodePost(Async)");
}
String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
List<Property> properties = code.getProperties();
for (Property property : properties) {
if (StringUtils.isNotEmpty(property.getKey()) && MultitenantConstants.TENANT_DOMAIN
.equals(property.getKey())) {
tenantDomain = property.getValue();
}
}
basePath = IdentityManagementEndpointUtil
.getBasePath(tenantDomain, IdentityManagementEndpointConstants.UserInfoRecovery.USER_API_RELATIVE_PATH);
apiClient.setBasePath(basePath);
// create path and map variables
String localVarPath = "/validate-code".replaceAll("\\{format\\}", "json");
List<Pair> localVarQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
String[] localVarAuthNames = new String[]{};
GenericType<String> localVarReturnType = new GenericType<String>() {
};
apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
}
}
| Fix Self registration autologin flow
| components/identity-mgt/org.wso2.carbon.identity.mgt.endpoint.util/src/main/java/org/wso2/carbon/identity/mgt/endpoint/util/client/api/SelfRegisterApi.java | Fix Self registration autologin flow |
|
Java | apache-2.0 | 5e5ba0749626de9b0462f3942baa08b119eb4c98 | 0 | leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.orchestration.internal.registry.config.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.rule.Authentication;
import org.apache.shardingsphere.orchestration.internal.registry.listener.ShardingOrchestrationEvent;
/**
* Authentication changed event.
*
* @author panjuan
*/
@RequiredArgsConstructor
@Getter
public final class AuthenticationChangedEvent implements ShardingOrchestrationEvent {
private final Authentication authentication;
}
| sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/registry/config/event/AuthenticationChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.orchestration.internal.registry.config.event;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.rule.Authentication;
import org.apache.shardingsphere.orchestration.internal.registry.listener.ShardingOrchestrationEvent;
/**
* User changed event.
*
* @author panjuan
*/
@RequiredArgsConstructor
@Getter
public final class AuthenticationChangedEvent implements ShardingOrchestrationEvent {
private final Authentication authentication;
}
| use Authentication
| sharding-orchestration/sharding-orchestration-core/src/main/java/org/apache/shardingsphere/orchestration/internal/registry/config/event/AuthenticationChangedEvent.java | use Authentication |
|
Java | apache-2.0 | c7a991ab4a8f0c2079d70e0739847dc467c4b6d4 | 0 | threerings/playn,threerings/playn,threerings/playn,threerings/playn | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.java;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import playn.core.AudioImpl;
import javax.sound.sampled.Clip;
public class JavaAudio extends AudioImpl {
public JavaAudio(JavaPlatform platform) {
super(platform);
}
/**
* Creates a sound instance from the audio data available via {@code in}.
*
* @param rsrc a resource via which the audio data can be read.
* @param music if true, a custom {@link Clip} implementation will be used which can handle long
* audio clips; if false, the default Java clip implementation is used which cannot handle long
* audio clips.
*/
public JavaSound createSound(final JavaAssets.Resource rsrc, final boolean music) {
final JavaSound sound = new JavaSound();
((JavaPlatform) platform).invokeAsync(new Runnable() {
public void run () {
try {
AudioInputStream ais = rsrc.openAudioStream();
Clip clip = AudioSystem.getClip();
if (music) {
clip = new BigClip(clip);
}
AudioFormat baseFormat = ais.getFormat();
if (baseFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16, // we have to force sample size to 16
baseFormat.getChannels(),
baseFormat.getChannels()*2,
baseFormat.getSampleRate(),
false // big endian
);
ais = AudioSystem.getAudioInputStream(decodedFormat, ais);
}
clip.open(ais);
dispatchLoaded(sound, clip);
} catch (Exception e) {
dispatchLoadError(sound, e);
}
}
});
return sound;
}
}
| java/src/playn/java/JavaAudio.java | /**
* Copyright 2010 The PlayN Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package playn.java;
import java.io.InputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import playn.core.AudioImpl;
import javax.sound.sampled.Clip;
public class JavaAudio extends AudioImpl {
public JavaAudio(JavaPlatform platform) {
super(platform);
}
/**
* Creates a sound instance from the audio data available via {@code in}.
*
* @param in an input stream via which the audio data can be read.
* @param music if true, a custom {@link Clip} implementation will be used which can handle long
* audio clips; if false, the default Java clip implementation is used which cannot handle long
* audio clips.
*/
public JavaSound createSound(final JavaAssets.Resource rsrc, final boolean music) {
final JavaSound sound = new JavaSound();
((JavaPlatform) platform).invokeAsync(new Runnable() {
public void run () {
try {
AudioInputStream ais = rsrc.openAudioStream();
Clip clip = AudioSystem.getClip();
if (music) {
clip = new BigClip(clip);
}
AudioFormat baseFormat = ais.getFormat();
if (baseFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
AudioFormat decodedFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16, // we have to force sample size to 16
baseFormat.getChannels(),
baseFormat.getChannels()*2,
baseFormat.getSampleRate(),
false // big endian
);
ais = AudioSystem.getAudioInputStream(decodedFormat, ais);
}
clip.open(ais);
dispatchLoaded(sound, clip);
} catch (Exception e) {
dispatchLoadError(sound, e);
}
}
});
return sound;
}
}
| Fix one actual javadoc error.
| java/src/playn/java/JavaAudio.java | Fix one actual javadoc error. |
|
Java | apache-2.0 | 704b1112147d7017cfd2c724a338e33751e5d290 | 0 | eigengo/monitor,eigengo/monitor | /*
* Copyright (c) 2013 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eigengo.monitor.output.dtrace;
import com.sun.tracing.ProbeName;
import com.sun.tracing.ProviderName;
import com.sun.tracing.dtrace.FunctionName;
@ProviderName("akka")
public interface DtraceCounterProvider extends com.sun.tracing.Provider {
@FunctionName("Records execution time of ``def receive``")
@ProbeName("execution-time")
void executionTime(String name, int length, int duration);
@FunctionName("counter")
void counter(String name, int length, int delta);
@FunctionName("gauge")
void gauge(String name, int length, int value);
} | output-dtrace/src/main/java/org/eigengo/monitor/output/dtrace/DtraceCounterProvider.java | /*
* Copyright (c) 2013 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eigengo.monitor.output.dtrace;
import com.sun.tracing.ProviderName;
import com.sun.tracing.dtrace.FunctionName;
import com.sun.tracing.dtrace.ModuleName;
@ProviderName("akka")
public interface DtraceCounterProvider extends com.sun.tracing.Provider {
@FunctionName("execution-time") void executionTime(String name, int length, int duration);
@FunctionName("counter") void counter(String name, int length, int delta);
@FunctionName("gauge") void gauge(String name, int length, int value);
} | counters
| output-dtrace/src/main/java/org/eigengo/monitor/output/dtrace/DtraceCounterProvider.java | counters |
|
Java | apache-2.0 | 3979f8b9349a2e2e43a6ae5e958cd95d193e472c | 0 | santhosh-tekuri/jlibs,santhosh-tekuri/jlibs | /**
* JLibs: Common Utilities for Java
* Copyright (C) 2009 Santhosh Kumar T <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
package jlibs.wadl;
import jlibs.core.lang.StringUtil;
import jlibs.wadl.model.Method;
import jlibs.wadl.model.Param;
import jlibs.wadl.model.Representation;
import jlibs.wadl.model.Response;
import jlibs.wadl.runtime.Path;
import jlibs.xml.dom.DOMUtil;
import jline.Completor;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.net.HttpURLConnection;
import java.util.*;
/**
* @author Santhosh Kumar T
*/
public class WADLCompletor implements Completor{
private WADLTerminal terminal;
public WADLCompletor(WADLTerminal terminal){
this.terminal = terminal;
}
@Override
@SuppressWarnings("unchecked")
public int complete(String buffer, int cursor, List candidates){
int from = 0;
int to = findArgument(buffer, from, ' ');
String arg = buffer.substring(from, Math.min(to, cursor));
if(arg.isEmpty() || cursor<=to){
List<String> available = new ArrayList<String>();
available.add("cd");
if(!arg.isEmpty() && "import".startsWith(arg))
available.add("import");
if(!arg.isEmpty() && "server".startsWith(arg))
available.add("server");
if(!arg.isEmpty() && "set".startsWith(arg))
available.add("set");
else{
Path path = terminal.getCurrentPath();
while(path!=null){
if(path.variable()!=null && path.value==null){
available.add("set");
break;
}
path = path.parent;
}
}
if(!arg.isEmpty() && "target".startsWith(arg))
available.add("target");
Path path = terminal.getCurrentPath();
if(path.resource!=null){
for(Object obj: path.resource.getMethodOrResource()){
if(obj instanceof Method){
String method = ((Method)obj).getName().toUpperCase();
if(method.startsWith(arg.toUpperCase()))
available.add(method);
}
}
}
fillCandidates(candidates, arg, available);
if(candidates.isEmpty())
available.addAll(Arrays.asList("GET", "PUT", "POST", "DELETE"));
fillCandidates(candidates, arg, available);
return from;
}else{
if(arg.equals("cd"))
return completePath(buffer, cursor, candidates, terminal.getCurrentPath(), to);
else if(arg.equals("set"))
return completeVariable(buffer, cursor, candidates, terminal.getCurrentPath(), to);
else if(arg.equals("server")){
String token = buffer.substring(to+1, cursor);
if(token.contains(" "))
return -1;
Path currentRoot = terminal.getCurrentPath();
if(currentRoot!=null)
currentRoot = currentRoot.getRoot();
for(Path root: terminal.getRoots()){
if(root!=currentRoot && root.name.startsWith(token))
candidates.add(root.name+" ");
}
return candidates.isEmpty() ? -1 : to+1;
}else{
Path path = terminal.getCurrentPath();
if(path.resource!=null){
Method method = null;
for(Object obj: path.resource.getMethodOrResource()){
if(obj instanceof Method){
String m = ((Method)obj).getName();
if(arg.equalsIgnoreCase(m)){
method = (Method)obj;
break;
}
}
}
if(method==null)
return -1;
return completePath(buffer, cursor, candidates, terminal.getCurrentPath(), to);
}
return -1;
}
}
}
private int findArgument(String buffer, int from, char separator){
for(; from<buffer.length(); from++){
if(buffer.charAt(from)==separator)
return from;
}
return from;
}
private void fillCandidates(List<String> candidates, String token, List<String> args){
for(String arg: args){
if(arg.toLowerCase().startsWith(token.toLowerCase()))
candidates.add(arg+' ');
}
}
private List<String> fetchResourceNames(Path current){
if(current.resource==null)
return Collections.emptyList();
for(Object item: current.resource.getMethodOrResource()){
if(item instanceof Method){
Method method = (Method)item;
if(method.getName().equalsIgnoreCase("GET")){
for(Response response: method.getResponse()){
for(Representation rep: response.getRepresentation()){
if(Command.isXML(rep.getMediaType())){
for(Param param: rep.getParam()){
if(param.getPath()!=null)
return fetchResourceNames(current, method, param.getPath());
}
}
}
}
}
}
}
return Collections.emptyList();
}
private List<String> fetchResourceNames(Path current, Method method, String xpath){
try{
HttpURLConnection con = current.execute(method, new HashMap<String, List<String>>(), null);
if(con.getResponseCode()==200){
Document doc = DOMUtil.newDocumentBuilder(true, false).parse(con.getInputStream());
XPathExpression expr = XPathFactory.newInstance().newXPath().compile(xpath);
NodeList nodeSet = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
List<String> resourceNames = new ArrayList<String>();
for(int i=0; i<nodeSet.getLength(); i++)
resourceNames.add(nodeSet.item(i).getTextContent());
return resourceNames;
}
}catch(Exception ex){
ex.printStackTrace();
}
return Collections.emptyList();
}
private void fillPathCandidates(List<String> candidates, String token, Path current){
for(Path child: current.children){
if(child.variable()!=null){
candidates.clear();
for(String resourceName: fetchResourceNames(current)){
if(resourceName.startsWith(token)){
if(child.children.isEmpty())
candidates.add(resourceName);
else
candidates.add(resourceName+"/");
}
}
return;
}
if(child.name.startsWith(token)){
if(child.children.isEmpty())
candidates.add(child.name+' ');
else{
String candidate = child.name;
while(child.resource==null && child.children.size()==1){
child = child.children.get(0);
candidate += "/"+child.name;
}
candidate += child.children.isEmpty() ? ' ' : '/';
candidates.add(candidate);
}
}
}
}
private int completePath(String buffer, int cursor, List<String>candidates, Path path, int to){
if(path.children.isEmpty())
return -1;
int from = to+1;
to = findArgument(buffer, from, '/');
if(to<buffer.length()){
assert buffer.charAt(to)=='/';
String token = buffer.substring(from, to);
Path child = path.get(token);
if(child==null)
return -1;
return completePath(buffer, cursor, candidates, child, to);
}
String arg = buffer.substring(from, Math.min(to, cursor));
fillPathCandidates(candidates, arg, path);
return from;
}
private int completeVariable(String buffer, int cursor, List<String> candidates, Path path, int to){
Deque<Path> stack = new ArrayDeque<Path>();
while(path!=null){
stack.push(path);
path = path.parent;
}
Set<String> assigned = new LinkedHashSet<String>();
Set<String> unAssigned = new LinkedHashSet<String>();
while(!stack.isEmpty()){
path = stack.pop();
String var = path.variable();
if(var!=null){
if(path.value!=null)
assigned.add(var);
else
unAssigned.add(var);
}
}
String tokens[] = StringUtil.getTokens(buffer.substring(to+1, cursor), " ", true);
for(String token: tokens){
int equals = token.indexOf('=');
if(equals!=-1){
String var = token.substring(0, equals);
unAssigned.remove(var);
assigned.remove(var);
}
}
String token = tokens.length==0 ? "" : tokens[tokens.length-1];
int equals = token.indexOf('=');
if(equals!=-1){
if(buffer.charAt(cursor-1)==' ')
token = "";
else
return -1;
}
for(String var: unAssigned){
if(var.startsWith(token))
candidates.add(var+'=');
}
if(candidates.isEmpty()){
for(String var: assigned){
if(var.startsWith(token))
candidates.add(var+'=');
}
}
return candidates.isEmpty() ? -1 : cursor-token.length();
}
}
| wadl/src/main/java/jlibs/wadl/WADLCompletor.java | /**
* JLibs: Common Utilities for Java
* Copyright (C) 2009 Santhosh Kumar T <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*/
package jlibs.wadl;
import jlibs.core.lang.StringUtil;
import jlibs.wadl.model.Method;
import jlibs.wadl.runtime.Path;
import jline.Completor;
import java.util.*;
/**
* @author Santhosh Kumar T
*/
public class WADLCompletor implements Completor{
private WADLTerminal terminal;
public WADLCompletor(WADLTerminal terminal){
this.terminal = terminal;
}
@Override
@SuppressWarnings("unchecked")
public int complete(String buffer, int cursor, List candidates){
int from = 0;
int to = findArgument(buffer, from, ' ');
String arg = buffer.substring(from, Math.min(to, cursor));
if(arg.isEmpty() || cursor<=to){
List<String> available = new ArrayList<String>();
available.add("cd");
if(!arg.isEmpty() && "import".startsWith(arg))
available.add("import");
if(!arg.isEmpty() && "server".startsWith(arg))
available.add("server");
if(!arg.isEmpty() && "set".startsWith(arg))
available.add("set");
else{
Path path = terminal.getCurrentPath();
while(path!=null){
if(path.variable()!=null && path.value==null){
available.add("set");
break;
}
path = path.parent;
}
}
if(!arg.isEmpty() && "target".startsWith(arg))
available.add("target");
Path path = terminal.getCurrentPath();
if(path.resource!=null){
for(Object obj: path.resource.getMethodOrResource()){
if(obj instanceof Method){
String method = ((Method)obj).getName().toUpperCase();
if(method.startsWith(arg.toUpperCase()))
available.add(method);
}
}
}
fillCandidates(candidates, arg, available);
if(candidates.isEmpty())
available.addAll(Arrays.asList("GET", "PUT", "POST", "DELETE"));
fillCandidates(candidates, arg, available);
return from;
}else{
if(arg.equals("cd"))
return completePath(buffer, cursor, candidates, terminal.getCurrentPath(), to);
else if(arg.equals("set"))
return completeVariable(buffer, cursor, candidates, terminal.getCurrentPath(), to);
else if(arg.equals("server")){
String token = buffer.substring(to+1, cursor);
if(token.contains(" "))
return -1;
Path currentRoot = terminal.getCurrentPath();
if(currentRoot!=null)
currentRoot = currentRoot.getRoot();
for(Path root: terminal.getRoots()){
if(root!=currentRoot && root.name.startsWith(token))
candidates.add(root.name+" ");
}
return candidates.isEmpty() ? -1 : to+1;
}else{
Path path = terminal.getCurrentPath();
if(path.resource!=null){
Method method = null;
for(Object obj: path.resource.getMethodOrResource()){
if(obj instanceof Method){
String m = ((Method)obj).getName();
if(arg.equalsIgnoreCase(m)){
method = (Method)obj;
break;
}
}
}
if(method==null)
return -1;
return completePath(buffer, cursor, candidates, terminal.getCurrentPath(), to);
}
return -1;
}
}
}
private int findArgument(String buffer, int from, char separator){
for(; from<buffer.length(); from++){
if(buffer.charAt(from)==separator)
return from;
}
return from;
}
private void fillCandidates(List<String> candidates, String token, List<String> args){
for(String arg: args){
if(arg.toLowerCase().startsWith(token.toLowerCase()))
candidates.add(arg+' ');
}
}
private void fillPathCandidates(List<String> candidates, String token, Path current){
for(Path child: current.children){
if(child.variable()!=null){
candidates.clear();
return;
}
if(child.name.startsWith(token)){
if(child.children.isEmpty())
candidates.add(child.name+' ');
else{
String candidate = child.name;
while(child.resource==null && child.children.size()==1){
child = child.children.get(0);
candidate += "/"+child.name;
}
candidate += child.children.isEmpty() ? ' ' : '/';
candidates.add(candidate);
}
}
}
}
private int completePath(String buffer, int cursor, List<String>candidates, Path path, int to){
if(path.children.isEmpty())
return -1;
int from = to+1;
to = findArgument(buffer, from, '/');
if(to<buffer.length()){
assert buffer.charAt(to)=='/';
String token = buffer.substring(from, to);
Path child = null;
if(token.equals(".."))
child = path.parent;
else{
for(Path c: path.children){
if(c.variable()!=null || c.name.equals(token)){
child = c;
break;
}
}
}
if(child==null)
return -1;
return completePath(buffer, cursor, candidates, child, to);
}
String arg = buffer.substring(from, Math.min(to, cursor));
fillPathCandidates(candidates, arg, path);
return from;
}
private int completeVariable(String buffer, int cursor, List<String> candidates, Path path, int to){
Deque<Path> stack = new ArrayDeque<Path>();
while(path!=null){
stack.push(path);
path = path.parent;
}
Set<String> assigned = new LinkedHashSet<String>();
Set<String> unAssigned = new LinkedHashSet<String>();
while(!stack.isEmpty()){
path = stack.pop();
String var = path.variable();
if(var!=null){
if(path.value!=null)
assigned.add(var);
else
unAssigned.add(var);
}
}
String tokens[] = StringUtil.getTokens(buffer.substring(to+1, cursor), " ", true);
for(String token: tokens){
int equals = token.indexOf('=');
if(equals!=-1){
String var = token.substring(0, equals);
unAssigned.remove(var);
assigned.remove(var);
}
}
String token = tokens.length==0 ? "" : tokens[tokens.length-1];
int equals = token.indexOf('=');
if(equals!=-1){
if(buffer.charAt(cursor-1)==' ')
token = "";
else
return -1;
}
for(String var: unAssigned){
if(var.startsWith(token))
candidates.add(var+'=');
}
if(candidates.isEmpty()){
for(String var: assigned){
if(var.startsWith(token))
candidates.add(var+'=');
}
}
return candidates.isEmpty() ? -1 : cursor-token.length();
}
}
| FEATURE: support for querying and filling resource names | wadl/src/main/java/jlibs/wadl/WADLCompletor.java | FEATURE: support for querying and filling resource names |
|
Java | apache-2.0 | 3f3aba3b6863b5625236dc8010e97ae84ca45a4b | 0 | Bernardo-MG/Tabletop-Punkapocalyptic-Ruleset-API,Bernardo-MG/Tabletop-Punkapocalyptic-Ruleset-API | package com.wandrell.tabletop.business.service.punkapocalyptic;
import java.util.Collection;
import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.MeleeWeapon;
import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Weapon;
import com.wandrell.tabletop.business.model.punkapocalyptic.unit.Gang;
import com.wandrell.tabletop.business.model.punkapocalyptic.unit.Unit;
import com.wandrell.tabletop.business.model.valuebox.ValueBox;
public interface RulesetService {
public Collection<Weapon> filterWeaponOptions(
final Collection<Weapon> weaponsHas,
final Collection<Weapon> weapons);
public Integer getBulletCost();
public Integer getGangValoration(final Gang gang);
public Integer getMaxAllowedUnits(final Gang gang);
public Integer getPackMaxSize();
public MeleeWeapon getTwoHandedMeleeEquivalent();
public Integer getUnitValoration(final Unit unit);
public void
setUpMaxUnitsValueHandler(final ValueBox value, final Gang gang);
}
| src/main/java/com/wandrell/tabletop/business/service/punkapocalyptic/RulesetService.java | package com.wandrell.tabletop.business.service.punkapocalyptic;
import java.util.Collection;
import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.MeleeWeapon;
import com.wandrell.tabletop.business.model.punkapocalyptic.inventory.Weapon;
import com.wandrell.tabletop.business.model.punkapocalyptic.unit.Gang;
import com.wandrell.tabletop.business.model.punkapocalyptic.unit.Unit;
import com.wandrell.tabletop.business.model.valuebox.derived.DerivedValueBox;
public interface RulesetService {
public Collection<Weapon> filterWeaponOptions(
final Collection<Weapon> weaponsHas,
final Collection<Weapon> weapons);
public Integer getBulletCost();
public Integer getGangValoration(final Gang gang);
public Integer getMaxAllowedUnits(final Gang gang);
public Integer getPackMaxSize();
public MeleeWeapon getTwoHandedMeleeEquivalent();
public Integer getUnitValoration(final Unit unit);
public void setUpMaxUnitsValueHandler(final DerivedValueBox value,
final Gang gang);
}
| Corrected the ruleset service requiring a DerivedValueBox instead of a
ValueBox. | src/main/java/com/wandrell/tabletop/business/service/punkapocalyptic/RulesetService.java | Corrected the ruleset service requiring a DerivedValueBox instead of a ValueBox. |
|
Java | bsd-2-clause | 957fb5f562325ee9406ce872f10f7442e63f6e42 | 0 | TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing.viewer.image;
import imagej.data.Extents;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageCanvas;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.display.event.AxisPositionEvent;
import imagej.data.display.event.DelayedPositionEvent;
import imagej.data.display.event.LUTsChangedEvent;
import imagej.ui.common.awt.AWTInputEventDispatcher;
import imagej.ui.swing.StaticSwingUtils;
import imagej.ui.swing.SwingColorBar;
import imagej.ui.viewer.DisplayWindow;
import imagej.ui.viewer.image.ImageDisplayPanel;
import java.awt.Adjustable;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import net.miginfocom.swing.MigLayout;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.event.EventSubscriber;
/**
* Swing implementation of image display panel. Contains a label, a graphics
* pane containing an {@link ImageCanvas}, and panel containing dimensional
* controllers. This panel is added to a top-level {@link DisplayWindow} display
* container.
*
* @author Curtis Rueden
* @author Grant Harris
* @author Barry DeZonia
*/
public class SwingDisplayPanel extends JPanel implements ImageDisplayPanel {
private final SwingImageDisplayViewer displayViewer;
private final ImageDisplay display;
private final JLabel imageLabel;
private final JPanel imagePane;
private final SwingColorBar colorBar;
private final JPanel sliderPanel;
private final DisplayWindow window;
private boolean initialScaleCalculated = false;
private final Map<AxisType, JScrollBar> axisSliders =
new ConcurrentHashMap<AxisType, JScrollBar>();
private final Map<AxisType, JLabel> axisLabels =
new HashMap<AxisType, JLabel>();
@SuppressWarnings("unused")
private final List<EventSubscriber<?>> subscribers;
// -- constructors --
public SwingDisplayPanel(final SwingImageDisplayViewer displayViewer,
final DisplayWindow window)
{
this.displayViewer = displayViewer;
this.display = displayViewer.getDisplay();
this.window = window;
imageLabel = new JLabel(" ");
final int prefHeight = imageLabel.getPreferredSize().height;
imageLabel.setPreferredSize(new Dimension(0, prefHeight));
imagePane = new JPanel();
imagePane.setLayout(new MigLayout("ins 0,wrap 1", "fill,grow",
"[fill,grow|]"));
imagePane.add(displayViewer.getCanvas());
final int colorBarHeight = 8;
colorBar = new SwingColorBar(colorBarHeight);
colorBar.setPreferredSize(new Dimension(0, colorBarHeight));
colorBar.setBorder(new LineBorder(Color.black));
imagePane.add(colorBar);
sliderPanel = new JPanel();
sliderPanel.setLayout(new MigLayout("fillx,wrap 2", "[right|fill,grow]"));
setLayout(new BorderLayout());
setBorder(new EmptyBorder(3, 3, 3, 3));
add(imageLabel, BorderLayout.NORTH);
add(imagePane, BorderLayout.CENTER);
add(sliderPanel, BorderLayout.SOUTH);
window.setContent(this);
final EventService eventService =
display.getContext().getService(EventService.class);
subscribers = eventService.subscribe(this);
}
// -- SwingDisplayPanel methods --
public void addEventDispatcher(final AWTInputEventDispatcher dispatcher) {
dispatcher.register(this, true, false);
}
// -- ImageDisplayPanel methods --
@Override
public ImageDisplay getDisplay() {
return display;
}
// -- DisplayPanel methods --
@Override
public DisplayWindow getWindow() {
return window;
}
@Override
public void redoLayout() {
final int oldSliderHeight = sliderPanel.getPreferredSize().height;
// rebuild display panel UI
createSliders();
updateColorBar(0);
sliderPanel.setVisible(sliderPanel.getComponentCount() > 0);
doInitialSizing();
displayViewer.getCanvas().rebuild();
revalidate();
final int newSliderHeight = sliderPanel.getPreferredSize().height;
// HACK: Grow DisplayWindow height to match slider panel height increase.
final int heightIncrease = newSliderHeight - oldSliderHeight;
if (heightIncrease > 0) {
final Component c = (Component) getWindow();
final Dimension size = c.getSize();
size.height += heightIncrease;
c.setSize(size);
}
repaint();
}
@Override
public void setLabel(final String s) {
imageLabel.setText(s);
}
@Override
public void redraw() {
final ImageDisplayService imageDisplayService =
display.getContext().getService(ImageDisplayService.class);
final DatasetView view = imageDisplayService.getActiveDatasetView(display);
if (view == null) return; // no active dataset
view.getProjector().map();
displayViewer.getCanvas().update();
}
// -- Event handlers --
@EventHandler
protected void onEvent(final AxisPositionEvent event) {
if (event.getDisplay() != getDisplay()) return;
final AxisType axis = event.getAxis();
updateAxis(axis);
final EventService eventService =
display.getContext().getService(EventService.class);
eventService.publish(new DelayedPositionEvent(display, axis));
}
@EventHandler
protected void onEvent(LUTsChangedEvent event) {
if (!getDisplay().contains(event.getView())) return;
final int value = (int) display.getLongPosition(Axes.CHANNEL);
updateColorBar(value);
}
// -- Helper methods --
private void createSliders() {
final AxisType[] axes = display.getAxes();
final Extents extents = display.getExtents();
// remove obsolete sliders
for (final AxisType axis : axisSliders.keySet()) {
if (display.getAxisIndex(axis) >= 0) continue; // axis still active
sliderPanel.remove(axisSliders.get(axis));
sliderPanel.remove(axisLabels.get(axis));
axisSliders.remove(axis);
axisLabels.remove(axis);
}
// configure sliders to match axes and extents
for (int i = 0; i < axes.length; i++) {
final AxisType axis = axes[i];
if (Axes.isXY(axis)) continue; // skip spatial axes
final int min = (int) extents.min(i);
final int max = (int) extents.max(i) + 1;
final int value = (int) display.getLongPosition(axis);
final JScrollBar axisSlider = axisSliders.get(axis);
if (axisSlider == null) {
// create new slider
final JLabel label = new JLabel(axis.getLabel());
label.setHorizontalAlignment(SwingConstants.RIGHT);
axisLabels.put(axis, label);
final JScrollBar slider =
new JScrollBar(Adjustable.HORIZONTAL, value, 1, min, max);
slider.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
display.setPosition(slider.getValue(), axis);
}
});
axisSliders.put(axis, slider);
// add slider to panel
// TODO - ensure sliders are always ordered the same (alphabetical?)
sliderPanel.add(label);
sliderPanel.add(slider);
}
else {
// update slider extents and value
if (axisSlider.getMinimum() != min || axisSlider.getMaximum() != max) {
axisSlider.setValues(value, 1, min, max);
}
else if (axisSlider.getValue() != value) axisSlider.setValue(value);
}
}
}
private void updateColorBar(final int c) {
final ImageDisplayService imageDisplayService =
display.getContext().getService(ImageDisplayService.class);
final DatasetView view = imageDisplayService.getActiveDatasetView(display);
if (view == null) return; // no active dataset
List<ColorTable> colorTables = view.getColorTables();
if (c >= colorTables.size()) return;
final ColorTable lut = colorTables.get(c);
colorBar.setColorTable(lut);
colorBar.repaint();
}
private void doInitialSizing() {
final double scale = findFullyVisibleScale();
final double zoomLevel = display.getCanvas().getBestZoomLevel(scale);
final ImageCanvas canvas = displayViewer.getDisplay().getCanvas();
canvas.setZoomAndCenter(zoomLevel);
if (!initialScaleCalculated) {
canvas.setInitialScale(canvas.getZoomFactor());
initialScaleCalculated = true;
}
}
// NB - BDZ would like to streamline this to avoid extra display updates.
// However testing scroll bar position versus current display's position
// fails as the display position always matches already. So we can't avoid
// calling display.update() by testing such. We need to make the display
// update mechanism smarter if possible. Perhaps by giving it hints about
// the changes being made.
private void updateAxis(final AxisType axis) {
final int value = (int) display.getLongPosition(axis);
if (axis == Axes.CHANNEL) updateColorBar(value);
final JScrollBar scrollBar = axisSliders.get(axis);
if (scrollBar != null) scrollBar.setValue(value);
getDisplay().update();
}
private double findFullyVisibleScale() {
final JHotDrawImageCanvas canvas = displayViewer.getCanvas();
final Dimension canvasSize = canvas.getPreferredSize();
final Rectangle deskBounds = StaticSwingUtils.getWorkSpaceBounds();
// calc height variables
final int labelHeight = imageLabel.getPreferredSize().height;
final int sliderHeight = sliderPanel.getPreferredSize().height;
// NB - extraSpace used to be 64. But this caused some images to come in at
// an inappropriate scale. I think extraSpace was just a hopeful fudge
// factor. I am eliminating it for now but leaving machinery in place in
// case we want to restore such code. This fixes bug #1472.
final int extraSpace = 0;
// determine largest viewable panel sizes
final int maxViewHeight =
deskBounds.height - labelHeight - sliderHeight - extraSpace;
final int maxViewWidth = deskBounds.width - extraSpace;
// is canvas bigger than largest viewable panel?
if ((canvasSize.width > maxViewWidth) ||
(canvasSize.height > maxViewHeight))
{
// yes it is
// so calc best scale that brings whole image into max viewable panel size
final double canvasAspect = 1.0 * canvasSize.width / canvasSize.height;
final double viewAspect = 1.0 * maxViewWidth / maxViewHeight;
if (canvasAspect < viewAspect) {
// image height the issue
return 1.0 * maxViewHeight / canvasSize.height;
}
// else image width the issue
return 1.0 * maxViewWidth / canvasSize.width;
}
// else canvas fits on screen as is
return 1;
}
}
| plugins/uis/swing/src/main/java/imagej/ui/swing/viewer/image/SwingDisplayPanel.java | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2009 - 2013 Board of Regents of the University of
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
* Institute of Molecular Cell Biology and Genetics.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package imagej.ui.swing.viewer.image;
import imagej.data.Extents;
import imagej.data.display.DatasetView;
import imagej.data.display.ImageCanvas;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.display.event.AxisPositionEvent;
import imagej.data.display.event.DelayedPositionEvent;
import imagej.data.display.event.LUTsChangedEvent;
import imagej.ui.common.awt.AWTInputEventDispatcher;
import imagej.ui.swing.StaticSwingUtils;
import imagej.ui.swing.SwingColorBar;
import imagej.ui.viewer.DisplayWindow;
import imagej.ui.viewer.image.ImageDisplayPanel;
import java.awt.Adjustable;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import net.imglib2.display.ColorTable;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import net.miginfocom.swing.MigLayout;
import org.scijava.event.EventHandler;
import org.scijava.event.EventService;
import org.scijava.event.EventSubscriber;
/**
* Swing implementation of image display panel. Contains a label, a graphics
* pane containing an {@link ImageCanvas}, and panel containing dimensional
* controllers. This panel is added to a top-level {@link DisplayWindow} display
* container.
*
* @author Curtis Rueden
* @author Grant Harris
* @author Barry DeZonia
*/
public class SwingDisplayPanel extends JPanel implements ImageDisplayPanel {
private final SwingImageDisplayViewer displayViewer;
private final ImageDisplay display;
private final JLabel imageLabel;
private final JPanel imagePane;
private final SwingColorBar colorBar;
private final JPanel sliderPanel;
private final DisplayWindow window;
private boolean initialScaleCalculated = false;
private final Map<AxisType, JScrollBar> axisSliders =
new ConcurrentHashMap<AxisType, JScrollBar>();
private final Map<AxisType, JLabel> axisLabels =
new HashMap<AxisType, JLabel>();
@SuppressWarnings("unused")
private final List<EventSubscriber<?>> subscribers;
// -- constructors --
public SwingDisplayPanel(final SwingImageDisplayViewer displayViewer,
final DisplayWindow window)
{
this.displayViewer = displayViewer;
this.display = displayViewer.getDisplay();
this.window = window;
imageLabel = new JLabel(" ");
final int prefHeight = imageLabel.getPreferredSize().height;
imageLabel.setPreferredSize(new Dimension(0, prefHeight));
imagePane = new JPanel();
imagePane.setLayout(new MigLayout("ins 0,wrap 1", "fill,grow",
"[fill,grow|]"));
imagePane.add(displayViewer.getCanvas());
final int colorBarHeight = 8;
colorBar = new SwingColorBar(colorBarHeight);
colorBar.setPreferredSize(new Dimension(0, colorBarHeight));
colorBar.setBorder(new LineBorder(Color.black));
imagePane.add(colorBar);
sliderPanel = new JPanel();
sliderPanel.setLayout(new MigLayout("fillx,wrap 2", "[right|fill,grow]"));
setLayout(new BorderLayout());
setBorder(new EmptyBorder(3, 3, 3, 3));
add(imageLabel, BorderLayout.NORTH);
add(imagePane, BorderLayout.CENTER);
add(sliderPanel, BorderLayout.SOUTH);
window.setContent(this);
final EventService eventService =
display.getContext().getService(EventService.class);
subscribers = eventService.subscribe(this);
}
// -- SwingDisplayPanel methods --
public void addEventDispatcher(final AWTInputEventDispatcher dispatcher) {
dispatcher.register(this, true, false);
}
// -- ImageDisplayPanel methods --
@Override
public ImageDisplay getDisplay() {
return display;
}
// -- DisplayPanel methods --
@Override
public DisplayWindow getWindow() {
return window;
}
@Override
public void redoLayout() {
final int oldSliderHeight = sliderPanel.getPreferredSize().height;
// rebuild display panel UI
createSliders();
updateColorBar(0);
sliderPanel.setVisible(sliderPanel.getComponentCount() > 0);
doInitialSizing();
displayViewer.getCanvas().rebuild();
revalidate();
final int newSliderHeight = sliderPanel.getPreferredSize().height;
// HACK: Grow DisplayWindow height to match slider panel height increase.
final int heightIncrease = newSliderHeight - oldSliderHeight;
if (heightIncrease > 0) {
final Component c = (Component) getWindow();
final Dimension size = c.getSize();
size.height += heightIncrease;
c.setSize(size);
}
repaint();
}
@Override
public void setLabel(final String s) {
imageLabel.setText(s);
}
@Override
public void redraw() {
final ImageDisplayService imageDisplayService =
display.getContext().getService(ImageDisplayService.class);
final DatasetView view = imageDisplayService.getActiveDatasetView(display);
if (view == null) return; // no active dataset
view.getProjector().map();
displayViewer.getCanvas().update();
}
// -- Event handlers --
@EventHandler
protected void onEvent(final AxisPositionEvent event) {
if (event.getDisplay() != getDisplay()) return;
final AxisType axis = event.getAxis();
updateAxis(axis);
final EventService eventService =
display.getContext().getService(EventService.class);
eventService.publish(new DelayedPositionEvent(display, axis));
}
@EventHandler
protected void onEvent(LUTsChangedEvent event) {
if (!getDisplay().contains(event.getView())) return;
final int value = (int) display.getLongPosition(Axes.CHANNEL);
updateColorBar(value);
}
// -- Helper methods --
private void createSliders() {
final AxisType[] axes = display.getAxes();
final Extents extents = display.getExtents();
// remove obsolete sliders
for (final AxisType axis : axisSliders.keySet()) {
if (display.getAxisIndex(axis) >= 0) continue; // axis still active
sliderPanel.remove(axisSliders.get(axis));
sliderPanel.remove(axisLabels.get(axis));
axisSliders.remove(axis);
axisLabels.remove(axis);
}
// configure sliders to match axes and extents
for (int i = 0; i < axes.length; i++) {
final AxisType axis = axes[i];
if (Axes.isXY(axis)) continue; // skip spatial axes
final int min = (int) extents.min(i);
final int max = (int) extents.max(i) + 1;
int value = (int) display.getLongPosition(axis);
if (value < min) {
value = min;
display.setPosition(min, axis);
}
else if (value >= max) {
value = max - 1;
display.setPosition(max - 1, axis);
}
final JScrollBar axisSlider = axisSliders.get(axis);
if (axisSlider == null) {
// create new slider
final JLabel label = new JLabel(axis.getLabel());
label.setHorizontalAlignment(SwingConstants.RIGHT);
axisLabels.put(axis, label);
final JScrollBar slider =
new JScrollBar(Adjustable.HORIZONTAL, value, 1, min, max);
slider.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(final AdjustmentEvent e) {
display.setPosition(slider.getValue(), axis);
}
});
axisSliders.put(axis, slider);
// add slider to panel
// TODO - ensure sliders are always ordered the same (alphabetical?)
sliderPanel.add(label);
sliderPanel.add(slider);
}
else {
// update slider extents and value
if (axisSlider.getMinimum() != min || axisSlider.getMaximum() != max) {
axisSlider.setValues(value, 1, min, max);
}
else if (axisSlider.getValue() != value) axisSlider.setValue(value);
}
}
}
private void updateColorBar(final int c) {
final ImageDisplayService imageDisplayService =
display.getContext().getService(ImageDisplayService.class);
final DatasetView view = imageDisplayService.getActiveDatasetView(display);
if (view == null) return; // no active dataset
List<ColorTable> colorTables = view.getColorTables();
if (c >= colorTables.size()) return;
final ColorTable lut = colorTables.get(c);
colorBar.setColorTable(lut);
colorBar.repaint();
}
private void doInitialSizing() {
final double scale = findFullyVisibleScale();
final double zoomLevel = display.getCanvas().getBestZoomLevel(scale);
final ImageCanvas canvas = displayViewer.getDisplay().getCanvas();
canvas.setZoomAndCenter(zoomLevel);
if (!initialScaleCalculated) {
canvas.setInitialScale(canvas.getZoomFactor());
initialScaleCalculated = true;
}
}
// NB - BDZ would like to streamline this to avoid extra display updates.
// However testing scroll bar position versus current display's position
// fails as the display position always matches already. So we can't avoid
// calling display.update() by testing such. We need to make the display
// update mechanism smarter if possible. Perhaps by giving it hints about
// the changes being made.
private void updateAxis(final AxisType axis) {
final int value = (int) display.getLongPosition(axis);
if (axis == Axes.CHANNEL) updateColorBar(value);
final JScrollBar scrollBar = axisSliders.get(axis);
if (scrollBar != null) scrollBar.setValue(value);
getDisplay().update();
}
private double findFullyVisibleScale() {
final JHotDrawImageCanvas canvas = displayViewer.getCanvas();
final Dimension canvasSize = canvas.getPreferredSize();
final Rectangle deskBounds = StaticSwingUtils.getWorkSpaceBounds();
// calc height variables
final int labelHeight = imageLabel.getPreferredSize().height;
final int sliderHeight = sliderPanel.getPreferredSize().height;
// NB - extraSpace used to be 64. But this caused some images to come in at
// an inappropriate scale. I think extraSpace was just a hopeful fudge
// factor. I am eliminating it for now but leaving machinery in place in
// case we want to restore such code. This fixes bug #1472.
final int extraSpace = 0;
// determine largest viewable panel sizes
final int maxViewHeight =
deskBounds.height - labelHeight - sliderHeight - extraSpace;
final int maxViewWidth = deskBounds.width - extraSpace;
// is canvas bigger than largest viewable panel?
if ((canvasSize.width > maxViewWidth) ||
(canvasSize.height > maxViewHeight))
{
// yes it is
// so calc best scale that brings whole image into max viewable panel size
final double canvasAspect = 1.0 * canvasSize.width / canvasSize.height;
final double viewAspect = 1.0 * maxViewWidth / maxViewHeight;
if (canvasAspect < viewAspect) {
// image height the issue
return 1.0 * maxViewHeight / canvasSize.height;
}
// else image width the issue
return 1.0 * maxViewWidth / canvasSize.width;
}
// else canvas fits on screen as is
return 1;
}
}
| Revert "Do some sanity checking on slider vars"
This reverts commit 4f36454cfa6a14b3b74042dffb66c349a57aac56.
| plugins/uis/swing/src/main/java/imagej/ui/swing/viewer/image/SwingDisplayPanel.java | Revert "Do some sanity checking on slider vars" |
|
Java | mit | 25e9756ff1323d166ca10a7cdc529de6ed2a1f9f | 0 | guodongrui/left-behind-child | src/test/java/org/lbchild/window/MyFirstTest.java | package org.lbchild.window;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.junit.SWTBotJunit4ClassRunner;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(SWTBotJunit4ClassRunner.class)
public class MyFirstTest {
private static SWTWorkbenchBot bot;
@BeforeClass
public static void beforeClass() throws Exception {
bot = new SWTWorkbenchBot();
bot.viewByTitle("Welcome").close();
}
@Test
public void canCreateANewJavaProject() throws Exception {
bot.menu("File").menu("New").menu("Project...").click();
SWTBotShell shell = bot.shell("New Project");
shell.activate();
bot.tree().expandNode("Java").select("Java Project");
bot.button("Next >").click();
bot.textWithLabel("Project name:").setText("MyFirstProject");
bot.button("Finish").click();
// FIXME: assert that the project is actually created, for later
}
@AfterClass
public static void sleep() {
bot.sleep(2000);
}
} | Delete MyFirstTest.java | src/test/java/org/lbchild/window/MyFirstTest.java | Delete MyFirstTest.java |
||
Java | apache-2.0 | 99c8b312ee732d1aeece144238fcde599beb63af | 0 | apache/tapestry-5,apache/tapestry-5,apache/tapestry-5,apache/tapestry-5,apache/tapestry-5 | tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DelegatingMessagesImpl.java | // Copyright 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.services;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.ioc.Messages;
/**
* Implementation of {@link Messages} that wraps two other Messages instances: a primary and a delegate.
* The primary handles any keys it contains; method invocations that reference keys not contained by
* the primary are passed on to the delegate.
*
* @since 5.2.0
*/
public class DelegatingMessagesImpl implements Messages
{
private final Messages primary, delegate;
public DelegatingMessagesImpl(Messages primary, Messages delegate)
{
this.primary = primary;
this.delegate = delegate;
}
public boolean contains(String key)
{
return primary.contains(key) || delegate.contains(key);
}
private Messages select(String key)
{
return primary.contains(key) ? primary : delegate;
}
public String format(String key, Object... args)
{
return select(key).format(key, args);
}
public String get(String key)
{
return select(key).get(key);
}
public MessageFormatter getFormatter(String key)
{
return select(key).getFormatter(key);
}
}
| Remove unused class
| tapestry-core/src/main/java/org/apache/tapestry5/internal/services/DelegatingMessagesImpl.java | Remove unused class |
||
Java | mit | f78a6b3082d1569ec6d94e768f7d1ba883c37cb0 | 0 | mzmine/mzmine3,mzmine/mzmine3 | /*
* Copyright 2006-2008 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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 2 of the License, or (at your option) any later
* version.
*
* MZmine 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
* MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.visualization.threed;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.rmi.RemoteException;
import java.text.NumberFormat;
import net.sf.mzmine.data.ChromatographicPeak;
import net.sf.mzmine.data.PeakIdentity;
import net.sf.mzmine.data.PeakList;
import net.sf.mzmine.data.PeakListRow;
import net.sf.mzmine.main.MZmineCore;
import visad.AxisScale;
import visad.ConstantMap;
import visad.Data;
import visad.DataReference;
import visad.DataReferenceImpl;
import visad.Display;
import visad.FieldImpl;
import visad.FlatField;
import visad.FunctionType;
import visad.GraphicsModeControl;
import visad.Gridded2DSet;
import visad.MathType;
import visad.MouseHelper;
import visad.ProjectionControl;
import visad.Real;
import visad.RealTupleType;
import visad.RealType;
import visad.SI;
import visad.ScalarMap;
import visad.Set;
import visad.Text;
import visad.TextControl;
import visad.TextType;
import visad.Tuple;
import visad.TupleType;
import visad.VisADException;
import visad.bom.PickManipulationRendererJ3D;
import visad.java3d.DisplayImplJ3D;
import visad.java3d.DisplayRendererJ3D;
import visad.java3d.KeyboardBehaviorJ3D;
import visad.java3d.MouseBehaviorJ3D;
/**
* Visad's DisplayImplJ3D modified for our purpose
*/
class ThreeDDisplay extends DisplayImplJ3D {
private static final Font annotationFont = new Font("SansSerif",
Font.PLAIN, 8);
// axes aspect ratio X:Y:Z
private static final double[] ASPECT_RATIO = new double[] { 1, 0.8, 0.3 };
private RealType retentionTimeType, mzType, intensityType;
// peak height is for picked peaks, same as intensity, but not
// mapped to color
private RealType peakHeightType;
// [X:Y:Z] tuple for drawing peak box
private RealTupleType pointTupleType;
// function domain - R^2 (retention time and m/z)
private RealTupleType domainTuple;
// annotation type
private TextType annotationType;
// annotation range
private TupleType annotationTupleType;
// peak area renderer
private PickManipulationRendererJ3D pickRenderer;
// peak areas
private ThreeDPeakCells cells;
// functions domain -> range
private FunctionType intensityFunction, annotationFunction;
private ScalarMap retentionTimeMap, mzMap, intensityMap, heightMap,
colorMap, annotationMap;
// data references
private DataReference dataReference, peaksReference;
// axes
private AxisScale retentionTimeAxis, mzAxis, intensityAxis;
private double maxIntensity;
private boolean peaksShown;
private ConstantMap[] peakColorMap;
ThreeDDisplay() throws RemoteException, VisADException {
super("display");
// Setup data types
peakHeightType = RealType.getRealType("Height");
retentionTimeType = RealType.getRealType("RT", SI.second);
mzType = RealType.getRealType("m/z");
intensityType = RealType.getRealType("Intensity");
annotationType = TextType.getTextType("Annotation");
pointTupleType = new RealTupleType(retentionTimeType, mzType,
peakHeightType);
domainTuple = new RealTupleType(retentionTimeType, mzType);
annotationTupleType = new TupleType(new MathType[] { peakHeightType,
annotationType });
// Create a function from domain (retention time and m/z) to
// intensity
intensityFunction = new FunctionType(domainTuple, intensityType);
// Create a function from domain (retention time and m/z) to text
// annotation
annotationFunction = new FunctionType(domainTuple, annotationTupleType);
// create a DataReference connecting data to display
dataReference = new DataReferenceImpl("data");
// create mapping for X,Y,Z axes and color
retentionTimeMap = new ScalarMap(retentionTimeType, Display.XAxis);
mzMap = new ScalarMap(mzType, Display.YAxis);
intensityMap = new ScalarMap(intensityType, Display.ZAxis);
heightMap = new ScalarMap(peakHeightType, Display.ZAxis);
colorMap = new ScalarMap(intensityType, Display.RGB);
annotationMap = new ScalarMap(annotationType, Display.Text);
// Add maps to display
addMap(retentionTimeMap);
addMap(mzMap);
addMap(intensityMap);
addMap(heightMap);
addMap(colorMap);
addMap(annotationMap);
// Get formatters
NumberFormat rtFormat = MZmineCore.getRTFormat();
NumberFormat intensityFormat = MZmineCore.getIntensityFormat();
// set retention time axis properties
retentionTimeAxis = retentionTimeMap.getAxisScale();
retentionTimeAxis.setColor(Color.black);
retentionTimeAxis.setTitle("Retention time");
retentionTimeAxis.setLabelAllTicks(true);
retentionTimeAxis.setNumberFormat(rtFormat);
retentionTimeAxis.setFont(annotationFont);
// set m/z axis properties
// we ignore mzformat because it ends up like 400.00000 anyway
mzAxis = mzMap.getAxisScale();
mzAxis.setColor(Color.black);
mzAxis.setLabelAllTicks(true);
mzAxis.setFont(annotationFont);
// set intensity axis properties
intensityAxis = intensityMap.getAxisScale();
intensityAxis.setColor(Color.black);
intensityAxis.setLabelAllTicks(true);
intensityAxis.setNumberFormat(intensityFormat);
intensityAxis.setFont(annotationFont);
// height is the same as intensity
AxisScale peakHeightAxis = heightMap.getAxisScale();
peakHeightAxis.setVisible(false);
// get graphics mode control to set axes and textures properties
GraphicsModeControl dispGMC = getGraphicsModeControl();
// show axis scales
dispGMC.setScaleEnable(true);
// no textures
dispGMC.setTextureEnable(false);
// get display renderer to set colors, box, mouse, keys..
DisplayRendererJ3D dRenderer = (DisplayRendererJ3D) getDisplayRenderer();
// set colors
dRenderer.setForegroundColor(Color.black);
dRenderer.setBackgroundColor(Color.white);
// do not show box around the data
dRenderer.setBoxOn(false);
// set the mouse behavior
int mouseBehavior[][][] = new int[][][] { { { MouseHelper.ROTATE, // left
// mouse
// button
MouseHelper.ZOOM // SHIFT + left mouse button
}, { MouseHelper.ROTATE, // CTRL + left mouse button
MouseHelper.ZOOM // CTRL + SHIFT + left mouse button
} }, { { MouseHelper.NONE, // middle mouse button
MouseHelper.NONE // SHIFT + middle mouse button
}, { MouseHelper.NONE, // CTRL + middle mouse button
MouseHelper.NONE // CTRL + SHIFT + middle mouse
// button
} }, { { MouseHelper.TRANSLATE, // right mouse button
MouseHelper.DIRECT // SHIFT + right mouse button
}, { MouseHelper.TRANSLATE, // CTRL + right mouse button
MouseHelper.DIRECT // CTRL + SHIFT + right mouse button
} } };
dRenderer.getMouseBehavior().getMouseHelper().setFunctionMap(
mouseBehavior);
// set the keyboard behavior
KeyboardBehaviorJ3D keyBehavior = new KeyboardBehaviorJ3D(dRenderer);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_X_POS,
KeyEvent.VK_DOWN, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_X_NEG,
KeyEvent.VK_UP, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Y_POS,
KeyEvent.VK_LEFT, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Y_NEG,
KeyEvent.VK_RIGHT, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Z_POS,
KeyEvent.VK_PAGE_UP, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Z_NEG,
KeyEvent.VK_PAGE_DOWN, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_IN,
KeyEvent.VK_PLUS, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_OUT,
KeyEvent.VK_MINUS, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_IN,
KeyEvent.VK_ADD, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_OUT,
KeyEvent.VK_SUBTRACT, 0);
dRenderer.addKeyboardBehavior(keyBehavior);
// set text control properties
TextControl textControl = (TextControl) annotationMap.getControl();
textControl.setCenter(true);
textControl.setAutoSize(false);
textControl.setScale(0.3);
textControl.setFont(annotationFont);
// get projection control to set initial rotation and zooming
ProjectionControl projCont = getProjectionControl();
// set axes aspect ratio
projCont.setAspect(ASPECT_RATIO);
// get default projection matrix
double[] pControlMatrix = projCont.getMatrix();
// prepare rotation and scaling matrix
double[] mult = MouseBehaviorJ3D.static_make_matrix(75, 0, 0, // rotation
// X,Y,Z
1, // scaling
0.1, 0.2, 0 // translation (moving) X,Y,Z
);
// multiply projection matrix
pControlMatrix = MouseBehaviorJ3D.static_multiply_matrix(mult,
pControlMatrix);
// set new projection matrix
projCont.setMatrix(pControlMatrix);
// color of text annotations
peakColorMap = new ConstantMap[] { new ConstantMap(1, Display.Red),
new ConstantMap(1, Display.Green),
new ConstantMap(0.0, Display.Blue) };
// create a pick renderer, so we can track user clicks
pickRenderer = new PickManipulationRendererJ3D();
// data reference for peaks
peaksReference = new DataReferenceImpl("peaks");
peaksShown = false;
// peak area cells
cells = new ThreeDPeakCells(this);
}
/**
* Set data points
*/
void setData(double intensityValues[][], Set domainSet, double rtMin,
double rtMax, double mzMin, double mzMax, double maxIntensity) {
try {
// sampled Intensity values stored in 1D array (FlatField)
FlatField intensityValuesFlatField = new FlatField(
intensityFunction, domainSet);
intensityValuesFlatField.setSamples(intensityValues, false);
this.maxIntensity = maxIntensity;
retentionTimeMap.setRange(rtMin, rtMax);
mzMap.setRange(mzMin, mzMax);
intensityMap.setRange(0, maxIntensity);
heightMap.setRange(0, maxIntensity);
// set the color axis top intensity to 20% of the maximum intensity
// value, because the peaks are usually sharp
colorMap.setRange(0, maxIntensity / 5);
dataReference.setData(intensityValuesFlatField);
addReference(dataReference);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set picked peaks
*/
void setPeaks(PeakList peakList, ChromatographicPeak peaks[],
boolean showCompoundName) {
try {
float peaksDomainPoints[][] = new float[2][peaks.length];
Data peakValues[] = new Data[peaks.length];
// set the resolution (number of data points) on m/z axis
NumberFormat mzFormat = MZmineCore.getMZFormat();
for (int i = 0; i < peaks.length; i++) {
peaksDomainPoints[0][i] = (float) peaks[i].getRT();
peaksDomainPoints[1][i] = (float) peaks[i].getMZ();
Data[] peakData = new Data[2];
peakData[0] = new Real(peakHeightType, peaks[i].getHeight()
+ (maxIntensity * 0.03));
String peakText;
PeakListRow row = peakList.getPeakRow(peaks[i]);
PeakIdentity id = row.getPreferredCompoundIdentity();
if (showCompoundName && (id != null))
peakText = id.getName();
else
peakText = mzFormat.format(peaks[i].getMZ());
peakData[1] = new Text(annotationType, peakText);
peakValues[i] = new Tuple(annotationTupleType, peakData, false);
}
// peak domain points set
Set peaksDomainSet = new Gridded2DSet(domainTuple,
peaksDomainPoints, peaks.length);
// create peak values flat field
FieldImpl peakValuesFlatField = new FieldImpl(annotationFunction,
peaksDomainSet);
peakValuesFlatField.setSamples(peakValues, false);
peaksReference.setData(peakValuesFlatField);
// We have to remove the reference and add it again because the data
// have changed
if (peaksShown) {
cells.removeReference(peaksReference);
}
cells.addReference(peaksReference);
if (!peaksShown) {
addReferences(pickRenderer, peaksReference, peakColorMap);
peaksShown = true;
}
cells.setPeaks(peaks);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Toggle whether peaks are annotated or not. Annotation requires setPeaks()
* call first.
*
*/
void toggleShowingPeaks() {
try {
if (peaksShown) {
removeReference(peaksReference);
peaksShown = false;
} else {
addReferences(pickRenderer, peaksReference, peakColorMap);
peaksShown = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
RealTupleType getPointTupleType() {
return pointTupleType;
}
PickManipulationRendererJ3D getPickRenderer() {
return pickRenderer;
}
RealTupleType getDomainTuple() {
return domainTuple;
}
}
| src/net/sf/mzmine/modules/visualization/threed/ThreeDDisplay.java | /*
* Copyright 2006-2008 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine 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 2 of the License, or (at your option) any later
* version.
*
* MZmine 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
* MZmine; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.visualization.threed;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.rmi.RemoteException;
import java.text.NumberFormat;
import net.sf.mzmine.data.ChromatographicPeak;
import net.sf.mzmine.data.PeakIdentity;
import net.sf.mzmine.data.PeakList;
import net.sf.mzmine.data.PeakListRow;
import net.sf.mzmine.main.MZmineCore;
import visad.AxisScale;
import visad.ConstantMap;
import visad.Data;
import visad.DataReference;
import visad.DataReferenceImpl;
import visad.Display;
import visad.FieldImpl;
import visad.FlatField;
import visad.FunctionType;
import visad.GraphicsModeControl;
import visad.Gridded2DSet;
import visad.MathType;
import visad.MouseHelper;
import visad.ProjectionControl;
import visad.Real;
import visad.RealTupleType;
import visad.RealType;
import visad.SI;
import visad.ScalarMap;
import visad.Set;
import visad.Text;
import visad.TextControl;
import visad.TextType;
import visad.Tuple;
import visad.TupleType;
import visad.VisADException;
import visad.bom.PickManipulationRendererJ3D;
import visad.java3d.DisplayImplJ3D;
import visad.java3d.DisplayRendererJ3D;
import visad.java3d.KeyboardBehaviorJ3D;
import visad.java3d.MouseBehaviorJ3D;
/**
* Visad's DisplayImplJ3D modified for our purpose
*/
class ThreeDDisplay extends DisplayImplJ3D {
// number of labeled ticks on retention time axis
private static final int X_AXIS_TICKS = 30;
// number of labeled ticks on m/z axis
private static final int Y_AXIS_TICKS = 20;
// number of labeled ticks (marks) on intensity axis
private static final int Z_AXIS_TICKS = 10;
// number of minor (not labeled) axis ticks per 1 major tick
private static final int MINOR_TICKS = 5;
// tick labels font size
private static final int LABEL_FONT_SIZE = 2;
// axes aspect ratio X:Y:Z
private static final double[] ASPECT_RATIO = new double[] { 1, 0.8, 0.3 };
private RealType retentionTimeType, mzType, intensityType;
// peak height is for picked peaks, same as intensity, but not
// mapped to color
private RealType peakHeightType;
// [X:Y:Z] tuple for drawing peak box
private RealTupleType pointTupleType;
// function domain - R^2 (retention time and m/z)
private RealTupleType domainTuple;
// annotation type
private TextType annotationType;
// annotation range
private TupleType annotationTupleType;
// peak area renderer
private PickManipulationRendererJ3D pickRenderer;
// peak areas
private ThreeDPeakCells cells;
// functions domain -> range
private FunctionType intensityFunction, annotationFunction;
private ScalarMap retentionTimeMap, mzMap, intensityMap, heightMap,
colorMap, annotationMap;
// data references
private DataReference dataReference, peaksReference;
// axes
private AxisScale retentionTimeAxis, mzAxis, intensityAxis;
private double maxIntensity;
private boolean peaksShown;
private ConstantMap[] peakColorMap;
ThreeDDisplay() throws RemoteException, VisADException {
super("display");
// Setup data types
peakHeightType = RealType.getRealType("Height");
retentionTimeType = RealType.getRealType("RT", SI.second);
mzType = RealType.getRealType("m/z");
intensityType = RealType.getRealType("Intensity");
annotationType = TextType.getTextType("Annotation");
pointTupleType = new RealTupleType(retentionTimeType, mzType,
peakHeightType);
domainTuple = new RealTupleType(retentionTimeType, mzType);
annotationTupleType = new TupleType(new MathType[] { peakHeightType,
annotationType });
// Create a function from domain (retention time and m/z) to
// intensity
intensityFunction = new FunctionType(domainTuple, intensityType);
// Create a function from domain (retention time and m/z) to text
// annotation
annotationFunction = new FunctionType(domainTuple, annotationTupleType);
// create a DataReference connecting data to display
dataReference = new DataReferenceImpl("data");
// create mapping for X,Y,Z axes and color
retentionTimeMap = new ScalarMap(retentionTimeType, Display.XAxis);
mzMap = new ScalarMap(mzType, Display.YAxis);
intensityMap = new ScalarMap(intensityType, Display.ZAxis);
heightMap = new ScalarMap(peakHeightType, Display.ZAxis);
colorMap = new ScalarMap(intensityType, Display.RGB);
annotationMap = new ScalarMap(annotationType, Display.Text);
// Add maps to display
addMap(retentionTimeMap);
addMap(mzMap);
addMap(intensityMap);
addMap(heightMap);
addMap(colorMap);
addMap(annotationMap);
// Get formatters
NumberFormat rtFormat = MZmineCore.getRTFormat();
NumberFormat mzFormat = MZmineCore.getMZFormat();
NumberFormat intensityFormat = MZmineCore.getIntensityFormat();
// set retention time axis properties
retentionTimeAxis = retentionTimeMap.getAxisScale();
retentionTimeAxis.setColor(Color.black);
retentionTimeAxis.setTitle("Retention time");
retentionTimeAxis.setLabelSize(LABEL_FONT_SIZE);
retentionTimeAxis.setLabelAllTicks(true);
retentionTimeAxis.setNumberFormat(rtFormat);
// set m/z axis properties
mzAxis = mzMap.getAxisScale();
mzAxis.setColor(Color.black);
mzAxis.setLabelSize(LABEL_FONT_SIZE);
mzAxis.setLabelAllTicks(true);
mzAxis.setNumberFormat(mzFormat);
mzAxis.setFont(new Font("SansSerif", Font.PLAIN, 8));
// set intensity axis properties
intensityAxis = intensityMap.getAxisScale();
intensityAxis.setColor(Color.black);
intensityAxis.setLabelSize(LABEL_FONT_SIZE);
intensityAxis.setLabelAllTicks(true);
intensityAxis.setNumberFormat(intensityFormat);
// height is the same as intensity
AxisScale peakHeightAxis = heightMap.getAxisScale();
peakHeightAxis.setVisible(false);
// get graphics mode control to set axes and textures properties
GraphicsModeControl dispGMC = getGraphicsModeControl();
// show axis scales
dispGMC.setScaleEnable(true);
// no textures
dispGMC.setTextureEnable(false);
// get display renderer to set colors, box, mouse, keys..
DisplayRendererJ3D dRenderer = (DisplayRendererJ3D) getDisplayRenderer();
// set colors
dRenderer.setForegroundColor(Color.black);
dRenderer.setBackgroundColor(Color.white);
// do not show box around the data
dRenderer.setBoxOn(false);
// set the mouse behavior
int mouseBehavior[][][] = new int[][][] { {
{ MouseHelper.ROTATE, // left mouse button
MouseHelper.ZOOM // SHIFT + left mouse button
}, { MouseHelper.ROTATE, // CTRL + left mouse button
MouseHelper.ZOOM // CTRL + SHIFT + left mouse button
} }, { { MouseHelper.NONE, // middle mouse button
MouseHelper.NONE // SHIFT + middle mouse button
}, { MouseHelper.NONE, // CTRL + middle mouse button
MouseHelper.NONE // CTRL + SHIFT + middle mouse
// button
} }, { { MouseHelper.TRANSLATE, // right mouse button
MouseHelper.DIRECT // SHIFT + right mouse button
}, { MouseHelper.TRANSLATE, // CTRL + right mouse button
MouseHelper.DIRECT // CTRL + SHIFT + right mouse button
} } };
dRenderer.getMouseBehavior().getMouseHelper().setFunctionMap(
mouseBehavior);
// set the keyboard behavior
KeyboardBehaviorJ3D keyBehavior = new KeyboardBehaviorJ3D(dRenderer);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_X_POS,
KeyEvent.VK_DOWN, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_X_NEG,
KeyEvent.VK_UP, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Y_POS,
KeyEvent.VK_LEFT, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Y_NEG,
KeyEvent.VK_RIGHT, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Z_POS,
KeyEvent.VK_PAGE_UP, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ROTATE_Z_NEG,
KeyEvent.VK_PAGE_DOWN, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_IN,
KeyEvent.VK_PLUS, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_OUT,
KeyEvent.VK_MINUS, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_IN,
KeyEvent.VK_ADD, 0);
keyBehavior.mapKeyToFunction(KeyboardBehaviorJ3D.ZOOM_OUT,
KeyEvent.VK_SUBTRACT, 0);
dRenderer.addKeyboardBehavior(keyBehavior);
// set text control properties
TextControl textControl = (TextControl) annotationMap.getControl();
textControl.setCenter(true);
textControl.setAutoSize(false);
textControl.setScale(0.1);
// get projection control to set initial rotation and zooming
ProjectionControl projCont = getProjectionControl();
// set axes aspect ratio
projCont.setAspect(ASPECT_RATIO);
// get default projection matrix
double[] pControlMatrix = projCont.getMatrix();
// prepare rotation and scaling matrix
double[] mult = MouseBehaviorJ3D.static_make_matrix(
75, 0, 0, // rotation X,Y,Z
1, // scaling
0.1, 0.2, 0 // translation (moving) X,Y,Z
);
// multiply projection matrix
pControlMatrix = MouseBehaviorJ3D.static_multiply_matrix(mult,
pControlMatrix);
// set new projection matrix
projCont.setMatrix(pControlMatrix);
// color of text annotations
peakColorMap = new ConstantMap[] { new ConstantMap(0.8, Display.Red),
new ConstantMap(0.8, Display.Green),
new ConstantMap(0.0f, Display.Blue) };
// create a pick renderer, so we can track user clicks
pickRenderer = new PickManipulationRendererJ3D();
// data reference for peaks
peaksReference = new DataReferenceImpl("peaks");
peaksShown = false;
// peak area cells
cells = new ThreeDPeakCells(this);
}
/**
* Set data points
*/
void setData(double intensityValues[][], Set domainSet, double rtMin,
double rtMax, double mzMin, double mzMax, double maxIntensity) {
try {
// sampled Intensity values stored in 1D array (FlatField)
FlatField intensityValuesFlatField = new FlatField(
intensityFunction, domainSet);
intensityValuesFlatField.setSamples(intensityValues, false);
this.maxIntensity = maxIntensity;
retentionTimeMap.setRange(rtMin, rtMax);
mzMap.setRange(mzMin, mzMax);
intensityMap.setRange(0, maxIntensity);
heightMap.setRange(0, maxIntensity);
// set the color axis top intensity to 20% of the maximum intensity
// value, because the peaks are usually sharp
colorMap.setRange(0, maxIntensity / 5);
double mzRange = mzMax - mzMin;
double rtRange = rtMax - rtMin;
double ticks = Math.round(rtRange / X_AXIS_TICKS);
retentionTimeAxis.setMinorTickSpacing(ticks / MINOR_TICKS);
retentionTimeAxis.setMajorTickSpacing(ticks);
ticks = Math.round(mzRange / Y_AXIS_TICKS);
mzAxis.setMinorTickSpacing(ticks / MINOR_TICKS);
mzAxis.setMajorTickSpacing(ticks);
ticks = Math.round(maxIntensity / Z_AXIS_TICKS);
intensityAxis.setMinorTickSpacing(ticks / MINOR_TICKS);
intensityAxis.setMajorTickSpacing(ticks);
dataReference.setData(intensityValuesFlatField);
addReference(dataReference);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Set picked peaks
*/
void setPeaks(PeakList peakList, ChromatographicPeak peaks[], boolean showCompoundName) {
try {
float peaksDomainPoints[][] = new float[2][peaks.length];
Data peakValues[] = new Data[peaks.length];
// set the resolution (number of data points) on m/z axis
NumberFormat mzFormat = MZmineCore.getMZFormat();
for (int i = 0; i < peaks.length; i++) {
peaksDomainPoints[0][i] = (float) peaks[i].getRT();
peaksDomainPoints[1][i] = (float) peaks[i].getMZ();
Data[] peakData = new Data[2];
peakData[0] = new Real(peakHeightType, peaks[i].getHeight()
+ (maxIntensity * 0.03));
String peakText;
PeakListRow row = peakList.getPeakRow(peaks[i]);
PeakIdentity id = row.getPreferredCompoundIdentity();
if (showCompoundName && (id != null))
peakText = id.getName();
else
peakText = mzFormat.format(peaks[i].getMZ());
peakData[1] = new Text(annotationType, peakText);
peakValues[i] = new Tuple(annotationTupleType, peakData, false);
}
// peak domain points set
Set peaksDomainSet = new Gridded2DSet(domainTuple,
peaksDomainPoints, peaks.length);
// create peak values flat field
FieldImpl peakValuesFlatField = new FieldImpl(annotationFunction,
peaksDomainSet);
peakValuesFlatField.setSamples(peakValues, false);
peaksReference.setData(peakValuesFlatField);
// We have to remove the reference and add it again because the data
// have changed
if (peaksShown) {
cells.removeReference(peaksReference);
}
cells.addReference(peaksReference);
if (!peaksShown) {
addReferences(pickRenderer, peaksReference, peakColorMap);
peaksShown = true;
}
cells.setPeaks(peaks);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Toggle whether peaks are annotated or not. Annotation requires setPeaks()
* call first.
*
*/
void toggleShowingPeaks() {
try {
if (peaksShown) {
removeReference(peaksReference);
peaksShown = false;
} else {
addReferences(pickRenderer, peaksReference, peakColorMap);
peaksShown = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
RealTupleType getPointTupleType() {
return pointTupleType;
}
PickManipulationRendererJ3D getPickRenderer() {
return pickRenderer;
}
RealTupleType getDomainTuple() {
return domainTuple;
}
}
| Updated the font of 3D visualizer
| src/net/sf/mzmine/modules/visualization/threed/ThreeDDisplay.java | Updated the font of 3D visualizer |
|
Java | mit | d2ae5d727fbfc624ef390eb05c8e395bc1a109f2 | 0 | nagash91/TheGuardiansApp | package micc.theguardiansapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import micc.theguardiansapp.scrollPager.MyScrollPager;
public class FiActivity extends ActionBarActivity {
private ScrollView scrollView;
private ViewGroup contentView;
private ViewGroup[] fragContainer;
ImageView audioButton1;
ImageView audioButton2;
boolean audio1playing = false;
boolean audio2playing = false;
MediaPlayer mPlayer;
SliderLayout sliderShowAccademia;
SliderLayout sliderShowAccademia2;
SliderLayout sliderShowHero;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fi);
setTitle("Firenze");
scrollView = (ScrollView) findViewById(R.id.scroll_view_fi);
contentView = (ViewGroup) findViewById(R.id.scrolledLayout_fi);
fragContainer = new ViewGroup[3];
fragContainer[0] = (ViewGroup) findViewById(R.id.fragContainer0_fi);
fragContainer[1] = (ViewGroup) findViewById(R.id.fragContainer1_fi);
fragContainer[2] = (ViewGroup) findViewById(R.id.fragContainer2_fi);
MyScrollPager scrollPager = new MyScrollPager(scrollView, contentView, fragContainer, true, false);
scrollView.setOnTouchListener(scrollPager);
scrollView.post(new Runnable() {
public void run() {
scrollView.scrollTo(0, contentView.getPaddingTop());
}
});
audioButton1 = (ImageView) findViewById(R.id.audio_1_button);
audioButton2 = (ImageView) findViewById(R.id.audio_2_button);
sliderShowAccademia = (SliderLayout) findViewById(R.id.slider_accademia);
sliderShowAccademia2 = (SliderLayout) findViewById(R.id.slider_accademia_2);
sliderShowHero = (SliderLayout) findViewById(R.id.slider_hero_in_accademia);
setUpSliders();
setUpEvents();
}
private void setUpSliders()
{
MyTextSliderView tsv_accademia = new MyTextSliderView(this);
MyTextSliderView tsv_accademia1 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia2 = new MyTextSliderView(this);
//textSliderView.description("Hero").image(R.drawable.guardian_hero);
tsv_accademia
.description(getString(R.string.saracino_speech_fi_1))
.image(R.drawable.s_f)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia1
.description(getString(R.string.saracino_speech_fi_2))
.image(R.drawable.d)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia2
.description(getString(R.string.saracino_speech_fi_3))
.image(R.drawable.s_f)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowAccademia.addSlider(tsv_accademia);
sliderShowAccademia.addSlider(tsv_accademia1);
sliderShowAccademia.addSlider(tsv_accademia2);
sliderShowAccademia.stopAutoCycle();
sliderShowAccademia.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowAccademia.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowAccademia.setCustomAnimation(new DescriptionAnimation());
MyTextSliderView tsv_accademia3 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia4 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia5 = new MyTextSliderView(this);
tsv_accademia3
.description(getString(R.string.tartuferi_speech_1))
.image(R.drawable.a)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia4
.description(getString(R.string.tartuferi_speech_2))
.image(R.drawable.s_f)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia5
.description(getString(R.string.tartuferi_speech_3))
.image(R.drawable.s_p)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowAccademia2.addSlider(tsv_accademia3);
sliderShowAccademia2.addSlider(tsv_accademia4);
sliderShowAccademia2.addSlider(tsv_accademia5);
sliderShowAccademia2.stopAutoCycle();
sliderShowAccademia2.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowAccademia2.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowAccademia2.setCustomAnimation(new DescriptionAnimation());
// HERO
TextSliderView tsv_hero1 = new TextSliderView(this);
TextSliderView tsv_hero2 = new TextSliderView(this);
TextSliderView tsv_hero3 = new TextSliderView(this);
TextSliderView tsv_hero4 = new TextSliderView(this);
TextSliderView tsv_hero5 = new TextSliderView(this);
TextSliderView tsv_hero6 = new TextSliderView(this);
//textSliderView.description("Hero").image(R.drawable.guardian_hero);
tsv_hero1
.description("Genesis of Hero")
.image(R.drawable.cava)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero2
.description("Genesis of Hero")
.image(R.drawable.blocco)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero3
.description("Genesis of Hero")
.image(R.drawable.blocco2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero4
.description("Genesis of Hero")
.image(R.drawable.fresa)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero5
.description("Genesis of Hero")
.image(R.drawable.osso)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero6
.description("Genesis of Hero")
.image(R.drawable.osso2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowHero.addSlider(tsv_hero1);
sliderShowHero.addSlider(tsv_hero2);
sliderShowHero.addSlider(tsv_hero3);
sliderShowHero.addSlider(tsv_hero4);
sliderShowHero.addSlider(tsv_hero5);
sliderShowHero.addSlider(tsv_hero6);
sliderShowHero.stopAutoCycle();
sliderShowHero.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowHero.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowHero.setCustomAnimation(new DescriptionAnimation());
}
private void stopAudio1()
{
audio1playing = false;
audioButton1.setImageResource(R.drawable.play);
if(mPlayer != null ) {
mPlayer.stop();
mPlayer.reset();
}
}
private void stopAudio2()
{
audio2playing = false;
audioButton2.setImageResource(R.drawable.play);
if(mPlayer != null ) {
mPlayer.stop();
mPlayer.reset();
}
}
private void stopAudio()
{
stopAudio1();
stopAudio2();
}
private void playAudio1()
{
stopAudio1();
stopAudio2();
audio1playing = true;
audioButton1.setImageResource(R.drawable.stop);
mPlayer = MediaPlayer.create(getBaseContext(), R.raw.innocenti_florence_en);
mPlayer.start();
}
private void playAudio2()
{
stopAudio1();
stopAudio2();
audio2playing = true;
audioButton2.setImageResource(R.drawable.stop);
mPlayer = MediaPlayer.create(getBaseContext(), R.raw.tartufieri_florence_it);
mPlayer.start();
}
private void setUpEvents()
{
audioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!audio1playing)
{
playAudio1();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
}
});
}
else
{
stopAudio1();
}
}
});
audioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!audio2playing)
{
playAudio2();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
}
});
}
else
{
stopAudio2();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_fi, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| app/src/main/java/micc/theguardiansapp/FiActivity.java | package micc.theguardiansapp;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import micc.theguardiansapp.scrollPager.MyScrollPager;
public class FiActivity extends ActionBarActivity {
private ScrollView scrollView;
private ViewGroup contentView;
private ViewGroup[] fragContainer;
ImageView audioButton1;
ImageView audioButton2;
boolean audio1playing = false;
boolean audio2playing = false;
MediaPlayer mPlayer;
SliderLayout sliderShowAccademia;
SliderLayout sliderShowAccademia2;
SliderLayout sliderShowHero;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fi);
setTitle("Firenze");
scrollView = (ScrollView) findViewById(R.id.scroll_view_fi);
contentView = (ViewGroup) findViewById(R.id.scrolledLayout_fi);
fragContainer = new ViewGroup[3];
fragContainer[0] = (ViewGroup) findViewById(R.id.fragContainer0_fi);
fragContainer[1] = (ViewGroup) findViewById(R.id.fragContainer1_fi);
fragContainer[2] = (ViewGroup) findViewById(R.id.fragContainer2_fi);
MyScrollPager scrollPager = new MyScrollPager(scrollView, contentView, fragContainer, true, false);
scrollView.setOnTouchListener(scrollPager);
scrollView.post(new Runnable() {
public void run() {
scrollView.scrollTo(0, contentView.getPaddingTop());
}
});
audioButton1 = (ImageView) findViewById(R.id.audio_1_button);
audioButton2 = (ImageView) findViewById(R.id.audio_2_button);
sliderShowAccademia = (SliderLayout) findViewById(R.id.slider_accademia);
sliderShowAccademia2 = (SliderLayout) findViewById(R.id.slider_accademia_2);
sliderShowHero = (SliderLayout) findViewById(R.id.slider_hero_in_accademia);
setUpSliders();
setUpEvents();
}
private void setUpSliders()
{
MyTextSliderView tsv_accademia = new MyTextSliderView(this);
MyTextSliderView tsv_accademia1 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia2 = new MyTextSliderView(this);
//textSliderView.description("Hero").image(R.drawable.guardian_hero);
tsv_accademia
.description(getString(R.string.saracino_speech_fi_1))
.image(R.drawable.david)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia1
.description(getString(R.string.saracino_speech_fi_2))
.image(R.drawable.hero)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia2
.description(getString(R.string.saracino_speech_fi_3))
.image(R.drawable.hero_2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowAccademia.addSlider(tsv_accademia);
sliderShowAccademia.addSlider(tsv_accademia1);
sliderShowAccademia.addSlider(tsv_accademia2);
sliderShowAccademia.stopAutoCycle();
sliderShowAccademia.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowAccademia.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowAccademia.setCustomAnimation(new DescriptionAnimation());
MyTextSliderView tsv_accademia3 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia4 = new MyTextSliderView(this);
MyTextSliderView tsv_accademia5 = new MyTextSliderView(this);
tsv_accademia3
.description(getString(R.string.tartuferi_speech_1))
.image(R.drawable.david)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia4
.description(getString(R.string.tartuferi_speech_2))
.image(R.drawable.hero)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_accademia5
.description(getString(R.string.tartuferi_speech_3))
.image(R.drawable.hero_2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowAccademia2.addSlider(tsv_accademia3);
sliderShowAccademia2.addSlider(tsv_accademia4);
sliderShowAccademia2.addSlider(tsv_accademia5);
sliderShowAccademia2.stopAutoCycle();
sliderShowAccademia2.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowAccademia2.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowAccademia2.setCustomAnimation(new DescriptionAnimation());
// HERO
TextSliderView tsv_hero1 = new TextSliderView(this);
TextSliderView tsv_hero2 = new TextSliderView(this);
TextSliderView tsv_hero3 = new TextSliderView(this);
TextSliderView tsv_hero4 = new TextSliderView(this);
TextSliderView tsv_hero5 = new TextSliderView(this);
TextSliderView tsv_hero6 = new TextSliderView(this);
//textSliderView.description("Hero").image(R.drawable.guardian_hero);
tsv_hero1
.description("Genesis of Hero")
.image(R.drawable.cava)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero2
.description("Genesis of Hero")
.image(R.drawable.blocco)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero3
.description("Genesis of Hero")
.image(R.drawable.blocco2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero4
.description("Genesis of Hero")
.image(R.drawable.osso)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero5
.description("Genesis of Hero")
.image(R.drawable.osso2)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
tsv_hero6
.description("Genesis of Hero")
.image(R.drawable.fresa)
.setScaleType(BaseSliderView.ScaleType.CenterInside);
sliderShowHero.addSlider(tsv_hero1);
sliderShowHero.addSlider(tsv_hero2);
sliderShowHero.addSlider(tsv_hero3);
sliderShowHero.addSlider(tsv_hero4);
sliderShowHero.addSlider(tsv_hero5);
sliderShowHero.addSlider(tsv_hero6);
sliderShowHero.stopAutoCycle();
sliderShowHero.setPresetTransformer(SliderLayout.Transformer.DepthPage);
//sliderShow.setCustomIndicator((PagerIndicator) findViewById(R.id.custom_indicator));
sliderShowHero.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);
sliderShowHero.setCustomAnimation(new DescriptionAnimation());
}
private void stopAudio1()
{
audio1playing = false;
audioButton1.setImageResource(R.drawable.play);
if(mPlayer != null ) {
mPlayer.stop();
mPlayer.reset();
}
}
private void stopAudio2()
{
audio2playing = false;
audioButton2.setImageResource(R.drawable.play);
if(mPlayer != null ) {
mPlayer.stop();
mPlayer.reset();
}
}
private void stopAudio()
{
stopAudio1();
stopAudio2();
}
private void playAudio1()
{
stopAudio1();
stopAudio2();
audio1playing = true;
audioButton1.setImageResource(R.drawable.stop);
mPlayer = MediaPlayer.create(getBaseContext(), R.raw.innocenti_florence_en);
mPlayer.start();
}
private void playAudio2()
{
stopAudio1();
stopAudio2();
audio2playing = true;
audioButton2.setImageResource(R.drawable.stop);
mPlayer = MediaPlayer.create(getBaseContext(), R.raw.tartufieri_florence_it);
mPlayer.start();
}
private void setUpEvents()
{
audioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!audio1playing)
{
playAudio1();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
}
});
}
else
{
stopAudio1();
}
}
});
audioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!audio2playing)
{
playAudio2();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopAudio();
}
});
}
else
{
stopAudio2();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_fi, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Corrette gallerie immagini
Conflicts:
app/app.iml
| app/src/main/java/micc/theguardiansapp/FiActivity.java | Corrette gallerie immagini |
|
Java | mit | 472bda743b193af317ca86d00cc367123f030044 | 0 | fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg | package ua.com.fielden.platform.entity.query.metadata;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractUnionEntity.unionProperties;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getAnnotation;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getPropertyAnnotation;
import static ua.com.fielden.platform.reflection.AnnotationReflector.isContextual;
import static ua.com.fielden.platform.reflection.Finder.getFieldByName;
import static ua.com.fielden.platform.reflection.Finder.getKeyMembers;
import static ua.com.fielden.platform.reflection.Reflector.getKeyMemberSeparator;
import static ua.com.fielden.platform.utils.EntityUtils.isEntityType;
import static ua.com.fielden.platform.utils.EntityUtils.isUnionEntityType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.annotation.Optional;
import ua.com.fielden.platform.entity.meta.PropertyDescriptor;
import ua.com.fielden.platform.entity.query.exceptions.EqlException;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICaseWhenFunctionWhen;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IConcatFunctionWith;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IFromAlias;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IStandAloneExprOperationAndClose;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ISubsequentCompletedAndYielded;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.ExpressionModel;
import ua.com.fielden.platform.expression.ExpressionText2ModelConverter;
import ua.com.fielden.platform.types.tuples.T3;
import ua.com.fielden.platform.utils.Pair;
public class DomainMetadataUtils {
private static final String EMPTY_STRING = "";
/** Private default constructor to prevent instantiation. */
private DomainMetadataUtils() {
}
public static ExpressionModel generateUnionEntityPropertyExpression(final Class<? extends AbstractUnionEntity> entityType, final String commonPropName) {
final List<Field> props = unionProperties(entityType);
final Iterator<Field> iterator = props.iterator();
final String firstUnionPropName = iterator.next().getName();
ICaseWhenFunctionWhen<IStandAloneExprOperationAndClose, AbstractEntity<?>> expressionModelInProgress = expr().caseWhen().prop(firstUnionPropName).isNotNull().then().prop(firstUnionPropName
+ "." + commonPropName);
for (; iterator.hasNext();) {
final String unionPropName = iterator.next().getName();
expressionModelInProgress = expressionModelInProgress.when().prop(unionPropName).isNotNull().then().prop(unionPropName + "." + commonPropName);
}
return expressionModelInProgress.otherwise().val(null).end().model();
}
public static ExpressionModel getVirtualKeyPropForEntityWithCompositeKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType) {
final String keyMemberSeparator = getKeyMemberSeparator(entityType);
final Iterator<Field> kmIter = getKeyMembers(entityType).iterator();
final Field firstKeyMember = kmIter.next();
if (!kmIter.hasNext()) {
return processFirstKeyMember(firstKeyMember.getName(), firstKeyMember.getType(), keyMemberSeparator);
} else {
IConcatFunctionWith<IStandAloneExprOperationAndClose, AbstractEntity<?>> concatStart = expr().concat().expr(processFirstKeyMember(firstKeyMember.getName(), firstKeyMember.getType(), keyMemberSeparator));
while (kmIter.hasNext()) {
final Field nextKeyMember = kmIter.next();
concatStart = getPropertyAnnotation(Optional.class, entityType, nextKeyMember.getName()) != null ?
concatStart.with().expr(processOptionalKeyMember(nextKeyMember.getName(), nextKeyMember.getType(), keyMemberSeparator))
:
concatStart.with().val(keyMemberSeparator).with().expr(expr().prop(getKeyMemberConcatenationPropName(nextKeyMember.getName(), nextKeyMember.getType())).model());
}
return concatStart.end().model();
}
}
private static String getKeyMemberConcatenationPropName(final String keyMemberName, final Class<?> keyMemberType) {
return PropertyDescriptor.class != keyMemberType && isEntityType(keyMemberType) ? keyMemberName + "." + KEY : keyMemberName;
}
private static ExpressionModel processFirstKeyMember(final String keyMemberName, final Class<?> keyMemberType, final String separator) {
return expr().prop(getKeyMemberConcatenationPropName(keyMemberName, keyMemberType)).model();
}
private static ExpressionModel processOptionalKeyMember(final String keyMemberName, final Class<?> keyMemberType, final String separator) {
return expr().caseWhen().prop(keyMemberName).isNotNull().then().concat().val(separator).with().prop(getKeyMemberConcatenationPropName(keyMemberName, keyMemberType)).end().otherwise().val(EMPTY_STRING).end()/*.endAsStr(256)*/.model();
}
public static ExpressionModel extractExpressionModelFromCalculatedProperty(final Class<? extends AbstractEntity<?>> entityType, final Field calculatedPropfield) throws Exception {
final Calculated calcAnnotation = getAnnotation(calculatedPropfield, Calculated.class);
if (isNotEmpty(calcAnnotation.value())) {
return createExpressionText2ModelConverter(entityType, calcAnnotation).convert().getModel();
} else {
try {
final Field exprField = getFieldByName(entityType, calculatedPropfield.getName() + "_");
exprField.setAccessible(true);
return (ExpressionModel) exprField.get(null);
} catch (final Exception e) {
throw new EqlException(format("Can't extract hard-coded expression model for prop [%s] due to: [%s]", calculatedPropfield.getName(), e.getMessage()));
}
}
}
private static ExpressionText2ModelConverter createExpressionText2ModelConverter(final Class<? extends AbstractEntity<?>> entityType, final Calculated calcAnnotation)
throws Exception {
if (isContextual(calcAnnotation)) {
return new ExpressionText2ModelConverter(getRootType(calcAnnotation), calcAnnotation.contextPath(), calcAnnotation.value());
} else {
return new ExpressionText2ModelConverter(entityType, calcAnnotation.value());
}
}
private static Class<? extends AbstractEntity<?>> getRootType(final Calculated calcAnnotation) throws ClassNotFoundException {
return (Class<? extends AbstractEntity<?>>) ClassLoader.getSystemClassLoader().loadClass(calcAnnotation.rootTypeName());
}
public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> produceUnionEntityModels(final Class<ET> entityType) {
final List<EntityResultQueryModel<ET>> result = new ArrayList<>();
if (!isUnionEntityType(entityType)) {
return result;
}
final List<Field> unionProps = unionProperties((Class<? extends AbstractUnionEntity>) entityType);
for (final Field currProp : unionProps) {
result.add(generateModelForUnionEntityProperty(unionProps, currProp).modelAsEntity(entityType));
}
return result;
}
private static <PT extends AbstractEntity<?>> ISubsequentCompletedAndYielded<PT> generateModelForUnionEntityProperty(final List<Field> unionProps, final Field currProp) {
final IFromAlias<PT> startWith = select((Class<PT>) currProp.getType());
final Field firstUnionProp = unionProps.get(0);
final ISubsequentCompletedAndYielded<PT> initialModel = firstUnionProp.equals(currProp) ? startWith.yield().prop(ID).as(firstUnionProp.getName()) : startWith.yield().val(null).as(firstUnionProp.getName());
return unionProps.stream().skip(1).reduce(initialModel, (m, f) -> f.equals(currProp) ? m.yield().prop(ID).as(f.getName()) : m.yield().val(null).as(f.getName()), (m1, m2) -> {throw new UnsupportedOperationException("Combining is not applicable here.");});
}
}
| platform-dao/src/main/java/ua/com/fielden/platform/entity/query/metadata/DomainMetadataUtils.java | package ua.com.fielden.platform.entity.query.metadata;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static ua.com.fielden.platform.entity.AbstractEntity.ID;
import static ua.com.fielden.platform.entity.AbstractEntity.KEY;
import static ua.com.fielden.platform.entity.AbstractUnionEntity.unionProperties;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.expr;
import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getAnnotation;
import static ua.com.fielden.platform.reflection.AnnotationReflector.getPropertyAnnotation;
import static ua.com.fielden.platform.reflection.AnnotationReflector.isContextual;
import static ua.com.fielden.platform.reflection.Finder.getFieldByName;
import static ua.com.fielden.platform.reflection.Finder.getKeyMembers;
import static ua.com.fielden.platform.reflection.Reflector.getKeyMemberSeparator;
import static ua.com.fielden.platform.utils.EntityUtils.isEntityType;
import static ua.com.fielden.platform.utils.EntityUtils.isUnionEntityType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.entity.AbstractUnionEntity;
import ua.com.fielden.platform.entity.DynamicEntityKey;
import ua.com.fielden.platform.entity.annotation.Calculated;
import ua.com.fielden.platform.entity.annotation.Optional;
import ua.com.fielden.platform.entity.meta.PropertyDescriptor;
import ua.com.fielden.platform.entity.query.exceptions.EqlException;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICaseWhenFunctionWhen;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IFromAlias;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.IStandAloneExprOperationAndClose;
import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ISubsequentCompletedAndYielded;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.entity.query.model.ExpressionModel;
import ua.com.fielden.platform.expression.ExpressionText2ModelConverter;
import ua.com.fielden.platform.types.tuples.T3;
import ua.com.fielden.platform.utils.Pair;
public class DomainMetadataUtils {
/** Private default constructor to prevent instantiation. */
private DomainMetadataUtils() {
}
public static ExpressionModel generateUnionEntityPropertyExpression(final Class<? extends AbstractUnionEntity> entityType, final String commonPropName) {
final List<Field> props = unionProperties(entityType);
final Iterator<Field> iterator = props.iterator();
final String firstUnionPropName = iterator.next().getName();
ICaseWhenFunctionWhen<IStandAloneExprOperationAndClose, AbstractEntity<?>> expressionModelInProgress = expr().caseWhen().prop(firstUnionPropName).isNotNull().then().prop(firstUnionPropName
+ "." + commonPropName);
for (; iterator.hasNext();) {
final String unionPropName = iterator.next().getName();
expressionModelInProgress = expressionModelInProgress.when().prop(unionPropName).isNotNull().then().prop(unionPropName + "." + commonPropName);
}
return expressionModelInProgress.otherwise().val(null).end().model();
}
public static ExpressionModel getVirtualKeyPropForEntityWithCompositeKey(final Class<? extends AbstractEntity<DynamicEntityKey>> entityType) {
final List<T3<String, Class<?>, Boolean>> keyMembersWithOptionality = new ArrayList<>();
for (final Field field : getKeyMembers(entityType)) {
keyMembersWithOptionality.add(new T3<String, Class<?>, Boolean>(field.getName(), field.getType(), getPropertyAnnotation(Optional.class, entityType, field.getName()) != null));
}
return composeExpression(keyMembersWithOptionality, getKeyMemberSeparator(entityType));
}
private static String getKeyMemberConcatenationExpression(final String keyMemberName, final Class<?> keyMemberType) {
if (PropertyDescriptor.class != keyMemberType && isEntityType(keyMemberType)) {
return keyMemberName + "." + KEY;
} else {
return keyMemberName;
}
}
private static ExpressionModel composeExpression(final List<T3<String, Class<?>, Boolean>> original, final String separator) {
ExpressionModel currExp = null;
Boolean currExpIsOptional = null;
for (final T3<String, Class<?>, Boolean> originalField : original) {
currExp = composeTwo(new Pair<ExpressionModel, Boolean>(currExp, currExpIsOptional), originalField, separator);
currExpIsOptional = currExpIsOptional != null ? currExpIsOptional && originalField._3 : originalField._3;
}
return currExp;
}
private static ExpressionModel concatTwo(final ExpressionModel first, final String secondPropName, final String separator) {
return expr().concat().expr(first).with().val(separator).with().prop(secondPropName).end().model();
}
private static ExpressionModel composeTwo(final Pair<ExpressionModel, Boolean> first, final T3<String, Class<?>, Boolean> second, final String separator) {
final ExpressionModel firstModel = first.getKey();
final Boolean firstIsOptional = first.getValue();
final String secondPropName = getKeyMemberConcatenationExpression(second._1, second._2);
final boolean secondPropIsOptional = second._3;
if (first.getKey() == null) {
return expr().prop(secondPropName).model();
} else {
if (firstIsOptional) {
if (secondPropIsOptional) {
return expr().caseWhen().expr(firstModel).isNotNull().and().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). //
when().expr(firstModel).isNotNull().and().prop(secondPropName).isNull().then().expr(firstModel). //
when().prop(secondPropName).isNotNull().then().prop(secondPropName). //
otherwise().val(null).endAsStr(256).model();
} else {
return expr().caseWhen().expr(firstModel).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). //
otherwise().prop(secondPropName).endAsStr(256).model();
}
} else {
if (secondPropIsOptional) {
return expr().caseWhen().prop(secondPropName).isNotNull().then().expr(concatTwo(firstModel, secondPropName, separator)). //
otherwise().expr(firstModel).endAsStr(256).model();
} else {
return concatTwo(firstModel, secondPropName, separator);
}
}
}
}
public static ExpressionModel extractExpressionModelFromCalculatedProperty(final Class<? extends AbstractEntity<?>> entityType, final Field calculatedPropfield) throws Exception {
final Calculated calcAnnotation = getAnnotation(calculatedPropfield, Calculated.class);
if (isNotEmpty(calcAnnotation.value())) {
return createExpressionText2ModelConverter(entityType, calcAnnotation).convert().getModel();
} else {
try {
final Field exprField = getFieldByName(entityType, calculatedPropfield.getName() + "_");
exprField.setAccessible(true);
return (ExpressionModel) exprField.get(null);
} catch (final Exception e) {
throw new EqlException(format("Can't extract hard-coded expression model for prop [%s] due to: [%s]", calculatedPropfield.getName(), e.getMessage()));
}
}
}
private static ExpressionText2ModelConverter createExpressionText2ModelConverter(final Class<? extends AbstractEntity<?>> entityType, final Calculated calcAnnotation)
throws Exception {
if (isContextual(calcAnnotation)) {
return new ExpressionText2ModelConverter(getRootType(calcAnnotation), calcAnnotation.contextPath(), calcAnnotation.value());
} else {
return new ExpressionText2ModelConverter(entityType, calcAnnotation.value());
}
}
private static Class<? extends AbstractEntity<?>> getRootType(final Calculated calcAnnotation) throws ClassNotFoundException {
return (Class<? extends AbstractEntity<?>>) ClassLoader.getSystemClassLoader().loadClass(calcAnnotation.rootTypeName());
}
public static <ET extends AbstractEntity<?>> List<EntityResultQueryModel<ET>> produceUnionEntityModels(final Class<ET> entityType) {
final List<EntityResultQueryModel<ET>> result = new ArrayList<>();
if (!isUnionEntityType(entityType)) {
return result;
}
final List<Field> unionProps = unionProperties((Class<? extends AbstractUnionEntity>) entityType);
for (final Field currProp : unionProps) {
result.add(generateModelForUnionEntityProperty(unionProps, currProp).modelAsEntity(entityType));
}
return result;
}
private static <PT extends AbstractEntity<?>> ISubsequentCompletedAndYielded<PT> generateModelForUnionEntityProperty(final List<Field> unionProps, final Field currProp) {
final IFromAlias<PT> startWith = select((Class<PT>) currProp.getType());
final Field firstUnionProp = unionProps.get(0);
final ISubsequentCompletedAndYielded<PT> initialModel = firstUnionProp.equals(currProp) ? startWith.yield().prop(ID).as(firstUnionProp.getName()) : startWith.yield().val(null).as(firstUnionProp.getName());
return unionProps.stream().skip(1).reduce(initialModel, (m, f) -> f.equals(currProp) ? m.yield().prop(ID).as(f.getName()) : m.yield().val(null).as(f.getName()), (m1, m2) -> {throw new UnsupportedOperationException("Combining is not applicable here.");});
}
} | #1293 Simplified logic of building EQL expression for composite key assuming that first key member is not-optinal.
| platform-dao/src/main/java/ua/com/fielden/platform/entity/query/metadata/DomainMetadataUtils.java | #1293 Simplified logic of building EQL expression for composite key assuming that first key member is not-optinal. |
|
Java | mit | f1257982f84c6e226957ae2fbeca9e264dcd1e7c | 0 | CMPUT301F17T14/gitrekt | package com.example.habitrack;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
/**
* Handles all the Activities on the Main Page once Logged in
*/
public class MainActivity extends AppCompatActivity {
// bool var for connection status
Boolean isConnected;
// userID
String currentUserID;
// declare components
Button createTypeButton;
Button historybutton;
Button allButton;
Button logoutButton;
Button socialButton;
private ListView displayNames;
//private ArrayList<HabitType> today = new ArrayList<HabitType>();
private ArrayList<HabitEvent> today = new ArrayList<HabitEvent>();
//private ArrayAdapter<HabitType> adapter;
private ArrayAdapter<HabitEvent> adapter;
// Preliminary Setup
// 1. Get the controllers
HabitTypeController htc = new HabitTypeController(this);
HabitEventController hec = new HabitEventController(this);
// Get Filemanager
FileManager fileManager = new FileManager(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get connection status
isConnected = isOnline();
createTypeButton = (Button) findViewById(R.id.createHabitButton);
allButton = (Button) findViewById(R.id.allButton);
historybutton = (Button) findViewById(R.id.historyButton);
logoutButton = (Button) findViewById(R.id.button10);
socialButton = (Button) findViewById(R.id.button4);
displayNames = (ListView) findViewById(R.id.listView);
final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnectedOrConnecting ()) {
Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show();
} else if (mobile.isConnectedOrConnecting ()) {
Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show();
}
// ------------------
// Checks if app is in a logged in state. If not, goes to login page (SignupActivity)
SharedPreferences loggedInPrefs = getApplicationContext().getSharedPreferences("loggedInStatus", MODE_PRIVATE);
SharedPreferences loggedInUserID = getApplicationContext().getSharedPreferences("userID", MODE_PRIVATE);
final SharedPreferences.Editor loggedInEditor = loggedInPrefs.edit();
boolean isLoggedIn = loggedInPrefs.getBoolean("loggedIn", false);
String liUserID = loggedInUserID.getString("userID", null);
final Intent toLogIn = new Intent(getApplicationContext(), SignupActivity.class);
if(!isLoggedIn) {
startActivity(toLogIn);
}
//if Social button --> to social activity to interact with other participants
socialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent social = new Intent(getApplicationContext(), SocialActivity.class);
startActivity(social);
}
});
//If logoutButton is clicked, change loggedIn to false and go to SignupAcitivty
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loggedInEditor.putBoolean("loggedIn", false);
loggedInEditor.apply();
startActivity(toLogIn);
}
});
// ------------------
currentUserID = liUserID;
// Handles if user pressed CREATE button , redirects to create a new habit type class
createTypeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent newType = new Intent(getApplicationContext(), NewHabitTypeActivity.class);
newType.putExtra("connection", isConnected);
newType.putExtra("currentUserID", currentUserID);
startActivity(newType);
}
});
// Handles if user pressed HISTORY button , redirects to history class
historybutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent newType = new Intent(getApplicationContext(), HabitHistory.class);
//Intent newType = new Intent(getApplicationContext(), HistoryActivity.class);
startActivity(newType);
}
});
// Handles if user pressed ALL button, redirects to all habit types
allButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent viewAll = new Intent(getApplicationContext(), AllHabitTypesActivity.class);
startActivity(viewAll);
}
});
// Handles the pressing of Habits on the Main Activity to launch a new habit event
displayNames.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//intent.putExtra("habitID", today.get(i).getID());
Intent intent;
Integer heID = today.get(i).getHabitEventID();
if(hec.getHabitEventIsEmpty(heID)) {
intent = new Intent(MainActivity.this, NewHabitEventActivity.class);
} else {
intent = new Intent(MainActivity.this, HabitEventDetailsActivity.class);
}
intent.putExtra("habitEventID", heID);
intent.putExtra("habitTypeID", hec.getCorrespondingHabitTypeID(heID));
intent.putExtra("connection", isConnected);
startActivity(intent);
}
});
// --------------------------------TEST COMMANDS BELOW -- MUST BE REMOVED ------------------
// HabitEvent testHE = new HabitEvent(1000, 2000);
// testHE.setUserID("test");
// ElasticSearchController.AddHabitEvent addHabitEvent = new ElasticSearchController.AddHabitEvent();
// addHabitEvent.execute(testHE);
//
// ElasticSearchController.GetHabitEvent getHabitEvent = new ElasticSearchController.GetHabitEvent();
// getHabitEvent.execute("user", "test");
//
// ElasticSearchController.GetUser users = new ElasticSearchController.GetUser();
// users.execute("");
// ArrayList<HabitType> test = htc.getHabitTypeElasticSearch();
//
// NewUser user = new NewUser("testUser3");
// ElasticSearchController.AddNewUser addNewUser = new ElasticSearchController.AddNewUser();
// addNewUser.execute(user);
// NewUser user2 = new NewUser("testUser2");
// addNewUser.execute(user2);
// ElasticSearchController.GetUser getUser = new ElasticSearchController.GetUser();
// getUser.execute();
// try {
// ArrayList<NewUser> allUsers = getUser.get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
// 2. load
// htc.loadHTID();
// hec.loadHEID();
// hec.createNewHabitEvent(1000, isConnected, currentUserID);
// hec.doOfflineTasks();
// --------------------------------TEST COMMANDS ABOVE -- MUST BE REMOVED ------------------
// 1. load HT Metadata
fileManager.load(fileManager.HT_METADATA_MODE);
// 2. calculate all the hts for today, using htmds
htc.getHabitTypesForToday();
// 3. calculate the hes for today, using the previously created htmdfortoday list
hec.generateEventsForToday(isConnected, currentUserID);
// 2. load IDs
htc.loadHTID();
hec.loadHEID();
// 3. Restore all HT and HE if saved
htc.loadFromFile();
hec.loadFromFile();
// 4. Get Recent events and HabitTypes for today
htc.generateHabitsForToday(isConnected, currentUserID);
hec.updateRecentHabitEvents();
}
@Override
protected void onStart() {
super.onStart();
today = hec.getHabitEventsForToday();
adapter = new ArrayAdapter<HabitEvent>(this, R.layout.list_item, today);
displayNames.setAdapter(adapter);
}
@Override
protected void onResume() {
super.onResume();
}
// Code taken from: https://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
| HabiTrack/app/src/main/java/com/example/habitrack/MainActivity.java | package com.example.habitrack;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
/**
* Handles all the Activities on the Main Page once Logged in
*/
public class MainActivity extends AppCompatActivity {
// bool var for connection status
Boolean isConnected;
// userID
String currentUserID;
// declare components
Button createTypeButton;
Button historybutton;
Button allButton;
Button logoutButton;
Button socialButton;
private ListView displayNames;
//private ArrayList<HabitType> today = new ArrayList<HabitType>();
private ArrayList<HabitEvent> today = new ArrayList<HabitEvent>();
//private ArrayAdapter<HabitType> adapter;
private ArrayAdapter<HabitEvent> adapter;
// Preliminary Setup
// 1. Get the controllers
HabitTypeController htc = new HabitTypeController(this);
HabitEventController hec = new HabitEventController(this);
// Get Filemanager
FileManager fileManager = new FileManager(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get connection status
isConnected = isOnline();
createTypeButton = (Button) findViewById(R.id.createHabitButton);
allButton = (Button) findViewById(R.id.allButton);
historybutton = (Button) findViewById(R.id.historyButton);
logoutButton = (Button) findViewById(R.id.button10);
socialButton = (Button) findViewById(R.id.button4);
displayNames = (ListView) findViewById(R.id.listView);
final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnectedOrConnecting ()) {
Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show();
} else if (mobile.isConnectedOrConnecting ()) {
Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show();
}
// ------------------
// Checks if app is in a logged in state. If not, goes to login page (SignupActivity)
SharedPreferences loggedInPrefs = getApplicationContext().getSharedPreferences("loggedInStatus", MODE_PRIVATE);
SharedPreferences loggedInUserID = getApplicationContext().getSharedPreferences("userID", MODE_PRIVATE);
final SharedPreferences.Editor loggedInEditor = loggedInPrefs.edit();
boolean isLoggedIn = loggedInPrefs.getBoolean("loggedIn", false);
String liUserID = loggedInUserID.getString("userID", null);
final Intent toLogIn = new Intent(getApplicationContext(), SignupActivity.class);
if(!isLoggedIn) {
startActivity(toLogIn);
}
//if Social button --> to social activity to interact with other participants
socialButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent social = new Intent(getApplicationContext(), SocialActivity.class);
startActivity(social);
}
});
//If logoutButton is clicked, change loggedIn to false and go to SignupAcitivty
logoutButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loggedInEditor.putBoolean("loggedIn", false);
loggedInEditor.apply();
startActivity(toLogIn);
}
});
// ------------------
currentUserID = liUserID;
// Handles if user pressed CREATE button , redirects to create a new habit type class
createTypeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent newType = new Intent(getApplicationContext(), NewHabitTypeActivity.class);
newType.putExtra("connection", isConnected);
newType.putExtra("currentUserID", currentUserID);
startActivity(newType);
}
});
// Handles if user pressed HISTORY button , redirects to history class
historybutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Intent newType = new Intent(getApplicationContext(), HabitHistory.class);
//Intent newType = new Intent(getApplicationContext(), HistoryActivity.class);
startActivity(newType);
}
});
// Handles if user pressed ALL button, redirects to all habit types
allButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent viewAll = new Intent(getApplicationContext(), AllHabitTypesActivity.class);
startActivity(viewAll);
}
});
// Handles the pressing of Habits on the Main Activity to launch a new habit event
displayNames.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//intent.putExtra("habitID", today.get(i).getID());
Intent intent;
Integer heID = today.get(i).getHabitEventID();
if(hec.getHabitEventIsEmpty(heID)) {
intent = new Intent(MainActivity.this, NewHabitEventActivity.class);
} else {
intent = new Intent(MainActivity.this, HabitEventDetailsActivity.class);
}
intent.putExtra("habitEventID", heID);
intent.putExtra("habitTypeID", hec.getCorrespondingHabitTypeID(heID));
intent.putExtra("connection", isConnected);
startActivity(intent);
}
});
// --------------------------------TEST COMMANDS BELOW -- MUST BE REMOVED ------------------
// HabitEvent testHE = new HabitEvent(1000, 2000);
// testHE.setUserID("test");
// ElasticSearchController.AddHabitEvent addHabitEvent = new ElasticSearchController.AddHabitEvent();
// addHabitEvent.execute(testHE);
//
// ElasticSearchController.GetHabitEvent getHabitEvent = new ElasticSearchController.GetHabitEvent();
// getHabitEvent.execute("user", "test");
//
// ElasticSearchController.GetUser users = new ElasticSearchController.GetUser();
// users.execute("");
// ArrayList<HabitType> test = htc.getHabitTypeElasticSearch();
//
// NewUser user = new NewUser("testUser3");
// ElasticSearchController.AddNewUser addNewUser = new ElasticSearchController.AddNewUser();
// addNewUser.execute(user);
// NewUser user2 = new NewUser("testUser2");
// addNewUser.execute(user2);
// ElasticSearchController.GetUser getUser = new ElasticSearchController.GetUser();
// getUser.execute();
// try {
// ArrayList<NewUser> allUsers = getUser.get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
// 2. load
// htc.loadHTID();
// hec.loadHEID();
// hec.createNewHabitEvent(1000, isConnected, currentUserID);
// hec.doOfflineTasks();
// --------------------------------TEST COMMANDS ABOVE -- MUST BE REMOVED ------------------
// load HT Metadata
fileManager.load(fileManager.HT_METADATA_MODE);
// 2. load
htc.loadHTID();
hec.loadHEID();
// 3. Restore all HT and HE if saved
htc.loadFromFile();
hec.loadFromFile();
// 4. Get Recent events and HabitTypes for today
htc.generateHabitsForToday(isConnected, currentUserID);
hec.updateRecentHabitEvents();
}
@Override
protected void onStart() {
super.onStart();
today = hec.getHabitEventsForToday();
adapter = new ArrayAdapter<HabitEvent>(this, R.layout.list_item, today);
displayNames.setAdapter(adapter);
}
@Override
protected void onResume() {
super.onResume();
}
// Code taken from: https://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-times-out
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
}
| add new flow for starting the app
| HabiTrack/app/src/main/java/com/example/habitrack/MainActivity.java | add new flow for starting the app |
|
Java | mit | 9f600e9f88883986fa95ae32785cea42abc588d1 | 0 | domisum/AuxiliumLib | package de.domisum.lib.auxilium.data.container.file;
import de.domisum.lib.auxilium.util.java.annotations.APIUsage;
import lombok.Getter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
@APIUsage
public class PropertiesFileWrapper
{
private File file;
@Getter private Properties properties;
// INIT
@APIUsage public PropertiesFileWrapper(File file)
{
this.file = file;
loadFromFile();
}
// LOADING
private void loadFromFile()
{
this.properties = new Properties();
try(InputStream inputStream = new FileInputStream(this.file))
{
this.properties.load(inputStream);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
// SAVING
@APIUsage public void save(String comment)
{
try(OutputStream outputStream = new FileOutputStream(this.file))
{
this.properties.store(outputStream, comment);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
// GETTERS
@APIUsage public String get(String key)
{
if(!this.properties.containsKey(key))
throw new IllegalArgumentException("The properties file does not contain the key '"+key+"'");
return this.properties.getProperty(key);
}
// SETTERS
@APIUsage public void set(String key, String value)
{
this.properties.setProperty(key, value);
}
}
| src/main/java/de/domisum/lib/auxilium/data/container/file/PropertiesFileWrapper.java | package de.domisum.lib.auxilium.data.container.file;
import de.domisum.lib.auxilium.util.java.annotations.APIUsage;
import lombok.Getter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
@APIUsage
public class PropertiesFileWrapper
{
// PROPERTIES
private String filePath;
// REFERENCES
@Getter private Properties properties;
/*
// INITIALIZATION
*/
@APIUsage
public PropertiesFileWrapper(String filePath)
{
this.filePath = filePath;
loadFromFile();
}
/*
// LOADING
*/
private void loadFromFile()
{
this.properties = new Properties();
try(InputStream inputStream = new FileInputStream(this.filePath))
{
this.properties.load(inputStream);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
/*
// SAVING
*/
@APIUsage public void saveToFile(File file, String comment)
{
try(OutputStream outputStream = new FileOutputStream(file))
{
this.properties.store(outputStream, comment);
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
/*
// GETTERS
*/
@APIUsage public String get(String key)
{
if(!this.properties.containsKey(key))
throw new IllegalArgumentException("The properties file '"+this.filePath+"' does not contain the key '"+key+"'");
return this.properties.getProperty(key);
}
/*
// SETTERS
*/
@APIUsage public void set(String key, String value)
{
this.properties.setProperty(key, value);
}
}
| Improved PropertiesFileWrapper
| src/main/java/de/domisum/lib/auxilium/data/container/file/PropertiesFileWrapper.java | Improved PropertiesFileWrapper |
|
Java | mit | cee18d278a9923d72cb966f71c6f71e7369da3a3 | 0 | Yelp/yelp-android | package com.yelp.clientlib.entities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import java.io.Serializable;
import java.util.ArrayList;
@AutoValue
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonDeserialize(builder = AutoValue_SearchResponse.Builder.class)
public abstract class SearchResponse implements Serializable {
public abstract ArrayList<Business> businesses();
public abstract Region region();
public abstract Integer total();
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public abstract static class Builder {
public abstract Builder businesses(ArrayList<Business> businesses);
public abstract Builder region(Region region);
public abstract Builder total(Integer total);
public abstract SearchResponse build();
}
public static Builder builder() {
return new AutoValue_SearchResponse.Builder();
}
}
| src/main/java/com/yelp/clientlib/entities/SearchResponse.java | package com.yelp.clientlib.entities;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;
import java.io.Serializable;
import java.util.ArrayList;
@AutoValue
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonDeserialize(builder = AutoValue_SearchResponse.Builder.class)
public abstract class SearchResponse implements Serializable {
public abstract ArrayList<Business> businesses();
public abstract Region region();
public abstract Integer total();
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
public abstract static class Builder {
public abstract Builder businesses(ArrayList<Business> businesses);
public abstract Builder region(Region region);
public abstract Builder total(Integer total);
public abstract SearchResponse build();
}
public static Builder builder() {
return new AutoValue_SearchResponse.Builder();
}
} | Add a newline to SearchResponse.java
| src/main/java/com/yelp/clientlib/entities/SearchResponse.java | Add a newline to SearchResponse.java |
|
Java | mit | 8740c2d894b7ab0ccf186b48490291f2b2c0632c | 0 | gfneto/Hive2Hive,Hive2Hive/Hive2Hive | package org.hive2hive.core.test.tomp2p;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import net.tomp2p.connection.ChannelClientConfiguration;
import net.tomp2p.connection.ChannelServerConficuration;
import net.tomp2p.connection.DSASignatureFactory;
import net.tomp2p.connection.SignatureFactory;
import net.tomp2p.futures.FutureGet;
import net.tomp2p.futures.FuturePut;
import net.tomp2p.futures.FutureRemove;
import net.tomp2p.message.SignatureCodec;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerMaker;
import net.tomp2p.p2p.RSASignatureCodec;
import net.tomp2p.p2p.RSASignatureFactory;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number640;
import net.tomp2p.storage.Data;
import org.hive2hive.core.test.H2HJUnitTest;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* A test which test the content protection mechanisms of <code>TomP2P</code>. Tests should be completely
* independent of <code>Hive2Hive</code>.
*
* @author Seppi
*/
public class ContentProtectionTest extends H2HJUnitTest {
private final SignatureFactory signatureFactory = new DSASignatureFactory();
@BeforeClass
public static void initTest() throws Exception {
testClass = ContentProtectionTest.class;
beforeClass();
}
/**
* Tests if a protected entry can be overwritten without the according key.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws InvalidKeyException
*/
@Test
public void testPut1() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair, signatureFactory);
// initial put with protection key
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).keyPair(keyPair).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// try a put without a protection key (through peer 2)
Data data2 = new Data("data2");
FuturePut futurePut2 = p2.put(lKey).setData(cKey, data2).setDomainKey(dKey).start();
futurePut2.awaitUninterruptibly();
assertFalse(futurePut2.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
retData = futureGet2a.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
retData = futureGet2b.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// try a put without a protection key (through peer 1)
Data data3 = new Data("data3");
FuturePut futurePut3 = p2.put(lKey).setData(cKey, data3).setDomainKey(dKey).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
FutureGet futureGet3a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
retData = futureGet3a.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet3b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
retData = futureGet3b.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// now we put a signed data object
String newTestData = "new data";
data = new Data(newTestData).setProtectedEntry().sign(keyPair, signatureFactory);
FuturePut futurePut4 = p1.put(lKey).setData(cKey, data).keyPair(keyPair).setDomainKey(dKey).start();
futurePut4.awaitUninterruptibly();
Assert.assertTrue(futurePut4.isSuccess());
FutureGet futureGet4a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet4a.awaitUninterruptibly();
assertTrue(futureGet4a.isSuccess());
retData = futureGet4a.getData();
// should have been modified
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet4b.awaitUninterruptibly();
assertTrue(futureGet4b.isSuccess());
retData = futureGet4b.getData();
// should have been modified
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
/**
* Put of a protected entry using version keys.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void testPut2() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
Number160 vKey = Number160.createHash("version");
Number160 bKey = Number160.createHash("based on");
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair, signatureFactory);
data.ttlSeconds(10000).basedOn(bKey);
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).setVersionKey(vKey)
.keyPair(keyPair).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).setVersionKey(vKey)
.start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).setVersionKey(vKey)
.start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
/**
* Test overwriting a protected entry with a wrong key pair.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void testPut3() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// initial put using key pair 2
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// put with wrong key
String testData2 = "data2";
Data data2 = new Data(testData2).setProtectedEntry().sign(keyPair2, signatureFactory);
FuturePut futurePut2 = p2.put(lKey).setData(cKey, data2).setDomainKey(dKey).keyPair(keyPair2).start();
futurePut2.awaitUninterruptibly();
assertFalse(futurePut2.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
retData = futureGet2a.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
retData = futureGet2b.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemove1() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4836).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(keyPair1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// try to remove without key pair -------------------------------------------------------
FutureRemove futureRemove1a = p1.remove(lKey).contentKey(cKey).start();
futureRemove1a.awaitUninterruptibly();
assertFalse(futureRemove1a.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2a.getData().object());
FutureRemove futureRemove1b = p2.remove(lKey).contentKey(cKey).start();
futureRemove1b.awaitUninterruptibly();
assertFalse(futureRemove1b.isSuccess());
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2b.getData().object());
// try to remove with wrong key pair ---------------------------------------------------
FutureRemove futureRemove2a = p1.remove(lKey).contentKey(cKey).keyPair(keyPair2).start();
futureRemove2a.awaitUninterruptibly();
assertFalse(futureRemove2a.isSuccess());
FutureGet futureGet3a = p1.get(lKey).setContentKey(cKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3a.getData().object());
FutureRemove futureRemove2b = p2.remove(lKey).contentKey(cKey).keyPair(keyPair2).start();
futureRemove2b.awaitUninterruptibly();
assertFalse(futureRemove2b.isSuccess());
FutureGet futureGet3b = p2.get(lKey).setContentKey(cKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3b.getData().object());
// remove with correct key pair ---------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
assertFalse(futureGet4a.isSuccess());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
assertFalse(futureGet4b.isSuccess());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemove2() throws NoSuchAlgorithmException, IOException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// remove with key pair ------------------------------------------------------------------
FutureRemove futureRemove3 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair).start();
futureRemove3.awaitUninterruptibly();
assertTrue(futureRemove3.isSuccess());
FutureGet futureGet3 = p2.get(lKey).setContentKey(cKey).start();
futureGet3.awaitUninterruptibly();
assertFalse(futureGet3.isSuccess());
// should have been removed
assertNull(futureGet3.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemoveFromTo1() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair key1 = gen.generateKeyPair();
KeyPair key2 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String domainKey = "domain";
Number160 dKey = Number160.createHash(domainKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(key1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(key1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// try to remove without key pair using from/to -----------------------------------------
FutureRemove futureRemove1a = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove1a.awaitUninterruptibly();
assertFalse(futureRemove1a.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2a.getData().object());
FutureRemove futureRemove1b = p2.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove1b.awaitUninterruptibly();
assertFalse(futureRemove1b.isSuccess());
FutureGet futureGet2b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2b.getData().object());
// remove with wrong key pair -----------------------------------------------------------
FutureRemove futureRemove2a = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key2).start();
futureRemove2a.awaitUninterruptibly();
assertFalse(futureRemove2a.isSuccess());
FutureGet futureGet3a = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3a.getData().object());
FutureRemove futureRemove2b = p2.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key2).start();
futureRemove2b.awaitUninterruptibly();
assertFalse(futureRemove2b.isSuccess());
FutureGet futureGet3b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3b.getData().object());
// remove with correct key pair -----------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4a.isFailed());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4b.isFailed());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemoveFromTo2() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair key1 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String domainKey = "domain";
Number160 dKey = Number160.createHash(domainKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(key1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(key1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// remove with correct key pair -----------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4a.isFailed());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4b.isFailed());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testChangeProtectionKeyWithVersions() throws NoSuchAlgorithmException, IOException,
ClassNotFoundException, InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// put version 1 with protection keys 1
Number160 vKey1 = Number160.createHash("version1");
String testDataV1 = "data1v1";
Data data = new Data(testDataV1).setProtectedEntry().sign(keyPair1, signatureFactory);
data.basedOn(Number160.ZERO);
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1)
.setVersionKey(vKey1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
// put version 2 with protection keys 1
Number160 vKey2 = Number160.createHash("version2");
String testDataV2 = "data1v2";
data = new Data(testDataV2).setProtectedEntry().sign(keyPair1, signatureFactory);
data.basedOn(vKey1);
FuturePut futurePut2 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1)
.setVersionKey(vKey2).start();
futurePut2.awaitUninterruptibly();
assertTrue(futurePut2.isSuccess());
// // overwrite version 2 with new protection keys 2
// data = new Data("data1v2Overwrite").setProtectedEntry().sign(keyPair2, signatureFactory);
// data.basedOn(vKey1);
// FuturePut futurePut2Overwrite = p1.put(lKey).setDomainKey(dKey).setData(cKey,
// data).keyPair(keyPair1)
// .setVersionKey(vKey2).start();
// futurePut2Overwrite.awaitUninterruptibly();
// assertFalse(futurePut2Overwrite.isSuccess());
// put version 3 with (wrong) message signature (expected to fail)
Number160 vKey3 = Number160.createHash("version3");
data = new Data("data1v3").setProtectedEntry().sign(keyPair1, signatureFactory);
data.basedOn(vKey2);
FuturePut futurePut3 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2)
.setVersionKey(vKey3).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
// sign the data with the new key pair, get only the meta data
data = new Data(testDataV2).setProtectedEntry().sign(keyPair2, signatureFactory).duplicateMeta();
data.basedOn(vKey1);
// change protection keys, use the old protection key to sign the message
FuturePut futurePut4 = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, data)
.setVersionKey(vKey2).keyPair(keyPair1).start();
futurePut4.awaitUninterruptibly();
assertTrue(futurePut4.isSuccess());
// verify the protection keys of version 1
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey1).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV1, (String) retData.object());
// the protection key should be protection keys 1
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// verify the protection keys of version 2
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey2).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV2, (String) retData.object());
// the protection key should be protection keys 2
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// add another version with the new protection key
Number160 vKey4 = Number160.createHash("version4");
String testDataV4 = "data1v4";
data = new Data(testDataV4).setProtectedEntry().sign(keyPair2, signatureFactory);
data.basedOn(vKey2);
FuturePut futurePut5 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2)
.setVersionKey(vKey4).start();
futurePut5.awaitUninterruptibly();
assertTrue(futurePut5.isSuccess());
// verify the protection keys of version 4
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey4).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV4, (String) retData.object());
// the protection key should be protection keys 2
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
// put version 1 with protection keys 1
// change protection keys of version 1 to protection keys 2
// overwrite version 1 with protection keys 2
/**
* This test checks the changing of the content protection key of a signed entry in the network.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws InvalidKeyException
* @throws SignatureException
* @throws ClassNotFoundException
*/
@Test
public void testChangeProtectionKey() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// initial put
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
// verify initial put on node 1
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// verify initial put on node 2
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// sign the data with the new key pair, get only the meta data
data = new Data(testData).setProtectedEntry().sign(keyPair2, signatureFactory).duplicateMeta();
// use the old protection key to sign the message
FuturePut futurePut2 = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, data)
.keyPair(keyPair1).start();
futurePut2.awaitUninterruptibly();
assertTrue(futurePut2.isSuccess());
// verify protection keys change on node 1
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// verify protection keys change on node 2
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// should be not possible to modify
data = new Data().setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut3 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// modify with new protection key
String newTestData = "new data";
data = new Data(newTestData).setProtectedEntry().sign(keyPair2, signatureFactory);
FuturePut futurePut4 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2).start();
futurePut4.awaitUninterruptibly();
assertTrue(futurePut4.isSuccess());
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testChangeProtectionKeyWithReusedSignature() throws NoSuchAlgorithmException, IOException,
ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
// create custom RSA factories
SignatureFactory factory = new RSASignatureFactory();
SignatureCodec codec = new RSASignatureCodec();
// replace default signature factories
ChannelClientConfiguration clientConfig = PeerMaker.createDefaultChannelClientConfiguration();
clientConfig.signatureFactory(factory);
ChannelServerConficuration serverConfig = PeerMaker.createDefaultChannelServerConfiguration();
serverConfig.signatureFactory(factory);
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).channelClientConfiguration(clientConfig)
.channelServerConfiguration(serverConfig).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).channelClientConfiguration(clientConfig)
.channelServerConfiguration(serverConfig).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPairOld = gen.generateKeyPair();
KeyPair keyPairNew = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
Number160 vKey = Number160.createHash("version");
Number160 bKey = Number160.ZERO;
int ttl = 10;
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPairOld, factory);
data.ttlSeconds(ttl).basedOn(bKey);
// initial put of some test data
FuturePut futurePut = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).setVersionKey(vKey)
.keyPair(keyPairOld).start();
futurePut.awaitUninterruptibly();
Assert.assertTrue(futurePut.isSuccess());
// create signature with old key pair having the data object
byte[] signature1 = factory.sign(keyPairOld.getPrivate(), data.buffer()).encode();
// decrypt signature to get hash of the object
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, keyPairOld.getPublic());
byte[] hash = rsa.doFinal(signature1);
// encrypt hash with new key pair to get the new signature (without having the data object)
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, keyPairNew.getPrivate());
byte[] signatureNew = rsa.doFinal(hash);
// verify old content protection keys
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey).start()
.awaitUninterruptibly().getData();
Assert.assertTrue(retData.verify(keyPairOld.getPublic(), factory));
// create a dummy data object for changing the content protection key through a put meta
Data dummyData = new Data();
dummyData.basedOn(bKey).ttlSeconds(ttl);
// assign the reused hash from signature (don't forget to set the signed flag)
dummyData.signature(codec.decode(signatureNew)).signed(true).duplicateMeta();
// change content protection key through a put meta
FuturePut futurePutMeta = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, dummyData)
.setVersionKey(vKey).keyPair(keyPairOld).start();
futurePutMeta.awaitUninterruptibly();
Assert.assertTrue(futurePutMeta.isSuccess());
// verify new content protection keys
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey).start()
.awaitUninterruptibly().getData();
Assert.assertTrue(retData.verify(keyPairNew.getPublic(), factory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testChangeProtectionKey2() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
KeyPair keyPair3 = gen.generateKeyPair();
Number160 lKey = Number160.createHash(2); // same like node 2
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// initial put with protection key 1
Data data1 = new Data("data1").setProtectedEntry();
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data1).setDomainKey(dKey).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
// verify initial put
assertEquals("data1", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// overwrite with protection key 1
Data data2 = new Data("data2").setProtectedEntry();
FuturePut futurePut2 = p1.put(lKey).setData(cKey, data2).setDomainKey(dKey).keyPair(keyPair1).start();
futurePut2.awaitUninterruptibly();
assertTrue(futurePut2.isSuccess());
// verify overwrite
assertEquals("data2", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// try to overwrite without protection key (expected to fail)
Data data2A = new Data("data2A").setProtectedEntry();
FuturePut futurePut2A = p1.put(lKey).setData(cKey, data2A).setDomainKey(dKey).start();
futurePut2A.awaitUninterruptibly();
assertFalse(futurePut2A.isSuccess());
// verify that nothing changed
assertEquals("data2", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// try to overwrite with wrong protection key 2 (expected to fail)
Data data2B = new Data("data2B").setProtectedEntry();
FuturePut futurePut2B = p1.put(lKey).setData(cKey, data2B).setDomainKey(dKey).keyPair(keyPair2)
.start();
futurePut2B.awaitUninterruptibly();
assertFalse(futurePut2A.isSuccess());
// verify that nothing changed
assertEquals("data2", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// change protection key, create meta data
Data data3 = new Data().setProtectedEntry().publicKey(keyPair2.getPublic()).duplicateMeta();
// change protection keys, use the old protection key 1 to sign the message
FuturePut futurePut3 = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, data3)
.keyPair(keyPair1).start();
futurePut3.awaitUninterruptibly();
assertTrue(futurePut3.isSuccess());
// overwrite with protection key 2
Data data4 = new Data("data4").setProtectedEntry();
FuturePut futurePut4 = p1.put(lKey).setData(cKey, data4).setDomainKey(dKey).keyPair(keyPair2).start();
futurePut4.awaitUninterruptibly();
assertTrue(futurePut4.isSuccess());
// verify overwrite
assertEquals("data4", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// try to overwrite without protection key (expected to fail)
Data data5A = new Data("data5A").setProtectedEntry();
FuturePut futurePut5A = p1.put(lKey).setData(cKey, data5A).setDomainKey(dKey).start();
futurePut5A.awaitUninterruptibly();
assertFalse(futurePut5A.isSuccess());
// verify that nothing changed
assertEquals("data4", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
// try to overwrite with wrong protection key 3 (expected to fail)
Data data5B = new Data("data5B").setProtectedEntry();
FuturePut futurePut5B = p1.put(lKey).setData(cKey, data5B).setDomainKey(dKey).keyPair(keyPair3)
.start();
futurePut5B.awaitUninterruptibly();
assertFalse(futurePut5A.isSuccess());
// verify that nothing changed
assertEquals("data4", (String) p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start()
.awaitUninterruptibly().getData().object());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@AfterClass
public static void cleanAfterClass() {
afterClass();
}
}
| org.hive2hive.core.test/src/org/hive2hive/core/test/tomp2p/ContentProtectionTest.java | package org.hive2hive.core.test.tomp2p;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import net.tomp2p.connection.ChannelClientConfiguration;
import net.tomp2p.connection.ChannelServerConficuration;
import net.tomp2p.connection.DSASignatureFactory;
import net.tomp2p.connection.SignatureFactory;
import net.tomp2p.futures.FutureGet;
import net.tomp2p.futures.FuturePut;
import net.tomp2p.futures.FutureRemove;
import net.tomp2p.message.SignatureCodec;
import net.tomp2p.p2p.Peer;
import net.tomp2p.p2p.PeerMaker;
import net.tomp2p.p2p.RSASignatureCodec;
import net.tomp2p.p2p.RSASignatureFactory;
import net.tomp2p.peers.Number160;
import net.tomp2p.peers.Number640;
import net.tomp2p.storage.Data;
import org.hive2hive.core.test.H2HJUnitTest;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* A test which test the content protection mechanisms of <code>TomP2P</code>. Tests should be completely
* independent of <code>Hive2Hive</code>.
*
* @author Seppi
*/
public class ContentProtectionTest extends H2HJUnitTest {
private final SignatureFactory signatureFactory = new DSASignatureFactory();
@BeforeClass
public static void initTest() throws Exception {
testClass = ContentProtectionTest.class;
beforeClass();
}
/**
* Tests if a protected entry can be overwritten without the according key.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws InvalidKeyException
*/
@Test
public void testPut1() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair, signatureFactory);
// initial put with protection key
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).keyPair(keyPair).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// try a put without a protection key (through peer 2)
Data data2 = new Data("data2");
FuturePut futurePut2 = p2.put(lKey).setData(cKey, data2).setDomainKey(dKey).start();
futurePut2.awaitUninterruptibly();
assertFalse(futurePut2.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
retData = futureGet2a.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
retData = futureGet2b.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// try a put without a protection key (through peer 1)
Data data3 = new Data("data3");
FuturePut futurePut3 = p2.put(lKey).setData(cKey, data3).setDomainKey(dKey).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
FutureGet futureGet3a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
retData = futureGet3a.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet3b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
retData = futureGet3b.getData();
// should have been not modified
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
// now we put a signed data object
String newTestData = "new data";
data = new Data(newTestData).setProtectedEntry().sign(keyPair, signatureFactory);
FuturePut futurePut4 = p1.put(lKey).setData(cKey, data).keyPair(keyPair).setDomainKey(dKey).start();
futurePut4.awaitUninterruptibly();
Assert.assertTrue(futurePut4.isSuccess());
FutureGet futureGet4a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet4a.awaitUninterruptibly();
assertTrue(futureGet4a.isSuccess());
retData = futureGet4a.getData();
// should have been modified
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet4b.awaitUninterruptibly();
assertTrue(futureGet4b.isSuccess());
retData = futureGet4b.getData();
// should have been modified
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
/**
* Put of a protected entry using version keys.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void testPut2() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
Number160 vKey = Number160.createHash("version");
Number160 bKey = Number160.createHash("based on");
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair, signatureFactory);
data.ttlSeconds(10000).basedOn(bKey);
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).setVersionKey(vKey)
.keyPair(keyPair).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).setVersionKey(vKey)
.start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).setVersionKey(vKey)
.start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
/**
* Test overwriting a protected entry with a wrong key pair.
*
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
@Test
public void testPut3() throws IOException, ClassNotFoundException, NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// initial put using key pair 2
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).setDomainKey(dKey).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
Data retData = futureGet1a.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
retData = futureGet1b.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// put with wrong key
String testData2 = "data2";
Data data2 = new Data(testData2).setProtectedEntry().sign(keyPair2, signatureFactory);
FuturePut futurePut2 = p2.put(lKey).setData(cKey, data2).setDomainKey(dKey).keyPair(keyPair2).start();
futurePut2.awaitUninterruptibly();
assertFalse(futurePut2.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
retData = futureGet2a.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).setDomainKey(dKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
retData = futureGet2b.getData();
assertEquals(testData1, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemove1() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4836).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(keyPair1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// try to remove without key pair -------------------------------------------------------
FutureRemove futureRemove1a = p1.remove(lKey).contentKey(cKey).start();
futureRemove1a.awaitUninterruptibly();
assertFalse(futureRemove1a.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setContentKey(cKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2a.getData().object());
FutureRemove futureRemove1b = p2.remove(lKey).contentKey(cKey).start();
futureRemove1b.awaitUninterruptibly();
assertFalse(futureRemove1b.isSuccess());
FutureGet futureGet2b = p2.get(lKey).setContentKey(cKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2b.getData().object());
// try to remove with wrong key pair ---------------------------------------------------
FutureRemove futureRemove2a = p1.remove(lKey).contentKey(cKey).keyPair(keyPair2).start();
futureRemove2a.awaitUninterruptibly();
assertFalse(futureRemove2a.isSuccess());
FutureGet futureGet3a = p1.get(lKey).setContentKey(cKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3a.getData().object());
FutureRemove futureRemove2b = p2.remove(lKey).contentKey(cKey).keyPair(keyPair2).start();
futureRemove2b.awaitUninterruptibly();
assertFalse(futureRemove2b.isSuccess());
FutureGet futureGet3b = p2.get(lKey).setContentKey(cKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3b.getData().object());
// remove with correct key pair ---------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
assertFalse(futureGet4a.isSuccess());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
assertFalse(futureGet4b.isSuccess());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemove2() throws NoSuchAlgorithmException, IOException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setData(cKey, data).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// remove with key pair ------------------------------------------------------------------
FutureRemove futureRemove3 = p1.remove(lKey).contentKey(cKey).keyPair(keyPair).start();
futureRemove3.awaitUninterruptibly();
assertTrue(futureRemove3.isSuccess());
FutureGet futureGet3 = p2.get(lKey).setContentKey(cKey).start();
futureGet3.awaitUninterruptibly();
assertFalse(futureGet3.isSuccess());
// should have been removed
assertNull(futureGet3.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemoveFromTo1() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair key1 = gen.generateKeyPair();
KeyPair key2 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String domainKey = "domain";
Number160 dKey = Number160.createHash(domainKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(key1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(key1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// try to remove without key pair using from/to -----------------------------------------
FutureRemove futureRemove1a = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove1a.awaitUninterruptibly();
assertFalse(futureRemove1a.isSuccess());
FutureGet futureGet2a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet2a.awaitUninterruptibly();
assertTrue(futureGet2a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2a.getData().object());
FutureRemove futureRemove1b = p2.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).start();
futureRemove1b.awaitUninterruptibly();
assertFalse(futureRemove1b.isSuccess());
FutureGet futureGet2b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet2b.awaitUninterruptibly();
assertTrue(futureGet2b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet2b.getData().object());
// remove with wrong key pair -----------------------------------------------------------
FutureRemove futureRemove2a = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key2).start();
futureRemove2a.awaitUninterruptibly();
assertFalse(futureRemove2a.isSuccess());
FutureGet futureGet3a = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet3a.awaitUninterruptibly();
assertTrue(futureGet3a.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3a.getData().object());
FutureRemove futureRemove2b = p2.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key2).start();
futureRemove2b.awaitUninterruptibly();
assertFalse(futureRemove2b.isSuccess());
FutureGet futureGet3b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet3b.awaitUninterruptibly();
assertTrue(futureGet3b.isSuccess());
// should have been not modified
assertEquals(testData1, (String) futureGet3b.getData().object());
// remove with correct key pair -----------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4a.isFailed());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4b.isFailed());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testRemoveFromTo2() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4838).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair key1 = gen.generateKeyPair();
String locationKey = "location";
Number160 lKey = Number160.createHash(locationKey);
String domainKey = "domain";
Number160 dKey = Number160.createHash(domainKey);
String contentKey = "content";
Number160 cKey = Number160.createHash(contentKey);
String testData1 = "data1";
Data data = new Data(testData1).setProtectedEntry().sign(key1, signatureFactory);
// put trough peer 1 with key pair -------------------------------------------------------
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(key1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
FutureGet futureGet1a = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1a.awaitUninterruptibly();
assertTrue(futureGet1a.isSuccess());
assertEquals(testData1, (String) futureGet1a.getData().object());
FutureGet futureGet1b = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start();
futureGet1b.awaitUninterruptibly();
assertTrue(futureGet1b.isSuccess());
assertEquals(testData1, (String) futureGet1b.getData().object());
// remove with correct key pair -----------------------------------------------------------
FutureRemove futureRemove4 = p1.remove(lKey).from(new Number640(lKey, dKey, cKey, Number160.ZERO))
.to(new Number640(lKey, dKey, cKey, Number160.MAX_VALUE)).keyPair(key1).start();
futureRemove4.awaitUninterruptibly();
assertTrue(futureRemove4.isSuccess());
FutureGet futureGet4a = p2.get(lKey).setContentKey(cKey).start();
futureGet4a.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4a.isFailed());
// should have been removed
assertNull(futureGet4a.getData());
FutureGet futureGet4b = p2.get(lKey).setContentKey(cKey).start();
futureGet4b.awaitUninterruptibly();
// we did not find the data
Assert.assertTrue(futureGet4b.isFailed());
// should have been removed
assertNull(futureGet4b.getData());
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testChangeProtectionKeyWithVersions() throws NoSuchAlgorithmException, IOException,
ClassNotFoundException, InvalidKeyException, SignatureException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// put the first version of the content with key pair 1
Number160 vKey1 = Number160.createHash("version1");
String testDataV1 = "data1v1";
Data data = new Data(testDataV1).setProtectedEntry().sign(keyPair1, signatureFactory);
data.basedOn(Number160.ZERO);
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1)
.setVersionKey(vKey1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
// add another version with the correct key pair 1
Number160 vKey2 = Number160.createHash("version2");
String testDataV2 = "data1v2";
data = new Data(testDataV2).setProtectedEntry().sign(keyPair1, signatureFactory);
data.basedOn(vKey1);
FuturePut futurePut2 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1)
.setVersionKey(vKey2).start();
futurePut2.awaitUninterruptibly();
assertTrue(futurePut2.isSuccess());
// put new version with other key pair 2 (expected to fail)
Number160 vKey3 = Number160.createHash("version3");
data = new Data("data1v3").setProtectedEntry().sign(keyPair2, signatureFactory);
data.basedOn(vKey2);
FuturePut futurePut3 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2)
.setVersionKey(vKey3).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
// sign the data with the new key pair, get only the meta data
data = new Data(testDataV2).setProtectedEntry().sign(keyPair2, signatureFactory).duplicateMeta();
data.basedOn(vKey1);
// use the old protection key to sign the message
FuturePut futurePut4 = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, data)
.setVersionKey(vKey2).keyPair(keyPair1).start();
futurePut4.awaitUninterruptibly();
assertTrue(futurePut4.isSuccess());
// verify the protection keys
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey1).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV1, (String) retData.object());
// the protection key should be key pair 1
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey2).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV2, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// add another version with the new protection key
Number160 vKey4 = Number160.createHash("version4");
String testDataV4 = "data1v4";
data = new Data(testDataV4).setProtectedEntry().sign(keyPair2, signatureFactory);
data.basedOn(vKey2);
FuturePut futurePut5 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2)
.setVersionKey(vKey4).start();
futurePut5.awaitUninterruptibly();
assertTrue(futurePut5.isSuccess());
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey4).start()
.awaitUninterruptibly().getData();
assertEquals(testDataV4, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
/**
* This test checks the changing of the content protection key of a signed entry in the network.
*
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws InvalidKeyException
* @throws SignatureException
* @throws ClassNotFoundException
*/
@Test
public void testChangeProtectionKey() throws NoSuchAlgorithmException, IOException, InvalidKeyException,
SignatureException, ClassNotFoundException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPair1 = gen.generateKeyPair();
KeyPair keyPair2 = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
// initial put
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut1 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut1.awaitUninterruptibly();
assertTrue(futurePut1.isSuccess());
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair1.getPublic(), signatureFactory));
// sign the data with the new key pair, get only the meta data
data = new Data(testData).setProtectedEntry().sign(keyPair2, signatureFactory).duplicateMeta();
// use the old protection key to sign the message
FuturePut futurePut2 = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, data)
.keyPair(keyPair1).start();
futurePut2.awaitUninterruptibly();
assertTrue(futurePut2.isSuccess());
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// should be not possible to modify
data = new Data().setProtectedEntry().sign(keyPair1, signatureFactory);
FuturePut futurePut3 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair1).start();
futurePut3.awaitUninterruptibly();
assertFalse(futurePut3.isSuccess());
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(testData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
// modify with new protection key
String newTestData = "new data";
data = new Data(newTestData).setProtectedEntry().sign(keyPair2, signatureFactory);
FuturePut futurePut4 = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).keyPair(keyPair2).start();
futurePut4.awaitUninterruptibly();
assertTrue(futurePut4.isSuccess());
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
retData = p2.get(lKey).setDomainKey(dKey).setContentKey(cKey).start().awaitUninterruptibly()
.getData();
assertEquals(newTestData, (String) retData.object());
assertTrue(retData.verify(keyPair2.getPublic(), signatureFactory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@Test
public void testChangeProtectionKeyWithReusedSignature() throws NoSuchAlgorithmException, IOException,
ClassNotFoundException, InvalidKeyException, SignatureException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException {
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
// create custom RSA factories
SignatureFactory factory = new RSASignatureFactory();
SignatureCodec codec = new RSASignatureCodec();
// replace default signature factories
ChannelClientConfiguration clientConfig = PeerMaker.createDefaultChannelClientConfiguration();
clientConfig.signatureFactory(factory);
ChannelServerConficuration serverConfig = PeerMaker.createDefaultChannelServerConfiguration();
serverConfig.signatureFactory(factory);
KeyPair keyPairPeer1 = gen.generateKeyPair();
Peer p1 = new PeerMaker(Number160.createHash(1)).ports(4834).keyPair(keyPairPeer1)
.setEnableIndirectReplication(true).channelClientConfiguration(clientConfig)
.channelServerConfiguration(serverConfig).makeAndListen();
KeyPair keyPairPeer2 = gen.generateKeyPair();
Peer p2 = new PeerMaker(Number160.createHash(2)).masterPeer(p1).keyPair(keyPairPeer2)
.setEnableIndirectReplication(true).channelClientConfiguration(clientConfig)
.channelServerConfiguration(serverConfig).makeAndListen();
p2.bootstrap().setPeerAddress(p1.getPeerAddress()).start().awaitUninterruptibly();
p1.bootstrap().setPeerAddress(p2.getPeerAddress()).start().awaitUninterruptibly();
KeyPair keyPairOld = gen.generateKeyPair();
KeyPair keyPairNew = gen.generateKeyPair();
Number160 lKey = Number160.createHash("location");
Number160 dKey = Number160.createHash("domain");
Number160 cKey = Number160.createHash("content");
Number160 vKey = Number160.createHash("version");
Number160 bKey = Number160.ZERO;
int ttl = 10;
String testData = "data";
Data data = new Data(testData).setProtectedEntry().sign(keyPairOld, factory);
data.ttlSeconds(ttl).basedOn(bKey);
// initial put of some test data
FuturePut futurePut = p1.put(lKey).setDomainKey(dKey).setData(cKey, data).setVersionKey(vKey)
.keyPair(keyPairOld).start();
futurePut.awaitUninterruptibly();
Assert.assertTrue(futurePut.isSuccess());
// create signature with old key pair having the data object
byte[] signature1 = factory.sign(keyPairOld.getPrivate(), data.buffer()).encode();
// decrypt signature to get hash of the object
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, keyPairOld.getPublic());
byte[] hash = rsa.doFinal(signature1);
// encrypt hash with new key pair to get the new signature (without having the data object)
rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, keyPairNew.getPrivate());
byte[] signatureNew = rsa.doFinal(hash);
// verify old content protection keys
Data retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey).start()
.awaitUninterruptibly().getData();
Assert.assertTrue(retData.verify(keyPairOld.getPublic(), factory));
// create a dummy data object for changing the content protection key through a put meta
Data dummyData = new Data();
dummyData.basedOn(bKey).ttlSeconds(ttl);
// assign the reused hash from signature (don't forget to set the signed flag)
dummyData.signature(codec.decode(signatureNew)).signed(true).duplicateMeta();
// change content protection key through a put meta
FuturePut futurePutMeta = p1.put(lKey).setDomainKey(dKey).putMeta().setData(cKey, dummyData)
.setVersionKey(vKey).keyPair(keyPairOld).start();
futurePutMeta.awaitUninterruptibly();
Assert.assertTrue(futurePutMeta.isSuccess());
// verify new content protection keys
retData = p1.get(lKey).setDomainKey(dKey).setContentKey(cKey).setVersionKey(vKey).start()
.awaitUninterruptibly().getData();
Assert.assertTrue(retData.verify(keyPairNew.getPublic(), factory));
p1.shutdown().awaitUninterruptibly();
p2.shutdown().awaitUninterruptibly();
}
@AfterClass
public static void cleanAfterClass() {
afterClass();
}
}
| New findings in tomp2p tested. | org.hive2hive.core.test/src/org/hive2hive/core/test/tomp2p/ContentProtectionTest.java | New findings in tomp2p tested. |
|
Java | mit | ebf1644c60910e41f0adf5a36931eeed84ebbf93 | 0 | stevefsp/critterai,stevefsp/critterai,stevefsp/critterai,stevefsp/critterai,stevefsp/critterai | /*
* Copyright (c) 2010 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.critterai.math;
import static org.critterai.math.MathUtil.EPSILON_STD;
/**
* Represents a mutable 2-dimensional vector.
* <p>Contains various static operations applicable to 2D vectors.</p>
* <p>This class is optimized for speed. To support this priority, no argument validation is
* performed. E.g. No null checks, no divide by zero checks, etc.</p>
* <p>All operations support the use of the same object reference in multiple arguments.
* For example: Vector2.multiply(myVector, 5, myVector) will function
* the same as myVector.multiply(5)</p>
* <p>Instances of this class are not thread safe. Static operations are thread safe.</p>
*/
public class Vector2
{
/**
* The x-value for the vector (x, y).
*/
public float x;
/**
* The y-value for the vector (x, y).
*/
public float y;
/**
* Constructor for the vector (0.0, 0.0). (Default)
*/
public Vector2()
{
x = 0.0f;
y = 0.0f;
}
/**
* Constructor.
* @param x The x-value for the vector (x, y).
* @param y The y-value for the vector (x, y).
*/
public Vector2(float x, float y)
{
this.x = x;
this.y = y;
}
/**
* Adds the provided vector to this vector.
* <p>The values of this vector are mutated.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 add(float x, float y)
{
this.x += x;
this.y += y;
return this;
}
/**
* Adds the provided vector to this vector.
* <p>The values of this vector are mutated.</p>
* @param v The vector to add to this vector.
* @return A reference to this vector.
*/
public Vector2 add(Vector2 v)
{
return add(v.x, v.y);
}
/**
* Divides this vector by the provided value.
* <p>The values of this vector are mutated.</p>
* @param byValue The value to divide the elements of this vector by.
* @return A reference to this vector.
*/
public Vector2 divide(float byValue)
{
this.x /= byValue;
this.y /= byValue;
return this;
}
/**
* Returns the dot product of this vector and the provided vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return The dot product of this vector and the provided vector.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public float dot(float x, float y)
{
return (this.x * x) + (this.y * y);
}
/**
* Returns the dot product of this vector and the provided vector.
* @param v The vector.
* @return The dot product of this vector and the provided vector.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public float dot(Vector2 v)
{
return (this.x * v.x) + (this.y * v.y);
}
/**
* Determines whether or not this vector is equal to the provided vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return Returns TRUE if this vector is equal to the provided vector. Otherwise FALSE.
*/
public boolean equals(float x, float y)
{
if (Float.floatToIntBits(this.x) != Float.floatToIntBits(x)
|| Float.floatToIntBits(this.y) != Float.floatToIntBits(y))
return false;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Vector2))
return false;
Vector2 other = (Vector2) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.getX()))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.getY()))
return false;
return true;
}
/**
* Determines whether or not this vector is equal to the provided vector.
* <p>This operation is slightly faster than the {@link #equals(Object)} form.</p>
* @param v The vector to compare to. (A value of null will result in a runtime error.)
* @return Returns TRUE if this vector is equal to the provided vector. Otherwise FALSE.
*/
public boolean equals(Vector2 v)
{
return equals(v.x, v.y);
}
/**
* The x-value for this vector.
* @return The x-value for the vector (x, y).
*/
public float getX() { return x; }
/**
* The y-value for this vector.
* @return The y-value for the vector (x, y).
*/
public float getY() { return y; }
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
/**
* Returns TRUE if the length of the provided vector is zero.
* @return TRUE if the length of the provided vector is zero. Otherwise FALSE.
*/
public boolean isZeroLength()
{
return (x == 0 && y == 0);
}
/**
* Returns the square of the vector's length. (length * length)
* @return The square of the vector's length.
*/
public float lengthSq()
{
return (x * x) + (y * y);
}
/**
* Multiplies (scales) this vector by the provided value.
* <p>The values of this vector are mutated.</p>
* @param byValue The value to multiply the elements of this vector by.
* @return A reference to this vector.
*/
public Vector2 multiply(float byValue)
{
this.x *= byValue;
this.y *= byValue;
return this;
}
/**
* Normalizes this vector such that its length is one.
* <p>The values of this vector are mutated.</p>
* <p>WARNING: This is a costly operation.</p>
* @return A reference to this vector.
*/
public Vector2 normalize()
{
float length = (float)Math.sqrt((x * x) + (y * y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
return this;
}
/**
* Reverses the direction of the vector.
* @return A reference to this vector.
*/
public Vector2 reverse()
{
x = -x;
y = -y;
return this;
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>The values of this vector are mutated.</p>
* <p>This is a non-trivial operation.</p>
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @return A reference to this vector.
*/
public Vector2 rotate(float angle)
{
float ca = (float)Math.cos(angle);
float sa = (float)Math.sin(angle);
float tx = (x * ca) - (y * sa);
y = (x * sa) + (y * ca);
x = tx;
return this;
}
/**
* Scales the vector to the provided length.
* <p>The values of this vector are mutated.</p>
* <p>WARNING: This is a costly operation.</p>
* @param length The length to scale the vector to.
* @return A reference to this vector.
*/
public Vector2 scaleTo(float length)
{
if (length == 0 || isZeroLength())
{
x = 0;
y = 0;
return this;
}
return multiply(length / (float)(Math.sqrt((x * x) + (y * y))));
}
/**
* Sets the values of this vector.
* @param x The x-value for the vector (x, y).
* @param y The y-value for the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 set(float x, float y)
{
this.x = x;
this.y = y;
return this;
}
/**
* Sets the values of this vector to match the provided vector.
* @param v The vector to match this vector to.
* @return A reference to this vector.
*/
public Vector2 set(Vector2 v)
{
this.x = v.x;
this.y = v.y;
return this;
}
/**
* Sets the x-value of this vector.
* @param value The new the x-value for the vector (x, y).
*/
public void setX(float value) { x = value; }
/**
* Sets the y-value for the vector (x, y).
* @param value The new the y-value for the vector (x, y).
*/
public void setY(float value) { y = value; }
/**
* Determines whether or not the elements of the provided vector are equal within
* the specified tolerance of this vector.
* <p>The vectors are considered equal if the following condition is met:
* (vx >= x - tolerance && vx <= x + tolerance)
* && (vy >= y - tolerance && vy <= y + tolerance)</p>
* @param vx The x-value for the vector (vx, vy).
* @param vy The y-value for the vector (vx, vy).
* @param tolerance The tolerance to use for the comparison.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public boolean sloppyEquals(float vx, float vy, float tolerance)
{
tolerance = Math.max(0, tolerance);
if (vx < x - tolerance || vx > x + tolerance)
return false;
if (vy < y - tolerance || vy > y + tolerance)
return false;
return true;
}
/**
* Determines whether or not the elements of the provided vector are equal within
* the specified tolerance of this vector.
* <p>The vectors are considered equal if the following condition is met:
* (v.x >= x - tolerance && v.x <= x + tolerance)
* && (v.y >= y - tolerance && v.y <= y + tolerance)</p>
* @param v The vector to compare against.
* @param tolerance The tolerance for the comparison.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public boolean sloppyEquals(Vector2 v, float tolerance)
{
return sloppyEquals(v.x, v.y, tolerance);
}
/**
* Subtracts the provided vector from this vector. (this - providedVector)
* <p>The values of this vector are mutated.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 subtract(float x, float y)
{
this.x -= x;
this.y -= y;
return this;
}
/**
* Subtracts the provided vector from this vector. (this - v)
* <p>The values of this vector are mutated.</p>
* @param v The vector to subtract from this vector.
* @return A reference to this vector.
*/
public Vector2 subtract(Vector2 v)
{
return subtract(v.x, v.y);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() { return "(" + x + ", " + y + ")"; }
/**
* Truncates the length of this vector to the provided value.
* <p>The values of this vector are mutated.</p>
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param maxLength The maximum allowed length of the resulting vector.
* @return A reference to this vector.
*/
public Vector2 truncateLength(float maxLength)
{
if (isZeroLength())
return this;
if (maxLength == 0)
{
set(0, 0);
return this;
}
float mlsq = maxLength * maxLength;
float csq = (x * x) + (y * y);
if (csq > mlsq)
multiply((float)(maxLength / Math.sqrt(csq)));
return this;
}
/**
* Adds the vectors (ux, uy) and (vx, vy).
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(float ux, float uy, float vx, float vy, Vector2 out)
{
out.set(ux + vx, uy + vy);
return out;
}
/**
* Adds the value to both elements of the vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param value The value to add to both of the vector elements.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(float x, float y, float value, Vector2 out)
{
out.set(x + value, y + value);
return out;
}
/**
* Adds the value to both elements of the vector.
* @param v The vector to add the value to.
* @param value The value to add to both of the vector elements.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(Vector2 v, float value, Vector2 out)
{
return add(v.x, v.y, value, out);
}
/**
* Adds the two provided vectors.
* @param u Vector to add.
* @param v Vector to add.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(Vector2 u, Vector2 v, Vector2 out)
{
return add(u.x, u.y, v.x, v.y, out);
}
/**
* Divides both elements of the vector by the provided value.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param byValue The value to divide the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 divide(float x, float y, float byValue, Vector2 out)
{
out.set(x / byValue, y / byValue);
return out;
}
/**
* Divides both elements of the vector by the provided value.
* @param v The vector.
* @param byValue The value to divide the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 divide(Vector2 v, float byValue, Vector2 out)
{
return divide(v.x, v.y, byValue, out);
}
/**
* Returns the dot products of the provided vectors.
* <p>If you need to the dot product of two vector objects, use {@link #dot(Vector2)}.</p>
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @return The dot product of the provided vectors.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public static float dot(float ux, float uy, float vx, float vy)
{
return (ux * vx) + (uy * vy);
}
/**
* Derives the normalized direction vector for the vector pointing from point A (ax, ay) to
* point B (bx, by).
* <p>WARNING: The out array size and validity of the outIndex are not checked.</p>
* <p>WARNING: This is a costly operation.</p>
* @param ax The x-value for the starting point A (ax, ay).
* @param ay The y-value for the starting point A (ax, ay).
* @param bx The x-value for the end point B (bx, by).
* @param by The y-value for the end point B (bx, by).
* @param out The array to load the result into in the form (x, y).
* @param outIndex The vector index to load the result into. (Stride = 2. So insertion location
* will be outIndex*2.)
* @return A reference to the out argument.
*/
public static float[] getDirectionAB(float ax, float ay
, float bx, float by
, float[] out
, int outIndex)
{
// Subtract.
float x = bx - ax;
float y = by - ay;
// Normalize.
float length = (float)Math.sqrt((x * x) + (y * y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
out[outIndex*2] = x;
out[outIndex*2+1] = y;
return out;
}
/**
* Derives the normalized direction vector for the vector pointing from point A (ax, ay) to
* point B (bx, by).
* <p>WARNING: This is a costly operation.</p>
* @param ax The x-value for the starting point A (ax, ay).
* @param ay The y-value for the starting point A (ax, ay).
* @param bx The x-value for the end point B (bx, by).
* @param by The y-value for the end point B (bx, by).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 getDirectionAB(float ax, float ay
, float bx, float by
, Vector2 out)
{
// Subtract.
out.x = bx - ax;
out.y = by - ay;
// Normalize.
float length = (float)Math.sqrt((out.x * out.x) + (out.y * out.y));
if (length <= EPSILON_STD)
length = 1;
out.x /= length;
out.y /= length;
if (Math.abs(out.x) < EPSILON_STD)
out.x = 0;
if (Math.abs(out.y) < EPSILON_STD)
out.y = 0;
return out;
}
/**
* Returns the square of the distance between the two provided points. (distance * distance)
* @param ax The x-value of the point (ax, ay).
* @param ay The y-value of the point (ax, ay).
* @param bx The x-value of the point (bx, by).
* @param by The y-value of the point (bx, by).
* @return The square of the distance between the two provided points.
*/
public static float getDistanceSq(float ax, float ay, float bx, float by)
{
float dx = ax - bx;
float dy = ay - by;
return (dx * dx + dy * dy);
}
/**
* Returns the square of the distance between the two provided points. (distance * distance)
* @param a Point A
* @param b Point B
* @return The square of the distance between the two provided points.
*/
public static float getDistanceSq(Vector2 a, Vector2 b)
{
return getDistanceSq(a.x, a.y, b.x, b.y);
}
/**
* Returns the square of the length of the vector. (length * length)
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return The square of the length of the vector.
*/
public static float getLengthSq(float x, float y)
{
return (x * x + y * y);
}
/**
* Multiplies both elements of the vector by the provided value.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param byValue The value to multiply the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 multiply(float x, float y, float byValue, Vector2 out)
{
out.set(x * byValue, y * byValue);
return out;
}
/**
* Multiplies both elements of the vector by the provided value.
* @param v The vector.
* @param byValue The value to multiply the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 multiply(Vector2 v, float byValue, Vector2 out)
{
return multiply(v.x, v.y, byValue, out);
}
/**
* Normalizes the provided vector such that its length is equal to one.
* <p>WARNING: This is a costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 normalize(float x, float y, Vector2 out)
{
float length = (float)Math.sqrt(getLengthSq(x, y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
out.set(x, y);
return out;
}
/**
* Normalizes the provided vector such that its length is equal to one.
* <p>WARNING: This is a costly operation.</p>
* @param v The vector to normalize.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 normalize(Vector2 v, Vector2 out)
{
return normalize(v.x, v.y, out);
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>This is a non-trivial operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 rotate(float x, float y, float angle, Vector2 out)
{
float ca = (float)Math.cos(angle);
float sa = (float)Math.sin(angle);
out.set((x * ca) - (y * sa), (x * sa) + (y * ca));
return out;
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>This is a non-trivial operation.</p>
* @param v The vector to rotate.
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 rotate(Vector2 v, float angle, Vector2 out)
{
return rotate(v.x, v.y, angle, out);
}
/**
* Scales the vector to the provided length.
* <p>WARNING: This is a costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param length The length to scale the vector to.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 scaleTo(float x, float y, float length, Vector2 out)
{
if (length == 0 || (x == 0 && y == 0))
{
out.set(0, 0);
return out;
}
return multiply(x, y
, (length / (float)(Math.sqrt(getLengthSq(x, y)))), out);
}
/**
* Scales the vector to the provided length.
* <p>WARNING: This is a costly operation.</p>
* @param v The vector to scale.
* @param length The length to scale the vector to.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 scaleTo(Vector2 v, float length, Vector2 out)
{
return scaleTo(v.x, v.y, length, out);
}
/**
* Determines whether or not the elements of the provided vectors are equal within
* the specified tolerance.
* <p>The vectors are considered equal if the following condition is met:
* (vx >= ux - tolerance && vx <= ux + tolerance)
* && (vy >= uy - tolerance && vy <= uy + tolerance)</p>
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @param tolerance The tolerance for the test.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public static boolean sloppyEquals(float ux, float uy, float vx, float vy, float tolerance)
{
tolerance = Math.max(0, tolerance);
if (vx < ux - tolerance || vx > ux + tolerance)
return false;
if (vy < uy - tolerance || vy > uy + tolerance)
return false;
return true;
}
/**
* Determines whether or not the elements of the provided vectors are equal within
* the specified tolerance.
* <p>The vectors are considered equal if the following condition is met:
* (v.x >= u.x - tolerance && v.x <= u.x + tolerance)
* && (v.y >= u.y - tolerance && v.y <= u.y + tolerance)</p>
* @param u Vector v
* @param v Vector u
* @param tolerance The tolerance for the test.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public static boolean sloppyEquals(Vector2 u, Vector2 v, float tolerance)
{
return sloppyEquals(u.x, u.y, v.x, v.y, tolerance);
}
/**
* Subtracts vector (vx, vy) from vector (ux, uy)
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 subtract(float ux, float uy, float vx, float vy, Vector2 out)
{
out.set(ux - vx, uy - vy);
return out;
}
/**
* Subtracts two vectors. (u - v)
* @param u Vector to be subtracted from.
* @param v Vector to subtract.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 subtract(Vector2 u, Vector2 v, Vector2 out)
{
return subtract(u.x, u.y, v.x, v.y, out);
}
/**
* Truncates the length of the vector to the provided value.
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param maxLength The maximum allowed length of the resulting vector.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 truncateLength(float x, float y, float maxLength, Vector2 out)
{
if (maxLength == 0 || (x == 0 && y == 0))
{
out.set(0, 0);
return out;
}
float mlsq = maxLength * maxLength;
float csq = getLengthSq(x, y);
if (csq <= mlsq)
{
out.set(x, y);
return out;
}
return multiply(x, y, (float)(maxLength / Math.sqrt(csq)), out);
}
/**
* Truncates the length of the vector to the provided value.
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param v The vector to truncate.
* @param maxLength The maximum allowed length of the resulting vector.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 truncateLength(Vector2 v, float maxLength, Vector2 out)
{
return truncateLength(v.x, v.y, maxLength, out);
}
}
| util/src/org/critterai/math/Vector2.java | /*
* Copyright (c) 2010 Stephen A. Pratt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.critterai.math;
import static org.critterai.math.MathUtil.EPSILON_STD;
/**
* Represents a mutable 2-dimensional vector.
* <p>Contains various static operations applicable to 2D vectors.</p>
* <p>This class is optimized for speed. To support this priority, no argument validation is
* performed. E.g. No null checks, no divide by zero checks, etc.</p>
* <p>All operations support the use of the same object reference in multiple arguments.
* For example: Vector2.multiply(myVector, 5, myVector) will function
* the same as myVector.multiply(5)</p>
* <p>Instances of this class are not thread safe. Static operations are thread safe.</p>
*/
public class Vector2
{
/**
* The x-value for the vector (x, y).
*/
public float x;
/**
* The y-value for the vector (x, y).
*/
public float y;
/**
* Constructor for the vector (0.0, 0.0). (Default)
*/
public Vector2()
{
x = 0.0f;
y = 0.0f;
}
/**
* Constructor.
* @param x The x-value for the vector (x, y).
* @param y The y-value for the vector (x, y).
*/
public Vector2(float x, float y)
{
this.x = x;
this.y = y;
}
/**
* Adds the provided vector to this vector.
* <p>The values of this vector are mutated.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 add(float x, float y)
{
this.x += x;
this.y += y;
return this;
}
/**
* Adds the provided vector to this vector.
* <p>The values of this vector are mutated.</p>
* @param v The vector to add to this vector.
* @return A reference to this vector.
*/
public Vector2 add(Vector2 v)
{
return add(v.x, v.y);
}
/**
* Divides this vector by the provided value.
* <p>The values of this vector are mutated.</p>
* @param byValue The value to divide the elements of this vector by.
* @return A reference to this vector.
*/
public Vector2 divide(float byValue)
{
this.x /= byValue;
this.y /= byValue;
return this;
}
/**
* Returns the dot product of this vector and the provided vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return The dot product of this vector and the provided vector.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public float dot(float x, float y)
{
return (this.x * x) + (this.y * y);
}
/**
* Returns the dot product of this vector and the provided vector.
* @param v The vector.
* @return The dot product of this vector and the provided vector.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public float dot(Vector2 v)
{
return (this.x * v.x) + (this.y * v.y);
}
/**
* Determines whether or not this vector is equal to the provided vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return Returns TRUE if this vector is equal to the provided vector. Otherwise FALSE.
*/
public boolean equals(float x, float y)
{
if (Float.floatToIntBits(this.x) != Float.floatToIntBits(x)
|| Float.floatToIntBits(this.y) != Float.floatToIntBits(y))
return false;
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Vector2))
return false;
Vector2 other = (Vector2) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.getX()))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.getY()))
return false;
return true;
}
/**
* Determines whether or not this vector is equal to the provided vector.
* <p>This operation is slightly faster than the {@link #equals(Object)} form.</p>
* @param v The vector to compare to. (A value of null will result in a runtime error.)
* @return Returns TRUE if this vector is equal to the provided vector. Otherwise FALSE.
*/
public boolean equals(Vector2 v)
{
return equals(v.x, v.y);
}
/**
* The x-value for this vector.
* @return The x-value for the vector (x, y).
*/
public float getX() { return x; }
/**
* The y-value for this vector.
* @return The y-value for the vector (x, y).
*/
public float getY() { return y; }
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
/**
* Returns TRUE if the length of the provided vector is zero.
* @return TRUE if the length of the provided vector is zero. Otherwise FALSE.
*/
public boolean isZeroLength()
{
return (x == 0 && y == 0);
}
/**
* Returns the square of the vector's length. (length * length)
* @return The square of the vector's length.
*/
public float lengthSq()
{
return (x * x) + (y * y);
}
/**
* Multiplies (scales) this vector by the provided value.
* <p>The values of this vector are mutated.</p>
* @param byValue The value to multiply the elements of this vector by.
* @return A reference to this vector.
*/
public Vector2 multiply(float byValue)
{
this.x *= byValue;
this.y *= byValue;
return this;
}
/**
* Normalizes this vector such that its length is one.
* <p>The values of this vector are mutated.</p>
* <p>WARNING: This is a costly operation.</p>
* @return A reference to this vector.
*/
public Vector2 normalize()
{
float length = (float)Math.sqrt((x * x) + (y * y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
return this;
}
/**
* Reverses the direction of the vector.
* @return A reference to this vector.
*/
public Vector2 reverse()
{
x = -x;
y = -y;
return this;
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>The values of this vector are mutated.</p>
* <p>This is a non-trivial operation.</p>
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @return A reference to this vector.
*/
public Vector2 rotate(float angle)
{
float ca = (float)Math.cos(angle);
float sa = (float)Math.sin(angle);
float tx = (x * ca) - (y * sa);
y = (x * sa) + (y * ca);
x = tx;
return this;
}
/**
* Scales the vector to the provided length.
* <p>The values of this vector are mutated.</p>
* <p>WARNING: This is a costly operation.</p>
* @param length The length to scale the vector to.
* @return A reference to this vector.
*/
public Vector2 scaleTo(float length)
{
if (length == 0 || isZeroLength())
{
x = 0;
y = 0;
return this;
}
return multiply(length / (float)(Math.sqrt((x * x) + (y * y))));
}
/**
* Sets the values of this vector.
* @param x The x-value for the vector (x, y).
* @param y The y-value for the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 set(float x, float y)
{
this.x = x;
this.y = y;
return this;
}
/**
* Sets the values of this vector to match the provided vector.
* @param v The vector to match this vector to.
* @return A reference to this vector.
*/
public Vector2 set(Vector2 v)
{
this.x = v.x;
this.y = v.y;
return this;
}
/**
* Sets the x-value of this vector.
* @param value The new the x-value for the vector (x, y).
*/
public void setX(float value) { x = value; }
/**
* Sets the y-value for the vector (x, y).
* @param value The new the y-value for the vector (x, y).
*/
public void setY(float value) { y = value; }
/**
* Determines whether or not the elements of the provided vector are equal within
* the specified tolerance of this vector.
* <p>The vectors are considered equal if the following condition is met:
* (vx >= x - tolerance && vx <= x + tolerance)
* && (vy >= y - tolerance && vy <= y + tolerance)</p>
* @param vx The x-value for the vector (vx, vy).
* @param vy The y-value for the vector (vx, vy).
* @param tolerance The tolerance to use for the comparison.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public boolean sloppyEquals(float vx, float vy, float tolerance)
{
tolerance = Math.max(0, tolerance);
if (vx < x - tolerance || vx > x + tolerance)
return false;
if (vy < y - tolerance || vy > y + tolerance)
return false;
return true;
}
/**
* Determines whether or not the elements of the provided vector are equal within
* the specified tolerance of this vector.
* <p>The vectors are considered equal if the following condition is met:
* (v.x >= x - tolerance && v.x <= x + tolerance)
* && (v.y >= y - tolerance && v.y <= y + tolerance)</p>
* @param v The vector to compare against.
* @param tolerance The tolerance for the comparison.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public boolean sloppyEquals(Vector2 v, float tolerance)
{
return sloppyEquals(v.x, v.y, tolerance);
}
/**
* Subtracts the provided vector from this vector. (this - providedVector)
* <p>The values of this vector are mutated.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return A reference to this vector.
*/
public Vector2 subtract(float x, float y)
{
this.x -= x;
this.y -= y;
return this;
}
/**
* Subtracts the provided vector from this vector. (this - v)
* <p>The values of this vector are mutated.</p>
* @param v The vector to subtract from this vector.
* @return A reference to this vector.
*/
public Vector2 subtract(Vector2 v)
{
return subtract(v.x, v.y);
}
/**
* {@inheritDoc}
*/
@Override
public String toString() { return "(" + x + ", " + y + ")"; }
/**
* Truncates the length of this vector to the provided value.
* <p>The values of this vector are mutated.</p>
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param maxLength The maximum allowed length of the resulting vector.
* @return A reference to this vector.
*/
public Vector2 truncateLength(float maxLength)
{
if (isZeroLength())
return this;
if (maxLength == 0)
{
set(0, 0);
return this;
}
float mlsq = maxLength * maxLength;
float csq = (x * x) + (y * y);
if (csq > mlsq)
multiply((float)(maxLength / Math.sqrt(csq)));
return this;
}
/**
* Adds the vectors (ux, uy) and (vx, vy).
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(float ux, float uy, float vx, float vy, Vector2 out)
{
out.set(ux + vx, uy + vy);
return out;
}
/**
* Adds the value to both elements of the vector.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param value The value to add to both of the vector elements.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(float x, float y, float value, Vector2 out)
{
out.set(x + value, y + value);
return out;
}
/**
* Adds the value to both elements of the vector.
* @param v The vector to add the value to.
* @param value The value to add to both of the vector elements.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(Vector2 v, float value, Vector2 out)
{
return add(v.x, v.y, value, out);
}
/**
* Adds the two provided vectors.
* @param u Vector to add.
* @param v Vector to add.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 add(Vector2 u, Vector2 v, Vector2 out)
{
return add(u.x, u.y, v.x, v.y, out);
}
/**
* Divides both elements of the vector by the provided value.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param byValue The value to divide the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 divide(float x, float y, float byValue, Vector2 out)
{
out.set(x / byValue, y / byValue);
return out;
}
/**
* Divides both elements of the vector by the provided value.
* @param v The vector.
* @param byValue The value to divide the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 divide(Vector2 v, float byValue, Vector2 out)
{
return divide(v.x, v.y, byValue, out);
}
/**
* Returns the dot products of the provided vectors.
* <p>If you need to the dot product of two vector objects, use {@link #dot(Vector2)}.</p>
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @return The dot product of the provided vectors.
* @see <a href="http://en.wikipedia.org/wiki/Dot_product" target="_blank">Wikipedia- Dot Product</a>
*/
public static float dot(float ux, float uy, float vx, float vy)
{
return (ux * vx) + (uy * vy);
}
/**
* Derives the normalized direction vector for the vector pointing from point A (ax, ay) to
* point B (bx, by).
* <p>WARNING: The out array size and validity of the outIndex are not checked.</p>
* <p>WARNING: This is a costly operation.</p>
* @param ax The x-value for the starting point A (ax, ay).
* @param ay The y-value for the starting point A (ax, ay).
* @param bx The x-value for the end point B (bx, by).
* @param by The y-value for the end point B (bx, by).
* @param out The array to load the result into in the form (x, y).
* @param outIndex The vector index to load the result into. (Stride = 2. So insertion location
* will be outIndex*2.)
* @return A reference to the out argument.
*/
public static float[] getDirectionAB(float ax, float ay
, float bx, float by
, float[] out
, int outIndex)
{
// Subtract.
float x = bx - ax;
float y = by - ay;
// Normalize.
float length = (float)Math.sqrt((x * x) + (y * y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
out[outIndex*2] = x;
out[outIndex*2+1] = y;
return out;
}
/**
* Derives the normalized direction vector for the vector pointing from point A (ax, ay) to
* point B (bx, by).
* <p>WARNING: This is a costly operation.</p>
* @param ax The x-value for the starting point A (ax, ay).
* @param ay The y-value for the starting point A (ax, ay).
* @param bx The x-value for the end point B (bx, by).
* @param by The y-value for the end point B (bx, by).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 getDirectionAB(float ax, float ay
, float bx, float by
, Vector2 out)
{
// Subtract.
out.x = bx - ax;
out.y = by - ay;
// Normalize.
float length = (float)Math.sqrt((out.x * out.x) + (out.y * out.y));
if (length <= EPSILON_STD)
length = 1;
out.x /= length;
out.y /= length;
if (Math.abs(out.x) < EPSILON_STD)
out.x = 0;
if (Math.abs(out.y) < EPSILON_STD)
out.y = 0;
return out;
}
/**
* Returns the square of the distance between the two provided points. (distance * distance)
* @param ax The x-value of the point (ax, ay).
* @param ay The y-value of the point (ax, ay).
* @param bx The x-value of the point (bx, by).
* @param by The y-value of the point (bx, by).
* @return The square of the distance between the two provided points.
*/
public static float getDistanceSq(float ax, float ay, float bx, float by)
{
float dx = ax - bx;
float dy = ay - by;
return (dx * dx + dy * dy);
}
/**
* Returns the square of the distance between the two provided points. (distance * distance)
* @param a Point A
* @param b Point B
* @return The square of the distance between the two provided points.
*/
public static float getDistanceSq(Vector2 a, Vector2 b)
{
return getDistanceSq(a.x, a.y, b.x, b.y);
}
/**
* Returns the square of the length of the vector. (length * length)
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @return The square of the length of the vector.
*/
public static float getLengthSq(float x, float y)
{
return (x * x + y * y);
}
/**
* Multiplies both elements of the vector by the provided value.
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param byValue The value to multiply the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 multiply(float x, float y, float byValue, Vector2 out)
{
out.set(x * byValue, y * byValue);
return out;
}
/**
* Multiplies both elements of the vector by the provided value.
* @param v The vector.
* @param byValue The value to multiply the vector by.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 multiply(Vector2 v, float byValue, Vector2 out)
{
return multiply(v.x, v.y, byValue, out);
}
/**
* Normalizes the provided vector such that its length is equal to one.
* <p>WARNING: This is a costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 normalize(float x, float y, Vector2 out)
{
float length = (float)Math.sqrt(getLengthSq(x, y));
if (length <= EPSILON_STD)
length = 1;
x /= length;
y /= length;
if (Math.abs(x) < EPSILON_STD)
x = 0;
if (Math.abs(y) < EPSILON_STD)
y = 0;
out.set(x, y);
return out;
}
/**
* Normalizes the provided vector such that its length is equal to one.
* <p>WARNING: This is a costly operation.</p>
* @param v The vector to normalize.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 normalize(Vector2 v, Vector2 out)
{
return normalize(v.x, v.y, out);
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>This is a non-trivial operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 rotate(float x, float y, float angle, Vector2 out)
{
float ca = (float)Math.cos(angle);
float sa = (float)Math.sin(angle);
out.set((x * ca) - (y * sa), (x * sa) + (y * ca));
return out;
}
/**
* Rotates the vector counter-clockwise by the specified angle.
* <p>This is a non-trivial operation.</p>
* @param v The vector to rotate.
* @param angle Angle of counter-clockwise rotation. (In Radians.)
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 rotate(Vector2 v, float angle, Vector2 out)
{
return rotate(v.x, v.y, angle, out);
}
/**
* Scales the vector to the provided length.
* <p>WARNING: This is a costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param length The length to scale the vector to.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 scaleTo(float x, float y, float length, Vector2 out)
{
if (length == 0 || (x == 0 && y == 0))
{
out.set(0, 0);
return out;
}
return multiply(x, y
, (length / (float)(Math.sqrt(getLengthSq(x, y)))), out);
}
/**
* Scales the vector to the provided length.
* <p>WARNING: This is a costly operation.</p>
* @param v The vector to scale.
* @param length The length to scale the vector to.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 scaleTo(Vector2 v, float length, Vector2 out)
{
return scaleTo(v.x, v.y, length, out);
}
/**
* Determines whether or not the elements of the provided vectors are equal within
* the specified tolerance.
* <p>The vectors are considered equal if the following condition is met:
* (vx >= ux - tolerance && vx <= ux + tolerance)
* && (vy >= uy - tolerance && vy <= uy + tolerance)</p>
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vy The y-value of the vector (vx, vy).
* @param tolerance The tolerance for the test.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public static boolean sloppyEquals(float ux, float uy, float vx, float vy, float tolerance)
{
tolerance = Math.max(0, tolerance);
if (vx < ux - tolerance || vx > ux + tolerance)
return false;
if (vy < uy - tolerance || vy > uy + tolerance)
return false;
return true;
}
/**
* Determines whether or not the elements of the provided vectors are equal within
* the specified tolerance.
* <p>The vectors are considered equal if the following condition is met:
* (v.x >= u.x - tolerance && v.x <= u.x + tolerance)
* && (v.y >= u.y - tolerance && v.y <= u.y + tolerance)</p>
* @param u Vector v
* @param v Vector u
* @param tolerance The tolerance for the test.
* @return TRUE if the the associated elements of each vector are within the specified tolerance
* of each other. Otherwise FALSE.
*/
public static boolean sloppyEquals(Vector2 u, Vector2 v, float tolerance)
{
return sloppyEquals(u.x, u.y, v.x, v.y, tolerance);
}
/**
* Subtracts vector (vx, vy) from vector (ux, uy)
* @param ux The x-value of the vector (ux, uy).
* @param uy The y-value of the vector (ux, uy).
* @param vx The x-value of the vector (vx, vy).
* @param vx The y-value of the vector (vx, vy).
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 subtract(float ux, float uy, float vx, float vy, Vector2 out)
{
out.set(ux - vx, uy - vy);
return out;
}
/**
* Subtracts two vectors. (u - v)
* @param u Vector to be subtracted from.
* @param v Vector to subtract.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 subtract(Vector2 u, Vector2 v, Vector2 out)
{
return subtract(u.x, u.y, v.x, v.y, out);
}
/**
* Truncates the length of the vector to the provided value.
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param x The x-value of the vector (x, y).
* @param y The y-value of the vector (x, y).
* @param maxLength The maximum allowed length of the resulting vector.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 truncateLength(float x, float y, float maxLength, Vector2 out)
{
if (maxLength == 0 || (x == 0 && y == 0))
{
out.set(0, 0);
return out;
}
float mlsq = maxLength * maxLength;
float csq = getLengthSq(x, y);
if (csq <= mlsq)
{
out.set(x, y);
return out;
}
return multiply(x, y, (float)(maxLength / Math.sqrt(csq)), out);
}
/**
* Truncates the length of the vector to the provided value.
* <p>If the vector's length is longer than the provided value the length
* of the vector is scaled back to the provided maximum length.</p>
* <p>If the vector's length is shorter than the provided value, the vector
* is not changed.</p>
* <p>WARNING: This is a potentially costly operation.</p>
* @param v The vector to truncate.
* @param maxLength The maximum allowed length of the resulting vector.
* @param out The vector to load the result into.
* @return A reference to the out argument.
*/
public static Vector2 truncateLength(Vector2 v, float maxLength, Vector2 out)
{
return truncateLength(v.x, v.y, maxLength, out);
}
}
| Fix javadoc, clean tabs. | util/src/org/critterai/math/Vector2.java | Fix javadoc, clean tabs. |
|
Java | mit | 6283ae34a5c78dd13074e276cc436222add78500 | 0 | Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation,Lyokone/flutterlocation | package com.lyokone.location;
import android.Manifest;
import android.app.Activity;
import android.provider.Settings;
import android.content.IntentSender;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.content.Context;
import android.os.Build;
import android.os.Looper;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.annotation.TargetApi;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.OnFailureListener;
import java.util.ArrayList;
import java.util.HashMap;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener;
/**
* LocationPlugin
*/
public class LocationPlugin implements MethodCallHandler, StreamHandler, PluginRegistry.ActivityResultListener {
private static final String STREAM_CHANNEL_NAME = "lyokone/locationstream";
private static final String METHOD_CHANNEL_NAME = "lyokone/location";
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final int GPS_ENABLE_REQUEST = 0x1001;
private final FusedLocationProviderClient mFusedLocationClient;
private final SettingsClient mSettingsClient;
private static LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private PluginRegistry.RequestPermissionsResultListener mPermissionsResultListener;
@TargetApi(Build.VERSION_CODES.N)
private OnNmeaMessageListener mMessageListener;
private Double mLastMslAltitude;
// Parameters of the request
private static long update_interval_in_milliseconds = 5000;
private static long fastest_update_interval_in_milliseconds = update_interval_in_milliseconds / 2;
private static Integer location_accuray = LocationRequest.PRIORITY_HIGH_ACCURACY;
private static float distanceFilter = 0f;
private EventSink events;
private Result result;
private int locationPermissionState;
private final Activity activity;
private boolean waitingForPermission = false;
private LocationManager locationManager;
private HashMap<Integer, Integer> mapFlutterAccuracy = new HashMap<>();
LocationPlugin(Activity activity) {
this.activity = activity;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(activity);
mSettingsClient = LocationServices.getSettingsClient(activity);
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
this.mapFlutterAccuracy.put(0, LocationRequest.PRIORITY_NO_POWER);
this.mapFlutterAccuracy.put(1, LocationRequest.PRIORITY_LOW_POWER);
this.mapFlutterAccuracy.put(2, LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
this.mapFlutterAccuracy.put(3, LocationRequest.PRIORITY_HIGH_ACCURACY);
this.mapFlutterAccuracy.put(4, LocationRequest.PRIORITY_HIGH_ACCURACY);
createLocationCallback();
createLocationRequest();
createPermissionsResultListener();
buildLocationSettingsRequest();
}
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
if(registrar.activity() != null) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), METHOD_CHANNEL_NAME);
LocationPlugin locationWithMethodChannel = new LocationPlugin(registrar.activity());
channel.setMethodCallHandler(locationWithMethodChannel);
registrar.addRequestPermissionsResultListener(locationWithMethodChannel.getPermissionsResultListener());
registrar.addActivityResultListener(locationWithMethodChannel);
final EventChannel eventChannel = new EventChannel(registrar.messenger(), STREAM_CHANNEL_NAME);
LocationPlugin locationWithEventChannel = new LocationPlugin(registrar.activity());
eventChannel.setStreamHandler(locationWithEventChannel);
registrar.addRequestPermissionsResultListener(locationWithEventChannel.getPermissionsResultListener());
}
}
@Override
public void onMethodCall(MethodCall call, final Result result) {
if (call.method.equals("changeSettings")) {
try {
this.location_accuray = this.mapFlutterAccuracy.get(call.argument("accuracy"));
this.update_interval_in_milliseconds = new Long((int) call.argument("interval"));
this.fastest_update_interval_in_milliseconds = this.update_interval_in_milliseconds / 2;
this.distanceFilter = new Float((double) call.argument("distanceFilter"));
createLocationCallback();
createLocationRequest();
createPermissionsResultListener();
buildLocationSettingsRequest();
result.success(1);
} catch(Exception e) {
result.error("CHANGE_SETTINGS_ERROR", "An unexcepted error happened during location settings change:" + e.getMessage(), null);
}
} else if (call.method.equals("getLocation")) {
this.result = result;
if (!checkPermissions()) {
requestPermissions();
} else {
startRequestingLocation();
}
} else if (call.method.equals("hasPermission")) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
result.success(1);
return;
}
if (checkPermissions()) {
result.success(1);
} else {
result.success(0);
}
} else if (call.method.equals("requestPermission")) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
result.success(1);
return;
}
this.waitingForPermission = true;
this.result = result;
requestPermissions();
} else if (call.method.equals("serviceEnabled")) {
checkServiceEnabled(result);
} else if (call.method.equals("requestService")) {
requestService(result);
} else {
result.notImplemented();
}
}
public PluginRegistry.RequestPermissionsResultListener getPermissionsResultListener() {
return mPermissionsResultListener;
}
private void createPermissionsResultListener() {
mPermissionsResultListener = new PluginRegistry.RequestPermissionsResultListener() {
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE && permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
if (waitingForPermission) {
waitingForPermission = false;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
result.success(1);
} else {
result.success(0);
}
result = null;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (result != null) {
startRequestingLocation();
} else if (events != null) {
startRequestingLocation();
}
} else {
if (!shouldShowRequestPermissionRationale()) {
if (result != null) {
result.error("PERMISSION_DENIED_NEVER_ASK", "Location permission denied forever- please open app settings", null);
} else if (events != null) {
events.error("PERMISSION_DENIED_NEVER_ASK", "Location permission denied forever - please open app settings", null);
events = null;
}
} else {
if (result != null) {
result.error("PERMISSION_DENIED", "Location permission denied", null);
} else if (events != null) {
events.error("PERMISSION_DENIED", "Location permission denied", null);
events = null;
}
}
}
return true;
}
return false;
}
};
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case GPS_ENABLE_REQUEST:
if (resultCode == Activity.RESULT_OK) {
this.result.success(1);
} else {
this.result.success(0);
}
break;
default:
return false;
}
return true;
}
/**
* Creates a callback for receiving location events.
*/
private void createLocationCallback() {
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
HashMap<String, Double> loc = new HashMap<>();
loc.put("latitude", location.getLatitude());
loc.put("longitude", location.getLongitude());
loc.put("accuracy", (double) location.getAccuracy());
// Using NMEA Data to get MSL level altitude
if (mLastMslAltitude == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
loc.put("altitude", location.getAltitude());
} else {
loc.put("altitude", mLastMslAltitude);
}
loc.put("speed", (double) location.getSpeed());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
loc.put("speed_accuracy", (double) location.getSpeedAccuracyMetersPerSecond());
}
loc.put("heading", (double) location.getBearing());
loc.put("time", (double) location.getTime());
if (result != null) {
result.success(loc);
result = null;
}
if (events != null) {
events.success(loc);
} else {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mMessageListener = new OnNmeaMessageListener() {
@Override
public void onNmeaMessage(String message, long timestamp) {
if (message.startsWith("$")) {
String[] tokens = message.split(",");
String type = tokens[0];
// Parse altitude above sea level, Detailed description of NMEA string here
// http://aprs.gids.nl/nmea/#gga
if (type.startsWith("$GPGGA")) {
if (!tokens[9].isEmpty()) {
mLastMslAltitude = Double.parseDouble(tokens[9]);
}
}
}
}};
}
}
/**
* Sets up the location request. Android has two location request settings:
* {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
private void createLocationRequest() {
this.mLocationRequest = LocationRequest.create();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
this.mLocationRequest.setInterval(this.update_interval_in_milliseconds);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
this.mLocationRequest.setFastestInterval(this.fastest_update_interval_in_milliseconds);
this.mLocationRequest.setPriority(this.location_accuray);
this.mLocationRequest.setSmallestDisplacement(this.distanceFilter);
}
/**
* Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build
* a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking
* if a device has the needed location settings.
*/
private void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
this.locationPermissionState = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
return this.locationPermissionState == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
private boolean shouldShowRequestPermissionRationale() {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION);
}
public boolean checkServiceEnabled(final Result result) {
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = this.locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
result.error("SERVICE_STATUS_ERROR", "Location service status couldn't be determined", null);
return false;
}
if (gps_enabled || network_enabled) {
if (result != null) {
result.success(1);
}
return true;
} else {
if (result != null) {
result.success(0);
}
return false;
}
}
public void requestService(final Result result) {
if (this.checkServiceEnabled(null)) {
result.success(1);
return;
}
this.result = result;
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnFailureListener(activity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(activity, GPS_ENABLE_REQUEST);
} catch (IntentSender.SendIntentException sie) {
Log.i(METHOD_CHANNEL_NAME, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
result.error("SERVICE_STATUS_DISABLED",
"Failed to get location. Location services disabled", null);
}
}
});
}
public void startRequestingLocation() {
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(activity, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locationManager.addNmeaListener(mMessageListener);
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}).addOnFailureListener(activity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.i(METHOD_CHANNEL_NAME, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be "
+ "fixed here. Fix in Settings.";
Log.e(METHOD_CHANNEL_NAME, errorMessage);
}
}
});
}
@Override
public void onListen(Object arguments, final EventSink eventsSink) {
events = eventsSink;
if (!checkPermissions()) {
requestPermissions();
if (this.locationPermissionState == PackageManager.PERMISSION_DENIED) {
result.error("PERMISSION_DENIED",
"The user explicitly denied the use of location services for this app or location services are currently disabled in Settings.",
null);
}
}
startRequestingLocation();
}
@Override
public void onCancel(Object arguments) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
events = null;
}
}
| android/src/main/java/com/lyokone/location/LocationPlugin.java | package com.lyokone.location;
import android.Manifest;
import android.app.Activity;
import android.provider.Settings;
import android.content.IntentSender;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.content.Context;
import android.os.Build;
import android.os.Looper;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.Log;
import android.annotation.TargetApi;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.OnFailureListener;
import java.util.ArrayList;
import java.util.HashMap;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import io.flutter.plugin.common.PluginRegistry.ActivityResultListener;
/**
* LocationPlugin
*/
public class LocationPlugin implements MethodCallHandler, StreamHandler, PluginRegistry.ActivityResultListener {
private static final String STREAM_CHANNEL_NAME = "lyokone/locationstream";
private static final String METHOD_CHANNEL_NAME = "lyokone/location";
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final int GPS_ENABLE_REQUEST = 0x1001;
private final FusedLocationProviderClient mFusedLocationClient;
private final SettingsClient mSettingsClient;
private static LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private PluginRegistry.RequestPermissionsResultListener mPermissionsResultListener;
@TargetApi(Build.VERSION_CODES.N)
private OnNmeaMessageListener mMessageListener;
private Double mLastMslAltitude;
// Parameters of the request
private static long update_interval_in_milliseconds = 5000;
private static long fastest_update_interval_in_milliseconds = update_interval_in_milliseconds / 2;
private static Integer location_accuray = LocationRequest.PRIORITY_HIGH_ACCURACY;
private static float distanceFilter = 0f;
private EventSink events;
private Result result;
private int locationPermissionState;
private final Activity activity;
private boolean waitingForPermission = false;
private LocationManager locationManager;
private HashMap<Integer, Integer> mapFlutterAccuracy = new HashMap<>();
LocationPlugin(Activity activity) {
this.activity = activity;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(activity);
mSettingsClient = LocationServices.getSettingsClient(activity);
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
this.mapFlutterAccuracy.put(0, LocationRequest.PRIORITY_NO_POWER);
this.mapFlutterAccuracy.put(1, LocationRequest.PRIORITY_LOW_POWER);
this.mapFlutterAccuracy.put(2, LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
this.mapFlutterAccuracy.put(3, LocationRequest.PRIORITY_HIGH_ACCURACY);
this.mapFlutterAccuracy.put(4, LocationRequest.PRIORITY_HIGH_ACCURACY);
createLocationCallback();
createLocationRequest();
createPermissionsResultListener();
buildLocationSettingsRequest();
}
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), METHOD_CHANNEL_NAME);
LocationPlugin locationWithMethodChannel = new LocationPlugin(registrar.activity());
channel.setMethodCallHandler(locationWithMethodChannel);
registrar.addRequestPermissionsResultListener(locationWithMethodChannel.getPermissionsResultListener());
registrar.addActivityResultListener(locationWithMethodChannel);
final EventChannel eventChannel = new EventChannel(registrar.messenger(), STREAM_CHANNEL_NAME);
LocationPlugin locationWithEventChannel = new LocationPlugin(registrar.activity());
eventChannel.setStreamHandler(locationWithEventChannel);
registrar.addRequestPermissionsResultListener(locationWithEventChannel.getPermissionsResultListener());
}
@Override
public void onMethodCall(MethodCall call, final Result result) {
if (call.method.equals("changeSettings")) {
try {
this.location_accuray = this.mapFlutterAccuracy.get(call.argument("accuracy"));
this.update_interval_in_milliseconds = new Long((int) call.argument("interval"));
this.fastest_update_interval_in_milliseconds = this.update_interval_in_milliseconds / 2;
this.distanceFilter = new Float((double) call.argument("distanceFilter"));
createLocationCallback();
createLocationRequest();
createPermissionsResultListener();
buildLocationSettingsRequest();
result.success(1);
} catch(Exception e) {
result.error("CHANGE_SETTINGS_ERROR", "An unexcepted error happened during location settings change:" + e.getMessage(), null);
}
} else if (call.method.equals("getLocation")) {
this.result = result;
if (!checkPermissions()) {
requestPermissions();
} else {
startRequestingLocation();
}
} else if (call.method.equals("hasPermission")) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
result.success(1);
return;
}
if (checkPermissions()) {
result.success(1);
} else {
result.success(0);
}
} else if (call.method.equals("requestPermission")) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
result.success(1);
return;
}
this.waitingForPermission = true;
this.result = result;
requestPermissions();
} else if (call.method.equals("serviceEnabled")) {
checkServiceEnabled(result);
} else if (call.method.equals("requestService")) {
requestService(result);
} else {
result.notImplemented();
}
}
public PluginRegistry.RequestPermissionsResultListener getPermissionsResultListener() {
return mPermissionsResultListener;
}
private void createPermissionsResultListener() {
mPermissionsResultListener = new PluginRegistry.RequestPermissionsResultListener() {
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE && permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
if (waitingForPermission) {
waitingForPermission = false;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
result.success(1);
} else {
result.success(0);
}
result = null;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (result != null) {
startRequestingLocation();
} else if (events != null) {
startRequestingLocation();
}
} else {
if (!shouldShowRequestPermissionRationale()) {
if (result != null) {
result.error("PERMISSION_DENIED_NEVER_ASK", "Location permission denied forever- please open app settings", null);
} else if (events != null) {
events.error("PERMISSION_DENIED_NEVER_ASK", "Location permission denied forever - please open app settings", null);
events = null;
}
} else {
if (result != null) {
result.error("PERMISSION_DENIED", "Location permission denied", null);
} else if (events != null) {
events.error("PERMISSION_DENIED", "Location permission denied", null);
events = null;
}
}
}
return true;
}
return false;
}
};
}
@Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case GPS_ENABLE_REQUEST:
if (resultCode == Activity.RESULT_OK) {
this.result.success(1);
} else {
this.result.success(0);
}
break;
default:
return false;
}
return true;
}
/**
* Creates a callback for receiving location events.
*/
private void createLocationCallback() {
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
HashMap<String, Double> loc = new HashMap<>();
loc.put("latitude", location.getLatitude());
loc.put("longitude", location.getLongitude());
loc.put("accuracy", (double) location.getAccuracy());
// Using NMEA Data to get MSL level altitude
if (mLastMslAltitude == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
loc.put("altitude", location.getAltitude());
} else {
loc.put("altitude", mLastMslAltitude);
}
loc.put("speed", (double) location.getSpeed());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
loc.put("speed_accuracy", (double) location.getSpeedAccuracyMetersPerSecond());
}
loc.put("heading", (double) location.getBearing());
loc.put("time", (double) location.getTime());
if (result != null) {
result.success(loc);
result = null;
}
if (events != null) {
events.success(loc);
} else {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mMessageListener = new OnNmeaMessageListener() {
@Override
public void onNmeaMessage(String message, long timestamp) {
if (message.startsWith("$")) {
String[] tokens = message.split(",");
String type = tokens[0];
// Parse altitude above sea level, Detailed description of NMEA string here
// http://aprs.gids.nl/nmea/#gga
if (type.startsWith("$GPGGA")) {
if (!tokens[9].isEmpty()) {
mLastMslAltitude = Double.parseDouble(tokens[9]);
}
}
}
}};
}
}
/**
* Sets up the location request. Android has two location request settings:
* {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
* the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
* the AndroidManifest.xml.
* <p/>
* When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
* interval (5 seconds), the Fused Location Provider API returns location updates that are
* accurate to within a few feet.
* <p/>
* These settings are appropriate for mapping applications that show real-time location
* updates.
*/
private void createLocationRequest() {
this.mLocationRequest = LocationRequest.create();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
this.mLocationRequest.setInterval(this.update_interval_in_milliseconds);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
this.mLocationRequest.setFastestInterval(this.fastest_update_interval_in_milliseconds);
this.mLocationRequest.setPriority(this.location_accuray);
this.mLocationRequest.setSmallestDisplacement(this.distanceFilter);
}
/**
* Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build
* a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking
* if a device has the needed location settings.
*/
private void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
/**
* Return the current state of the permissions needed.
*/
private boolean checkPermissions() {
this.locationPermissionState = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
return this.locationPermissionState == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
private boolean shouldShowRequestPermissionRationale() {
return ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION);
}
public boolean checkServiceEnabled(final Result result) {
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = this.locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = this.locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
result.error("SERVICE_STATUS_ERROR", "Location service status couldn't be determined", null);
return false;
}
if (gps_enabled || network_enabled) {
if (result != null) {
result.success(1);
}
return true;
} else {
if (result != null) {
result.success(0);
}
return false;
}
}
public void requestService(final Result result) {
if (this.checkServiceEnabled(null)) {
result.success(1);
return;
}
this.result = result;
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnFailureListener(activity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(activity, GPS_ENABLE_REQUEST);
} catch (IntentSender.SendIntentException sie) {
Log.i(METHOD_CHANNEL_NAME, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
result.error("SERVICE_STATUS_DISABLED",
"Failed to get location. Location services disabled", null);
}
}
});
}
public void startRequestingLocation() {
mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(activity, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locationManager.addNmeaListener(mMessageListener);
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}).addOnFailureListener(activity, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sie) {
Log.i(METHOD_CHANNEL_NAME, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be "
+ "fixed here. Fix in Settings.";
Log.e(METHOD_CHANNEL_NAME, errorMessage);
}
}
});
}
@Override
public void onListen(Object arguments, final EventSink eventsSink) {
events = eventsSink;
if (!checkPermissions()) {
requestPermissions();
if (this.locationPermissionState == PackageManager.PERMISSION_DENIED) {
result.error("PERMISSION_DENIED",
"The user explicitly denied the use of location services for this app or location services are currently disabled in Settings.",
null);
}
}
startRequestingLocation();
}
@Override
public void onCancel(Object arguments) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
events = null;
}
}
| Try to fix #156
| android/src/main/java/com/lyokone/location/LocationPlugin.java | Try to fix #156 |
|
Java | mit | d325b72b1f068682d954034343c17b496d8abd22 | 0 | antorof/Giftask | package es.trigit.gitftask.Vistas;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.Display;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Georgevik on 24/03/15.
*/
public class CameraPreview extends SurfaceView {
private static final String TAG = "CameraPreview";
private Context context;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.context = context;
mCamera = camera;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Size size1 = getMejorSize();
setMeasuredDimension(size1.height, size1.width);
}
private Size getMejorSize() {
Camera.Size mejorSize;
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
List<Camera.Size> supportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
List<Camera.Size> posiblesSizes = new ArrayList<>();
Point point = new Point();
display.getSize(point);
int witdhWindow = point.x;
int heightWindow = point.y;
double ratioPantalla = witdhWindow * 1.0 / heightWindow * 1.0;
double mejorRatioDiferencia = Double.MAX_VALUE;
double diferenciaRatio;
//Cogemos los que tengan un size como el de la pantalla
for (Camera.Size size : supportedPreviewSizes) {
if (size.height == witdhWindow) {
posiblesSizes.add(size);
}
}
//Si no encontramos ningun size obtenemos los sizes mayores que el ancho de pantalla
if (posiblesSizes.isEmpty()) {
for (Camera.Size size : supportedPreviewSizes) {
if (size.height > witdhWindow) {
posiblesSizes.add(size);
}
}
}
//Si no hay ningun size mayor al ancho de pantalla, devolvemos el primer size que se soporta
if (posiblesSizes.isEmpty()) {
posiblesSizes = supportedPreviewSizes;
}
//Obtenemos el que mejor ratio tenga de entre los posibles
mejorRatioDiferencia = Double.MAX_VALUE;
mejorSize = posiblesSizes.get(0);
for (Camera.Size size : posiblesSizes) {
double ratioA = size.height * 1.0 / size.width * 1.0;
diferenciaRatio = Math.abs(ratioA - ratioPantalla);
if (diferenciaRatio < mejorRatioDiferencia) {
mejorSize = size;
}
}
//ajustamos el mejor size al ancho de la panalla
double ratio =mejorSize.width*1.0/mejorSize.height * 1.0;
mejorSize.height = witdhWindow;
mejorSize.width = (int) (heightWindow/ratio);
return mejorSize;
}
} | app/src/main/java/es/trigit/gitftask/Vistas/CameraPreview.java | package es.trigit.gitftask.Vistas;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.view.Display;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Georgevik on 24/03/15.
*/
public class CameraPreview extends SurfaceView {
private static final String TAG = "CameraPreview";
private Context context;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.context = context;
mCamera = camera;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Size size1 = getMejorSize();
setMeasuredDimension(size1.height, size1.width);
}
private Size getMejorSize() {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
List<Camera.Size> supportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
List<Camera.Size> posiblesSizes = new ArrayList<>();
Point point = new Point();
display.getSize(point);
int witdhWindow = point.x;
int heightWindow = point.y;
//Cogemos los que tengan un size como el de la pantalla
for (Camera.Size size : supportedPreviewSizes) {
if (size.height == witdhWindow) {
posiblesSizes.add(size);
}
}
//Si no encontramos ningun size obtenemos los sizes mayores que el ancho de pantalla
if (posiblesSizes.isEmpty()) {
for (Camera.Size size : supportedPreviewSizes) {
if (size.height > witdhWindow) {
posiblesSizes.add(size);
}
}
}
//Si no hay ningun size mayor al ancho de pantalla, devolvemos el primer size que se soporta
if (posiblesSizes.isEmpty())
return supportedPreviewSizes.get(0);
//Obtenemos el que mejor ratio tenga de entre los posibles
double mejorRatioDiferencia = Double.MAX_VALUE;
Camera.Size mejorSize = posiblesSizes.get(0);
double diferenciaRatio;
for (Camera.Size size : posiblesSizes) {
double ratioA = size.height * 1.0 / size.width * 1.0;
double ratioB = witdhWindow * 1.0 / heightWindow * 1.0;
diferenciaRatio = Math.abs(ratioA - ratioB);
if (diferenciaRatio < mejorRatioDiferencia) {
mejorSize = size;
}
}
return mejorSize;
}
} | Preview de camara arreglado
| app/src/main/java/es/trigit/gitftask/Vistas/CameraPreview.java | Preview de camara arreglado |
|
Java | mit | 0e0af134d70030be0263022954baeb4e54e0a1fe | 0 | ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces,ButterFaces/ButterFaces | package de.larmic.butterfaces.component.renderkit.html_basic.text;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.ConverterException;
import javax.faces.render.FacesRenderer;
import de.larmic.butterfaces.component.html.text.HtmlTreeBox;
import de.larmic.butterfaces.component.partrenderer.RenderUtils;
import de.larmic.butterfaces.component.partrenderer.StringUtils;
import de.larmic.butterfaces.component.renderkit.html_basic.text.part.TrivialComponentsEntriesNodePartRenderer;
import de.larmic.butterfaces.model.tree.Node;
@FacesRenderer(componentFamily = HtmlTreeBox.COMPONENT_FAMILY, rendererType = HtmlTreeBox.RENDERER_TYPE)
public class TreeBoxRenderer extends AbstractTextRenderer<HtmlTreeBox> {
private final Map<Integer, Node> cachedNodes = new HashMap<>();
@Override
protected boolean encodeReadonly() {
return false;
}
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component, "butter-component-treebox");
}
@Override
protected void encodeEnd(UIComponent component, ResponseWriter writer) throws IOException {
final HtmlTreeBox treeBox = (HtmlTreeBox) component;
final Node rootNode = treeBox.getValues();
final List<Node> nodes = treeBox.isHideRootNode() ? rootNode.getSubNodes() : Arrays.asList(rootNode);
this.initCachedNodes(nodes, 0);
writer.startElement("script", component);
writer.writeText("jQuery(function () {\n", null);
writer.writeText("var entries_" + treeBox.getClientId().replace(":", "_") + " = " + new TrivialComponentsEntriesNodePartRenderer().renderEntriesAsJSON(nodes, Collections.<String>emptyList(), cachedNodes)+";\n", null);
final String jQueryBySelector = RenderUtils.createJQueryBySelector(component.getClientId(), "input");
final String pluginCall = createJQueryPluginCallTrivial(treeBox);
writer.writeText("var trivialTree = " + jQueryBySelector + pluginCall + ";", null);
writer.writeText("});", null);
writer.endElement("script");
}
@Override
protected void encodeInnerEnd(UIComponent component, ResponseWriter writer) throws IOException {
final HtmlTreeBox treeBox = (HtmlTreeBox) component;
if (treeBox.isReadonly()) {
writer.startElement(ELEMENT_DIV, component);
writer.writeAttribute("class", "butter-component-value", null);
super.encodeSuperEnd(FacesContext.getCurrentInstance(), component);
writer.endElement(ELEMENT_DIV);
}
}
@Override
public Object getConvertedValue(final FacesContext context,
final UIComponent component,
final Object submittedValue) throws ConverterException {
if (submittedValue == null || "".equals(submittedValue)) {
return null;
}
final String newValue = (String) submittedValue;
final Integer selectedIndex = Integer.valueOf(newValue);
return cachedNodes.get(selectedIndex);
}
private String createJQueryPluginCallTrivial(final HtmlTreeBox treeBox) {
final StringBuilder jQueryPluginCall = new StringBuilder();
Integer selectedEntryId = null;
Node selectedNode = null;
if (treeBox.getValue() != null) {
for (Integer index : cachedNodes.keySet()) {
final Node node = cachedNodes.get(index);
if (treeBox.getValue().equals(node)) {
selectedEntryId = index;
selectedNode = node;
break;
}
}
}
final String editable = TrivialComponentsEntriesNodePartRenderer.getEditingMode(treeBox);
jQueryPluginCall.append("TrivialTreeComboBox({");
jQueryPluginCall.append("\n allowFreeText: true,");
jQueryPluginCall.append("\n inputTextProperty: 'title',");
if (StringUtils.isNotEmpty(treeBox.getPlaceholder())) {
jQueryPluginCall.append("\n emptyEntry: {");
jQueryPluginCall.append("\n \"title\": \"" + treeBox.getPlaceholder() + "\"");
//jQueryPluginCall.append("\n \"imageUrl\": \"-\",");
//jQueryPluginCall.append("\n \"additionalInfo\": \"\"");
jQueryPluginCall.append("\n },");
}
jQueryPluginCall.append("\n editingMode: '" + editable + "',");
if (selectedEntryId != null && selectedNode != null) {
jQueryPluginCall.append("\n selectedEntry: " + new TrivialComponentsEntriesNodePartRenderer().renderNode(Collections.<String>emptyList(), cachedNodes, selectedEntryId, selectedNode) + ",");
}
jQueryPluginCall.append("\n templates: ['" + TreeRenderer.DEFAULT_TEMPLATE + "'],");
jQueryPluginCall.append("\n entries: entries_" + treeBox.getClientId().replace(":", "_"));
jQueryPluginCall.append("});");
return jQueryPluginCall.toString();
}
private int initCachedNodes(final List<Node> nodes,
final int index) {
int newIndex = index;
for (Node node : nodes) {
cachedNodes.put(newIndex, node);
newIndex++;
if (node.getSubNodes().size() > 0) {
newIndex = initCachedNodes(node.getSubNodes(), newIndex);
}
}
return newIndex;
}
}
| components/src/main/java/de/larmic/butterfaces/component/renderkit/html_basic/text/TreeBoxRenderer.java | package de.larmic.butterfaces.component.renderkit.html_basic.text;
import de.larmic.butterfaces.component.html.text.HtmlTreeBox;
import de.larmic.butterfaces.component.partrenderer.RenderUtils;
import de.larmic.butterfaces.component.partrenderer.StringUtils;
import de.larmic.butterfaces.component.renderkit.html_basic.text.part.TrivialComponentsEntriesNodePartRenderer;
import de.larmic.butterfaces.model.tree.Node;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.ConverterException;
import javax.faces.render.FacesRenderer;
import java.io.IOException;
import java.util.*;
@FacesRenderer(componentFamily = HtmlTreeBox.COMPONENT_FAMILY, rendererType = HtmlTreeBox.RENDERER_TYPE)
public class TreeBoxRenderer extends AbstractTextRenderer<HtmlTreeBox> {
private final Map<Integer, Node> cachedNodes = new HashMap<>();
@Override
protected boolean encodeReadonly() {
return false;
}
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component, "butter-component-treebox");
}
@Override
protected void encodeEnd(UIComponent component, ResponseWriter writer) throws IOException {
final HtmlTreeBox treeBox = (HtmlTreeBox) component;
final Node rootNode = treeBox.getValues();
final List<Node> nodes = treeBox.isHideRootNode() ? rootNode.getSubNodes() : Arrays.asList(rootNode);
this.initCachedNodes(nodes, 0);
writer.startElement("script", component);
writer.writeText("jQuery(function () {\n", null);
writer.writeText("var entries_" + treeBox.getClientId().replace(":", "_") + " = " + new TrivialComponentsEntriesNodePartRenderer().renderEntriesAsJSON(nodes, Collections.<String>emptyList(), cachedNodes)+";\n", null);
final String jQueryBySelector = RenderUtils.createJQueryBySelector(component.getClientId(), "input");
final String pluginCall = createJQueryPluginCallTrivial(treeBox);
writer.writeText("var trivialTree = " + jQueryBySelector + pluginCall + ";", null);
writer.writeText("});", null);
writer.endElement("script");
}
@Override
protected void encodeInnerEnd(UIComponent component, ResponseWriter writer) throws IOException {
final HtmlTreeBox treeBox = (HtmlTreeBox) component;
if (treeBox.isReadonly()) {
writer.startElement(ELEMENT_DIV, component);
writer.writeAttribute("class", "butter-component-value", null);
super.encodeSuperEnd(FacesContext.getCurrentInstance(), component);
writer.endElement(ELEMENT_DIV);
}
}
@Override
public Object getConvertedValue(final FacesContext context,
final UIComponent component,
final Object submittedValue) throws ConverterException {
if (submittedValue == null || "".equals(submittedValue)) {
return null;
}
final String newValue = (String) submittedValue;
final Integer selectedIndex = Integer.valueOf(newValue);
return cachedNodes.get(selectedIndex);
}
private String createJQueryPluginCallTrivial(final HtmlTreeBox treeBox) {
final StringBuilder jQueryPluginCall = new StringBuilder();
Integer selectedEntryId = null;
Node selectedNode = null;
if (treeBox.getValue() != null) {
for (Integer index : cachedNodes.keySet()) {
final Node node = cachedNodes.get(index);
if (treeBox.getValue().equals(node)) {
selectedEntryId = index;
selectedNode = node;
break;
}
}
}
final String editable = TrivialComponentsEntriesNodePartRenderer.getEditingMode(treeBox);
jQueryPluginCall.append("TrivialTreeComboBox({");
jQueryPluginCall.append("\n allowFreeText: true,");
if (StringUtils.isNotEmpty(treeBox.getPlaceholder())) {
jQueryPluginCall.append("\n emptyEntry: {");
jQueryPluginCall.append("\n \"title\": \"" + treeBox.getPlaceholder() + "\"");
//jQueryPluginCall.append("\n \"imageUrl\": \"-\",");
//jQueryPluginCall.append("\n \"additionalInfo\": \"\"");
jQueryPluginCall.append("\n },");
}
jQueryPluginCall.append("\n editingMode: '" + editable + "',");
if (selectedEntryId != null && selectedNode != null) {
jQueryPluginCall.append("\n selectedEntry: " + new TrivialComponentsEntriesNodePartRenderer().renderNode(Collections.<String>emptyList(), cachedNodes, selectedEntryId, selectedNode) + ",");
}
jQueryPluginCall.append("\n templates: ['" + TreeRenderer.DEFAULT_TEMPLATE + "'],");
jQueryPluginCall.append("\n entries: entries_" + treeBox.getClientId().replace(":", "_"));
jQueryPluginCall.append("});");
return jQueryPluginCall.toString();
}
private int initCachedNodes(final List<Node> nodes,
final int index) {
int newIndex = index;
for (Node node : nodes) {
cachedNodes.put(newIndex, node);
newIndex++;
if (node.getSubNodes().size() > 0) {
newIndex = initCachedNodes(node.getSubNodes(), newIndex);
}
}
return newIndex;
}
}
| BUT-412 fixed autocomplete
| components/src/main/java/de/larmic/butterfaces/component/renderkit/html_basic/text/TreeBoxRenderer.java | BUT-412 fixed autocomplete |
|
Java | mit | 915801fe7bb82fa7767ce05b592eb7da7d095a5e | 0 | relayrides/pushy,urbanairship/pushy,relayrides/pushy,urbanairship/pushy,relayrides/pushy,urbanairship/pushy | package com.relayrides.pushy;
import java.util.ArrayList;
import java.util.LinkedList;
public class SentNotificationBuffer<E extends ApnsPushNotification> {
private final LinkedList<SendableApnsPushNotification<E>> buffer;
private final int capacity;
public SentNotificationBuffer(final int capacity) {
this.buffer = new LinkedList<SendableApnsPushNotification<E>>();
this.capacity = capacity;
}
public synchronized void addSentNotification(SendableApnsPushNotification<E> notification) {
this.buffer.addLast(notification);
while (this.buffer.size() > this.capacity) {
this.buffer.removeFirst();
}
}
public synchronized E getFailedNotificationAndClearQueue(final int failedNotificationId, final PushManager<E> pushManager) {
while (this.buffer.getFirst().isSequentiallyBefore(failedNotificationId)) {
this.buffer.removeFirst();
}
final E failedNotification = this.buffer.getFirst().getNotificationId() == failedNotificationId ?
this.buffer.removeFirst().getPushNotification() : null;
{
final ArrayList<E> unsentNotifications = new ArrayList<E>(this.buffer.size());
for (final SendableApnsPushNotification<E> sentNotification : this.buffer) {
unsentNotifications.add(sentNotification.getPushNotification());
}
pushManager.enqueueAllNotifications(unsentNotifications);
}
this.buffer.clear();
return failedNotification;
}
}
| src/main/java/com/relayrides/pushy/SentNotificationBuffer.java | package com.relayrides.pushy;
import java.util.ArrayList;
import java.util.LinkedList;
public class SentNotificationBuffer<E extends ApnsPushNotification> {
private final LinkedList<SendableApnsPushNotification<E>> buffer;
private final int capacity;
public SentNotificationBuffer(final int capacity) {
this.buffer = new LinkedList<SendableApnsPushNotification<E>>();
this.capacity = capacity;
}
public synchronized void addSentNotification(SendableApnsPushNotification<E> notification) {
this.buffer.addLast(notification);
while (buffer.size() > this.capacity) {
this.buffer.removeFirst();
}
}
public synchronized E getFailedNotificationAndClearQueue(final int failedNotificationId, final PushManager<E> pushManager) {
while (this.buffer.getFirst().isSequentiallyBefore(failedNotificationId)) {
this.buffer.removeFirst();
}
final E failedNotification = this.buffer.getFirst().getNotificationId() == failedNotificationId ?
this.buffer.removeFirst().getPushNotification() : null;
{
final ArrayList<E> unsentNotifications = new ArrayList<E>(this.buffer.size());
for (final SendableApnsPushNotification<E> sentNotification : this.buffer) {
unsentNotifications.add(sentNotification.getPushNotification());
}
pushManager.enqueueAllNotifications(unsentNotifications);
}
this.buffer.clear();
return failedNotification;
}
}
| Minor: added an explicit "this".
| src/main/java/com/relayrides/pushy/SentNotificationBuffer.java | Minor: added an explicit "this". |
|
Java | epl-1.0 | 99aa6895d741cdd09a4c2225cfb1111dc4897b14 | 0 | ibm-messaging/iot-device-samples,ibm-messaging/iot-device-samples,amprasanna/iot-device-samples,ibm-messaging/iot-device-samples,amprasanna/iot-device-samples,amprasanna/iot-device-samples | /**
*****************************************************************************
* Copyright (c) 2016 IBM Corporation and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Amit M Mangalvedkar - Initial Contribution
* Sathiskumar Palaniappan - Initial Contribution
*****************************************************************************
*/
package com.ibm.iotf.sample.client.device;
import java.io.IOException;
import java.util.Properties;
import com.google.gson.JsonObject;
import com.ibm.iotf.client.api.APIClient.ContentType;
import com.ibm.iotf.client.device.DeviceClient;
import com.ibm.iotf.sample.client.SystemObject;
/**
*
* This sample shows how a device can publish events
* using HTTP(s) to IBM Watson IoT Platform
*
*/
public class HttpDeviceEventPublish {
private final static String PROPERTIES_FILE_NAME = "/device.properties";
public static void main(String[] args) throws Exception {
/**
* Load device properties
*/
Properties props = new Properties();
try {
props.load(HttpDeviceEventPublish.class.getResourceAsStream(PROPERTIES_FILE_NAME));
} catch (IOException e1) {
System.err.println("Not able to read the properties file, exiting..");
System.exit(-1);
}
DeviceClient myClient = null;
//APIClient myClient = null;
try {
//Instantiate the class by passing the properties file
myClient = new DeviceClient(props);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
SystemObject obj = new SystemObject();
/**
* Publishes the process load event for every 1 second
*/
while(true) {
try {
//Generate a JSON object of the event to be published
JsonObject event = new JsonObject();
event.addProperty("name", SystemObject.getName());
event.addProperty("cpu", obj.getProcessCpuLoad());
event.addProperty("mem", obj.getMemoryUsed());
boolean response = myClient.api().publishDeviceEventOverHTTP("blink", event, ContentType.json);
if(response == true)
System.out.println("Published Device Event Successfully!");
else
System.out.println("Failed Publishing Device Event!");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| java/device-samples/src/main/java/com/ibm/iotf/sample/client/device/HttpDeviceEventPublish.java | /**
*****************************************************************************
* Copyright (c) 2016 IBM Corporation and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Amit M Mangalvedkar - Initial Contribution
* Sathiskumar Palaniappan - Initial Contribution
*****************************************************************************
*/
package com.ibm.iotf.sample.client.device;
import java.io.IOException;
import java.util.Properties;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.ibm.iotf.client.api.APIClient;
import com.ibm.iotf.client.device.DeviceClient;
import com.ibm.iotf.sample.client.SystemObject;
/**
*
* This sample shows how a device can publish events
* using HTTP(s) to IBM Watson IoT Platform
*
*/
public class HttpDeviceEventPublish {
private final static String PROPERTIES_FILE_NAME = "/device.properties";
public static void main(String[] args) throws Exception {
/**
* Load device properties
*/
Properties props = new Properties();
try {
props.load(HttpDeviceEventPublish.class.getResourceAsStream(PROPERTIES_FILE_NAME));
} catch (IOException e1) {
System.err.println("Not able to read the properties file, exiting..");
System.exit(-1);
}
DeviceClient myClient = null;
//APIClient myClient = null;
try {
//Instantiate the class by passing the properties file
myClient = new DeviceClient(props);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
SystemObject obj = new SystemObject();
/**
* Publishes the process load event for every 1 second
*/
while(true) {
try {
//Generate a JSON object of the event to be published
JsonObject event = new JsonObject();
event.addProperty("name", SystemObject.getName());
event.addProperty("cpu", obj.getProcessCpuLoad());
event.addProperty("mem", obj.getMemoryUsed());
boolean response = myClient.api().publishDeviceEventOverHTTP("blink", event,"xml");
if(response == true)
System.out.println("Published Device Event Successfully!");
else
System.out.println("Failed Publishing Device Event!");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| Added enum instead of string for contenttype
| java/device-samples/src/main/java/com/ibm/iotf/sample/client/device/HttpDeviceEventPublish.java | Added enum instead of string for contenttype |
|
Java | epl-1.0 | d321f743763fb17e985c0fbbe5a83a05f1ee9204 | 0 | CA-APM/ca-apm-fieldpack-asm,CA-APM/ca-apm-fieldpack-asm | package com.wily.introscope.epagent;
import java.util.Properties;
import com.ca.apm.swat.epaplugins.utils.AsmProperties;
import com.wily.util.feedback.IModuleFeedbackChannel;
import com.wily.util.feedback.SeverityLevel;
import com.wily.util.feedback.SystemOutFeedbackChannel;
/**
* EPAgent utilities.
*
* @author Andreas Reiss - CA Wily Professional Service
*
*/
public class EpaUtils {
private static Properties properties;
private static IModuleFeedbackChannel channel = null;
private static boolean started = false;
public static String PREFERENCES_KEY = EPAConfig.kPrefsKey2;
/**
* Cannot instantiate.
*/
private EpaUtils() {
}
/**
* Get the logging component.
* @return the logging component
*/
public static IModuleFeedbackChannel getFeedback() {
if (null == channel) {
if (EPAgent.GetInstance() == null) {
channel = new SystemOutFeedbackChannel(
AsmProperties.ASM_PRODUCT_NAME_SHORT + " EPA",
SeverityLevel.INFO);
} else {
channel = EPAgent.GetFeedback();
}
if (!started && (null != getProperties())) {
String version = getProperties().getProperty(AsmProperties.VERSION);
channel.info("Started field pack " + AsmProperties.ASM_PRODUCT_NAME
+ ", version " + version);
started = true;
}
}
return channel;
}
/**
* Replace unsupported characters in metric name.
* @param rawMetric raw metric name
* @return cleansed metric name
*/
public static String fixMetricName(String rawMetric) {
/*
StringFilter normalizer = null;
try {
normalizer = TextNormalizer.getNormalizationStringFilter();
} catch (ClassNotFoundException e) {
EpaUtils.getFeedback().error(e.getMessage());
throw new InitializationError(
AsmMessages.getMessage(AsmMessages.NORMALIZER_INFO, e.getMessage()));
}
String metricKeyNormalized = normalizer.filter(rawMetric);
Pattern pattern = Pattern.compile(AsmProperties.JSON_PATTERN);
String fixedMetric =
pattern.matcher(metricKeyNormalized).replaceAll(AsmProperties.EMPTY_STRING);
*/
if (null == rawMetric) {
return null;
}
String fixedMetric = rawMetric;
// replace all but the last occurence of ':'
int lastColon = fixedMetric.lastIndexOf(':');
if (lastColon > -1) {
while (true) {
int otherColon = fixedMetric.indexOf(':');
if ((otherColon == lastColon) || (otherColon == -1)) {
break;
}
fixedMetric = fixedMetric.replaceFirst(":", "_");
}
}
return fixedMetric.replace("\\", "-")
//.replace("/", "-")
.replace(",", "_")
.replace(";", "-")
.replace("&", "_");
}
/**
* Replace unsupported characters in metric value.
* @param rawMetric raw metric name
* @return cleansed metric name
*/
public static String fixMetricValue(String rawMetric) {
if (null == rawMetric) {
return null;
}
return rawMetric.replace("\\", "-")
//.replace("/", "-")
.replace(",", "_")
.replace(";", "-")
.replace("&", "_")
.replace(":", "_")
.replace("\"", "'");
}
/**
* Get the global properties.
* @return the properties
*/
public static Properties getProperties() {
return properties;
}
/**
* Set the global properties.
* @param properties the properties
*/
public static void setProperties(Properties properties) {
EpaUtils.properties = properties;
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns the default value argument if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns null if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static String getProperty(String key) {
return properties.getProperty(key);
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns null if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static boolean getBooleanProperty(String key) {
return Boolean.getBoolean(properties.getProperty(key));
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns the default value argument if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static boolean getBooleanProperty(String key, boolean defaultValue) {
if (properties.containsKey(key)) {
return Boolean.valueOf(properties.getProperty(key));
}
return defaultValue;
}
/**
* Returns the name of the encoding (e.g. UTF_8) to use.
* @return name of the encoding (default: UTF_8)
*/
public static String getEncoding() {
return getProperty(AsmProperties.ENCODING, "UTF-8");
}
}
| asm-monitor/src/main/java/com/wily/introscope/epagent/EpaUtils.java | package com.wily.introscope.epagent;
import java.util.Properties;
import com.ca.apm.swat.epaplugins.utils.AsmProperties;
import com.wily.util.feedback.IModuleFeedbackChannel;
import com.wily.util.feedback.SeverityLevel;
import com.wily.util.feedback.SystemOutFeedbackChannel;
/**
* EPAgent utilities.
*
* @author Andreas Reiss - CA Wily Professional Service
*
*/
public class EpaUtils {
private static Properties properties;
private static IModuleFeedbackChannel channel = null;
private static boolean started = false;
public static String PREFERENCES_KEY = EPAConfig.kPrefsKey2;
/**
* Cannot instantiate.
*/
private EpaUtils() {
}
/**
* Get the logging component.
* @return the logging component
*/
public static IModuleFeedbackChannel getFeedback() {
if (null == channel) {
if (EPAgent.GetInstance() == null) {
channel = new SystemOutFeedbackChannel(
AsmProperties.ASM_PRODUCT_NAME_SHORT + " EPA",
SeverityLevel.INFO);
} else {
channel = EPAgent.GetFeedback();
}
if (!started && (null != getProperties())) {
String version = getProperties().getProperty(AsmProperties.VERSION);
channel.info("Started field pack " + AsmProperties.ASM_PRODUCT_NAME
+ ", version " + version);
started = true;
}
}
return channel;
}
/**
* Replace unsupported characters in metric name.
* @param rawMetric raw metric name
* @return cleansed metric name
*/
public static String fixMetricName(String rawMetric) {
/*
StringFilter normalizer = null;
try {
normalizer = TextNormalizer.getNormalizationStringFilter();
} catch (ClassNotFoundException e) {
EpaUtils.getFeedback().error(e.getMessage());
throw new InitializationError(
AsmMessages.getMessage(AsmMessages.NORMALIZER_INFO, e.getMessage()));
}
String metricKeyNormalized = normalizer.filter(rawMetric);
Pattern pattern = Pattern.compile(AsmProperties.JSON_PATTERN);
String fixedMetric =
pattern.matcher(metricKeyNormalized).replaceAll(AsmProperties.EMPTY_STRING);
*/
if (null == rawMetric) {
return null;
}
String fixedMetric = rawMetric;
// replace all but the last occurence of ':'
int lastColon = fixedMetric.lastIndexOf(':');
if (lastColon > -1) {
while (true) {
int otherColon = fixedMetric.indexOf(':');
if ((otherColon == lastColon) || (otherColon == -1)) {
break;
}
fixedMetric = fixedMetric.replaceFirst(":", "_");
}
}
return fixedMetric.replace("\\", "-")
//.replace("/", "-")
.replace(",", "_")
.replace(";", "-")
.replace("&", "_");
}
/**
* Replace unsupported characters in metric value.
* @param rawMetric raw metric name
* @return cleansed metric name
*/
public static String fixMetricValue(String rawMetric) {
if (null == rawMetric) {
return null;
}
return rawMetric.replace("\\", "-")
//.replace("/", "-")
.replace(",", "_")
.replace(";", "-")
.replace("&", "_")
.replace(":", "_");
}
/**
* Get the global properties.
* @return the properties
*/
public static Properties getProperties() {
return properties;
}
/**
* Set the global properties.
* @param properties the properties
*/
public static void setProperties(Properties properties) {
EpaUtils.properties = properties;
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns the default value argument if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns null if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static String getProperty(String key) {
return properties.getProperty(key);
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns null if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static boolean getBooleanProperty(String key) {
return Boolean.getBoolean(properties.getProperty(key));
}
/**
* Searches for the property with the specified key in the global property list.
* The method returns the default value argument if the property is not found.
* @param key the property key (name)
* @param defaultValue the default value
* @return the value in this property list with the specified key value.
*/
public static boolean getBooleanProperty(String key, boolean defaultValue) {
if (properties.containsKey(key)) {
return Boolean.valueOf(properties.getProperty(key));
}
return defaultValue;
}
/**
* Returns the name of the encoding (e.g. UTF_8) to use.
* @return name of the encoding (default: UTF_8)
*/
public static String getEncoding() {
return getProperty(AsmProperties.ENCODING, "UTF-8");
}
}
| replace double quotes in metric names
| asm-monitor/src/main/java/com/wily/introscope/epagent/EpaUtils.java | replace double quotes in metric names |
|
Java | agpl-3.0 | 523f88b1bb0b27073e8055a635044bac8a85de47 | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package imcode.server ;
import org.apache.oro.util.* ;
import org.apache.oro.text.* ;
import org.apache.oro.text.regex.* ;
import org.apache.oro.text.perl.* ;
import java.sql.*;
import java.sql.Date ;
import java.io.*;
import java.util.*;
import imcode.server.* ;
import java.text.Collator ;
import java.text.SimpleDateFormat ;
import java.net.URL ;
import java.net.MalformedURLException ;
import imcode.util.log.* ;
/**
Main services for the Imcode Net Server.
Made final, since only a complete and utter moron would want to extend it.
**/
final public class IMCService implements IMCServiceInterface, IMCConstants {
private class FileCache {
private final int m_FileCacheSize = 50 ;
private CacheLRU fileCache = new CacheLRU(m_FileCacheSize) ;
/**
Fetch a file from the cache, if it hasn't changed on disc.
*/
synchronized private String getCachedFileString(String filename) throws IOException {
return getCachedFileString(new File(filename)) ;
}
/**
Fetch a file from the cache, if it hasn't changed on disc.
*/
synchronized String getCachedFileString(File file) throws IOException {
if (m_FileCacheSize > 0) {
Object[] file_and_date = (Object[])(fileCache.getElement(file)) ; // Get the cached file, if any.
if (file_and_date == null || file.lastModified() > ((Long)file_and_date[1]).longValue() ) {
// No (new) file found?
String temp = loadFile(file).toString() ; // Load it.
fileCache.addElement(file, new Object[] {temp,new Long(System.currentTimeMillis())}) ; // Cache it.
return temp ;
}
return (String)file_and_date[0] ;
} else {
return loadFile(file).toString() ;
}
}
}
private final imcode.server.InetPoolManager m_conPool ; // inet pool of connections
private String m_TemplateHome ; // template home
private String m_IncludePath ;
private int m_DefaultHomePage ; // default home page
private String m_ServletUrl ; // servlet url
private String m_ImageFolder ; // image folder
private String m_Language = "" ; // language
private String m_serverName = "" ; // servername
private SystemData sysData ;
private ExternalDocType m_ExDoc[] ;
private String m_SessionCounterDate = "" ;
private int m_SessionCounter = 0 ;
private int m_NoOfTemplates ;
private FileCache fileCache = new FileCache() ;
private final static Perl5Util perl5util = new Perl5Util() ; // Internally synchronized
private static Pattern OBSOLETE_MENU_PATTERN = null ;
private static Pattern HASHTAG_PATTERN = null ;
private static Pattern HASHTAGNUMBER_PATTERN = null ;
private static Pattern MENU_PATTERN = null ;
private static Pattern MENULOOP_PATTERN = null ;
private static Pattern MENUITEM_PATTERN = null ;
private static Pattern MENUITEMHIDE_PATTERN = null ;
private static Pattern MENUITEMHIDETAG_PATTERN = null ;
private static Pattern IMCMS_TAG_PATTERN = null ;
private static Pattern IMCMS_TAG_ATTRIBUTES_PATTERN = null ;
private static Pattern HTML_PREBODY_PATTERN = null ;
private static Pattern HTML_POSTBODY_PATTERN = null ;
private static Pattern TR_START_PATTERN = null ;
private static Pattern TR_STOP_PATTERN = null ;
private static Pattern TD_START_PATTERN = null ;
private static Pattern TD_STOP_PATTERN = null ;
private static Pattern MENU_NO_PATTERN = null ;
private static Pattern HTML_TAG_PATTERN = null ;
private Log log = Log.getLog("server") ;
static {
Perl5Compiler patComp = new Perl5Compiler() ;
try {
OBSOLETE_MENU_PATTERN = patComp.compile("[\\r\\n]\\s*menu\\s+no=(\\d+)\\s+rows=(\\d+)\\s+table_col=(\\d+)\\s*",Perl5Compiler.READ_ONLY_MASK) ;
// newline menu no=123456 rows=123456 table_col=123456
HASHTAG_PATTERN = patComp.compile("#[^#\"<> \\t\\r\\n]+#",Perl5Compiler.READ_ONLY_MASK) ;
// # none of the above #
HASHTAGNUMBER_PATTERN = patComp.compile("(\\d+)#$", Perl5Compiler.READ_ONLY_MASK) ;
// 123456#
MENU_PATTERN = patComp.compile("<\\?imcms:menu(?:\\s+no=\"(\\d+)\")?\\?>(.*?)<\\?\\/imcms:menu\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENULOOP_PATTERN = patComp.compile("<\\?imcms:menuloop\\?>(.*?)<\\?\\/imcms:menuloop\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEM_PATTERN = patComp.compile("<\\?imcms:menuitem\\?>(.*?)<\\?\\/imcms:menuitem\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEMHIDE_PATTERN = patComp.compile("<\\?imcms:menuitemhide\\?>(.*?)<\\?\\/imcms:menuitemhide\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEMHIDETAG_PATTERN = patComp.compile("<\\?\\/?imcms:menuitemhide\\?>", Perl5Compiler.READ_ONLY_MASK) ;
IMCMS_TAG_PATTERN = patComp.compile("<\\?imcms:(\\w+)(.*?)\\?>", Perl5Compiler.READ_ONLY_MASK) ;
IMCMS_TAG_ATTRIBUTES_PATTERN = patComp.compile("\\s*(\\w+)\\s*=\\s*([\"'])(.*?)\\2", Perl5Compiler.READ_ONLY_MASK) ;
HTML_PREBODY_PATTERN = patComp.compile("^.*?<[Bb][Oo][Dd][Yy].*?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
HTML_POSTBODY_PATTERN = patComp.compile("<\\/[Bb][Oo][Dd][Yy]>.*$", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TR_START_PATTERN = patComp.compile("^(\\<tr[^>]*?\\>)",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TR_STOP_PATTERN = patComp.compile("(\\<\\/tr\\>)\\s*$",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TD_START_PATTERN = patComp.compile("^(\\<td[^>]*?\\>)",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TD_STOP_PATTERN = patComp.compile("(\\<\\/td\\>)\\s*$",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENU_NO_PATTERN = patComp.compile("#doc_menu_no#",Perl5Compiler.READ_ONLY_MASK) ;
// OK, so this is simple, ugly, and prone to give a lot of errors.
// Very good. Very good. Know something? NO SOUP FOR YOU!
HTML_TAG_PATTERN = patComp.compile("<[^>]+?>",Perl5Compiler.READ_ONLY_MASK) ;
} catch (MalformedPatternException ignored) {
// I ignore the exception because i know that these patterns work, and that the exception will never be thrown.
Log log = Log.getLog("server") ;
log.log(Log.CRITICAL, "Danger, Will Robinson!") ;
}
}
/**
* <p>Contructs an IMCService object.
*/
// public IMCService(ConnectionPool conPool,javax.swing.JTextArea output,String serverName)
public IMCService(imcode.server.InetPoolManager conPool,Properties props) {
super();
m_conPool = conPool ;
sysData = getSystemDataFromDb() ;
m_TemplateHome = props.getProperty("TemplatePath") ;
log.log(Log.INFO, "TemplatePath: " + m_TemplateHome) ;
m_IncludePath = props.getProperty("IncludePath") ;
log.log(Log.INFO, "IncludePath: " + m_IncludePath) ;
try {
m_DefaultHomePage = Integer.parseInt(props.getProperty("StartDocument")) ; //FIXME: Get from DB
} catch (NumberFormatException ex) {
throw new RuntimeException ("No StartDocument given in properties-file.") ;
}
log.log(Log.INFO, "StartDocument: " + m_DefaultHomePage) ;
m_ServletUrl = props.getProperty("ServletUrl") ; //FIXME: Get from webserver, or get rid of if possible.
log.log(Log.INFO, "ServletUrl: " + m_ServletUrl) ;
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
m_ImageFolder = props.getProperty("ImageUrl") ; //FIXME: Get from webserver, or get rid of if possible.
log.log(Log.INFO, "ImageUrl: " + m_ImageFolder) ;
String externalDocTypes = props.getProperty("ExternalDoctypes") ; //FIXME: Get rid of, if possible.
log.log(Log.INFO, "ExternalDoctypes: " + externalDocTypes) ;
m_Language = props.getProperty("DefaultLanguage") ; //FIXME: Get from DB
log.log(Log.INFO, "DefaultLanguage: " + m_Language) ;
StringTokenizer doc_types = new StringTokenizer(externalDocTypes,";",false) ;
m_ExDoc = new ExternalDocType[doc_types.countTokens()] ;
try {
for (int doc_count=0; doc_types.hasMoreTokens() ; ++doc_count) {
StringTokenizer tempStr = new StringTokenizer(doc_types.nextToken(),":",false) ;
String items[] = new String[tempStr.countTokens()] ;
for ( int i=0 ; tempStr.hasMoreTokens() ; ++i ) {
items[i] = tempStr.nextToken() ;
}
m_ExDoc[doc_count] = new ExternalDocType(Integer.parseInt(items[0]),items[1],items[2],"") ;
}
}
catch(NoSuchElementException e) {
e.printStackTrace() ;
}
try {
m_SessionCounter = Integer.parseInt(this.sqlProcedureStr("GetCurrentSessionCounter")) ;
m_SessionCounterDate = this.sqlProcedureStr("GetCurrentSessionCounterDate") ;
//m_NoOfTemplates = this.sqlProcedureInt("GetNoOfTemplates") ;
} catch ( NumberFormatException ex ) {
log.log(Log.CRITICAL, "Failed to get SessionCounter from db.", ex) ;
throw ex ;
}
//m_Template = new Template[m_NoOfTemplates] ;
log.log(Log.INFO, "SessionCounter: "+m_SessionCounter) ;
log.log(Log.INFO, "SessionCounterDate: "+m_SessionCounterDate) ;
//log.log(Log.INFO, "TemplateCount: "+m_NoOfTemplates) ;
}
/**
* <p>Get me page _id.
*/
public int getDefaultHomePage() {
return m_DefaultHomePage ;
}
/**
* <p>Verify a Internet/Intranet user. User data retrived from SQL Database.
*/
public imcode.server.User verifyUser(LoginUser login_user,String fieldNames[]) {
String sqlStr = "" ;
User user = new User() ;
DBConnect dbc = new DBConnect(m_conPool,login_user.createLoginQuery()) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector user_data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// if resultSet > 0 a user is found
if ( user_data.size() > 0 ) {
user.setFields(fieldNames,user_data) ;
// add roles to user
sqlStr = "select role_id from user_roles_crossref where user_id = " ;
sqlStr += user.getInt("user_id") ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector user_roles = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
user.addObject("user_roles",user_roles) ;
String login_password_from_db = user.getString(login_user.getLoginPasswordFieldName()).trim() ;
String login_password_from_form = login_user.getLoginPassword() ;
if ( login_password_from_db.equals(login_password_from_form) && user.getBoolean("active"))
this.updateLogs(new java.util.Date() + "->User " + login_user.getLoginName()
+ " succesfully logged in.") ;
else if (!user.getBoolean("active") ) {
this.updateLogs(new java.util.Date() + "->User " + (login_user.getLoginName()).trim()
+ " tried to logged in: User deleted!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
} else {
this.updateLogs(new java.util.Date() + "->User " + (login_user.getLoginName()).trim()
+ " tried to logged in: Wrong password!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
}
} else {
this.updateLogs(new java.util.Date() + "->User " + login_user.getLoginName()
+ " tried to logged in: User not found!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
}
// Get the users language prefix
String lang_prefix = null ;
sqlStr = "select lang_prefix from lang_prefixes where lang_id = "+user.getLangId() ; // Find language
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector lang_prefix_data = (Vector)dbc.executeQuery() ;
if ( lang_prefix_data.size() > 0 ) {
lang_prefix = lang_prefix_data.elementAt(0).toString() ;
user.put("lang_prefix",lang_prefix) ;
}
dbc.closeConnection() ;
dbc = null ;
return user ;
}
public byte[] parsePage (int meta_id, User user, int flags) throws IOException {
return parsePage(meta_id,user,flags,1) ;
}
public byte[] parsePage (int meta_id, User user, int flags, int includelevel) throws IOException {
try {
long totaltime = System.currentTimeMillis() ;
String meta_id_str = String.valueOf(meta_id) ;
int user_id = user.getInt("user_id") ;
String user_id_str = String.valueOf(user_id) ;
//log.log(Log.WILD, "Starting parsing of page for meta_id "+meta_id_str+", user "+user_id_str+", flags "+flags, null) ;
DBConnect dbc = new DBConnect(m_conPool) ;
//log.log(Log.WILD, "Getting connection", null) ;
dbc.getConnection() ;
dbc.createStatement() ;
String lang_prefix = user.getLangPrefix() ; // Find language
String[] sqlAry = {
meta_id_str,
user_id_str
} ;
//log.log(Log.WILD, "Getting permissions", null) ;
dbc.setProcedure("GetUserPermissionSet (?,?)",sqlAry) ;
Vector user_permission_set = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( user_permission_set == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetUserPermissionset returned null") ;
return ("GetUserPermissionset returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Setting permissionstate", null) ;
int user_set_id = Integer.parseInt((String)user_permission_set.elementAt(0)) ;
int user_perm_set = Integer.parseInt((String)user_permission_set.elementAt(1)) ;
int currentdoc_perms = Integer.parseInt((String)user_permission_set.elementAt(2)) ;
boolean textmode = false ;
boolean imagemode = false ;
boolean menumode = false ;
boolean templatemode = false ;
boolean includemode = false ;
if (flags > 0) {
textmode = (flags & PERM_DT_TEXT_EDIT_TEXTS) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_TEXTS) != 0) ;
imagemode = (flags & PERM_DT_TEXT_EDIT_IMAGES) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_IMAGES) != 0) ;
menumode = (flags & PERM_DT_TEXT_EDIT_MENUS) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_MENUS) != 0) ;
templatemode = (flags & PERM_DT_TEXT_CHANGE_TEMPLATE) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_CHANGE_TEMPLATE) != 0) ;
includemode = (flags & PERM_DT_TEXT_EDIT_INCLUDES) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_INCLUDES) != 0 ) ;
}
dbc.setProcedure("GetIncludes",String.valueOf(meta_id)) ;
Vector included_docs = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.setProcedure("GetTextDocData",String.valueOf(meta_id)) ;
Vector text_docs = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( text_docs == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTextDocData returned null") ;
return "parsePage: GetTextDocData returned null".getBytes("8859_1") ;
}
if ( text_docs.size() == 0 ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTextDocData returned nothing") ;
return "parsePage: GetTextDocData returned nothing".getBytes("8859_1") ;
}
String template_id = (String)text_docs.remove(0) ;
String simple_name = (String)text_docs.remove(0) ;
int sort_order = Integer.parseInt((String)text_docs.remove(0)) ;
String group_id = (String)text_docs.remove(0) ;
log.log(Log.WILD, "Got templateinfo. TemplateId: "+template_id, null) ;
Vector doc_types_vec = null ;
String sqlStr = null ;
if (menumode) {
// I'll retrieve a list of all doc-types the user may create.
sqlStr = "GetDocTypesForUser (?,?,?)" ;
String[] sqlAry2 = {
String.valueOf(meta_id),
String.valueOf(user.getInt("user_id")),
lang_prefix
} ;
dbc.setProcedure(sqlStr,sqlAry2) ;
doc_types_vec = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
}
Vector templategroups = null ;
Vector templates = null ;
Vector groupnamevec = null ;
int selected_group = user.getTemplateGroup() ;
if (templatemode) {
sqlStr = "GetTemplategroupsForUser (?,?)" ;
String[] sqlAry2 = {
String.valueOf(meta_id),
String.valueOf(user.getInt("user_id"))
} ;
dbc.setProcedure(sqlStr,sqlAry2) ;
templategroups = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
// do templatemode queries
if ( selected_group == -1 ) {
selected_group = Integer.parseInt(group_id) ;
}
sqlStr = "GetTemplatesInGroup";
dbc.setProcedure(sqlStr,String.valueOf(selected_group)) ;
templates = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
sqlStr = "select group_name from templategroups where group_id = " + selected_group ;
dbc.setSQLString(sqlStr);
groupnamevec = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
String[] emp = (String[])user.get("emphasize") ;
// Now we'll get the texts from the db.
//log.log(Log.WILD, "Starting texts.", null) ;
dbc.setProcedure("GetTexts",String.valueOf(meta_id)) ;
Vector texts = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( texts == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTexts returned null") ;
return ("GetTexts returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Getting images.", null) ;
// Get the images from the db
// sqlStr = "select '#img'+convert(varchar(5), name)+'#',name,imgurl,linkurl,width,height,border,v_space,h_space,image_name,align,alt_text,low_scr,target,target_name from images where meta_id = " + meta_id ;
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
sqlStr = "select date_modified, meta_headline, meta_image from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr);
Vector meta = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( meta == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: Query for date_modified returned null") ;
return ("Query for date_modified returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Got docinfo. Getting childs.", null) ;
// Here we have the most timeconsuming part of parsing the page.
// Selecting all the documents with permissions from the DB
sqlStr = "getChilds (?,?)" ;
//String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector childs = (Vector)dbc.executeProcedure() ;
if ( childs == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetChilds returned null") ;
return ("GetChilds returned null").getBytes("8859_1") ;
}
int child_cols = dbc.getColumnCount() ;
int child_rows = childs.size() / child_cols ;
dbc.clearResultSet() ;
dbc.setProcedure("GetImgs",String.valueOf(meta_id)) ;
Vector images = (Vector)dbc.executeProcedure() ;
if ( images == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetImgs returned null") ;
return ("GetImgs returned null").getBytes("8859_1") ;
}
dbc.closeConnection() ; // Close connection to db.
String emphasize_string = fileCache.getCachedFileString(m_TemplateHome + lang_prefix +"/admin/emphasize.html") ;
Perl5Compiler patComp = new Perl5Compiler() ;
Perl5Matcher patMat = new Perl5Matcher() ;
Perl5Substitution emphasize_substitution = new Perl5Substitution(emphasize_string) ;
Properties tags = new Properties() ; // A properties object to hold the results from the db...
HashMap textMap = new HashMap() ;
HashMap imageMap = new HashMap() ;
//log.log(Log.WILD, "Processing texts.", null) ;
Iterator it = texts.iterator() ;
while ( it.hasNext() ) {
String key = (String)it.next() ;
String txt_no = (String)it.next() ;
String txt_type = (String)it.next() ;
String value = (String)it.next() ;
if ( textmode ) { // Textmode
if ( value.length()>0 ) {
value = "<img src=\""
+ m_ImageFolder
+ "red.gif\" border=\"0\"> "
+ value
+ "<a href=\""
+ m_ServletUrl
+ "ChangeText?meta_id="
+ meta_id
+ "&txt="
+ txt_no
+ "&type="
+ txt_type
+ "\"><img src=\""
+ m_ImageFolder
+ "txt.gif\" border=\"0\"></a>" ;
tags.setProperty(key,value) ;
textMap.put(txt_no,value);
}
} else { // Not Textmode
if (emp!=null) {
value = emphasizeString(value,emp,emphasize_substitution,patMat) ;
}
if ( value.length()>0 ) {
tags.setProperty(key,value) ;
textMap.put(txt_no,value) ;
}
}
}
//log.log(Log.WILD, "Processing images.", null) ;
int images_cols = dbc.getColumnCount() ;
int images_rows = images.size() / images_cols ;
dbc.clearResultSet() ;
Iterator imit = images.iterator() ;
while ( imit.hasNext() ) {
String imgtag = (String)imit.next() ;
String imgnumber = (String)imit.next() ;
String imgurl = (String)imit.next() ;
String linkurl = (String)imit.next() ;
String width = (String)imit.next() ;
String height = (String)imit.next() ;
String border = (String)imit.next() ;
String vspace = (String)imit.next() ;
String hspace = (String)imit.next() ;
String image_name = (String)imit.next() ;
String align = (String)imit.next() ;
String alt = (String)imit.next() ;
String lowscr = (String)imit.next() ;
String target = (String)imit.next() ;
String target_name = (String)imit.next() ;
StringBuffer value = new StringBuffer (96) ;
if ( !"".equals(imgurl) ) {
if ( !"".equals(linkurl) ) {
value.append("<a href=\""+linkurl+"\"") ;
if ( target.equals("_other") ) {
value.append(" target=\""+target_name+"\">") ;
} else if ( !"".equals(target) ) {
value.append(" target=\""+target+"\">") ;
}
}
value.append("<img src=\""+m_ImageFolder+imgurl+"\"") ; // FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
if ( !"0".equals(width) ) {
value.append(" width=\""+width+"\"") ;
}
if ( !"0".equals(height) ) {
value.append(" height=\""+height+"\"") ;
}
value.append(" border=\""+border+"\"") ;
if ( !"0".equals(vspace) ) {
value.append(" vspace=\""+vspace+"\"") ;
}
if ( !"0".equals(hspace) ) {
value.append(" hspace=\""+hspace+"\"") ;
}
if ( !"".equals(image_name) ) {
value.append(" name=\""+image_name+"\"") ;
}
if ( !"".equals(alt) ) {
value.append(" alt=\""+alt+"\"") ;
}
if ( !"".equals(lowscr) ) {
value.append(" lowscr=\""+lowscr+"\"") ;
}
if ( !"".equals(align) && !"none".equals(align)) {
value.append(" align=\""+align+"\"") ;
}
if ( !"".equals(linkurl) || imagemode ) {
value.append("></a>") ;
} else {
value.append(">") ;
}
if ( imagemode ) { // Imagemode...
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
value.append("<a href=\"ChangeImage?meta_id="+meta_id+"&img="+imgnumber+"\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
}
}
log.log(Log.WILD, "Storing link '"+value.toString()+"' to image number '"+imgnumber+"'") ;
tags.setProperty(imgtag,value.toString()) ;
imageMap.put(imgnumber,value.toString()) ;
}
/*
OK.. we will now make a LinkedList for the entire page.
This LinkedList, menus, will contain one item for each menu on the page.
These items will also be instances of LinkedList.
These LinkedLists will in turn each hold one Properties for each item in each menu.
These Properties will hold the tags, and the corresponding data, that will go in each menuitem.
*/
HashMap menus = new HashMap () ; // Map to contain all the menus on the page.
LinkedList currentMenu = null ;
int old_menu = -1 ;
java.util.Date now = new java.util.Date() ;
Iterator childIt = childs.iterator() ;
while ( childIt.hasNext() ) {
// The menuitemproperties are retrieved in the following order:
// to_meta_id,
// c.menu_sort,
// manual_sort_order,
// doc_type,
// archive,
// target,
// date_created,
// date_modified,
// meta_headline,
// meta_text,
// meta_image,
// frame_name,
// activated_date+activated_time,
// archived_date+archived_time
// 0 if admin
// filename
String child_meta_id = (String)childIt.next() ; // The meta-id of the child
String child_menu_sort = (String)childIt.next() ; // What menu in the page the child is in.
String child_manual_sort_order = (String)childIt.next() ; // What order the document is sorted in in the menu, using sort-order 2 (manual sort)
String child_doc_type = (String)childIt.next() ; // The doctype of the child.
String child_archive = (String)childIt.next() ; // Child is considered archived?
String child_target = (String)childIt.next() ; // The target for this document.
String child_date_created = (String)childIt.next() ; // The datetime the child was created.
String child_date_modified = (String)childIt.next() ; // The datetime the child was modified.
String child_meta_headline = (String)childIt.next() ; // The headline of the child.
String child_meta_text = (String)childIt.next() ; // The subtext for the child.
String child_meta_image = (String)childIt.next() ; // An optional imageurl for this document.
String child_frame_name = (String)childIt.next() ; // The target fram for this document. Supposed to be replaced by 'target'.
String child_activated_date_time = (String)childIt.next() ; // The datetime the document is activated.
String child_archived_date_time = (String)childIt.next() ; // The datetime the document is archived.
String child_admin = (String)childIt.next() ; // "0" if the user may admin it.
String child_filename = (String)childIt.next() ; // The filename, if it is a file-doc.
// System.out.println((String)childs.get(i*child_cols+0)+" "+(String)childs.get(i*child_cols+1)+" "+(String)childs.get(i*child_cols+7)) ;
int menuno = Integer.parseInt(child_menu_sort) ;
if ( menuno != old_menu ) { //If we come upon a new menu...
old_menu = menuno ;
currentMenu = new LinkedList() ; // We make a new Menu,
menus.put(new Integer(menuno), currentMenu) ; // and add it to the page.
}
java.util.Date archived_date = null ;
java.util.Date activate_date = null ;
SimpleDateFormat DATETIMEFORMAT = new SimpleDateFormat("yyyy-MM-ddHH:mm") ;
try {
archived_date = DATETIMEFORMAT.parse(child_archived_date_time) ;
} catch ( java.text.ParseException ex ) {
}
try {
activate_date = DATETIMEFORMAT.parse(child_activated_date_time) ;
} catch ( java.text.ParseException ex ) {
}
boolean inactive = false ;
boolean archived = false ;
if ( activate_date != null && activate_date.compareTo(now) >= 0 ) {// If activated_date is greater than or equal to now
if ( !menumode ) { // and we're not in menumode...
continue ; // ...don't include this menuitem
} else {
inactive = true ;
}
}
if ( (archived_date != null && archived_date.compareTo(now) <= 0) // If archived_date is smaller than or equal to now
|| "1".equals(child_archive) ) { // or archive is set
if ( !menumode ) { // and we're not in menumode...
continue ; // ...don't include this menuitem
} else {
archived = true ;
}
}
Properties props = new Properties () ; // New Properties to hold the tags for this menuitem.
String admin_start = "" ;
String admin_stop = "" ;
if ( menumode ) {
String sortBox = "<input type=\"text\" name=\""+child_meta_id+"\" value=\""+child_manual_sort_order+"\" size=\"4\" maxlength=\"4\">" ;
String archiveDelBox = "<input type=\"checkbox\" name=\"archiveDelBox\" value=\""+child_meta_id+"\">" ;
//props.setProperty("#sortBox#",sortBox) ;
//props.setProperty("#archiveDelBox#",archiveDelBox) ;
if ( "0".equals(child_admin) ) {
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
admin_stop+=" <a href=\"AdminDoc?meta_id="+child_meta_id+"\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
}
if (sort_order == 2) {
admin_start += sortBox ;
}
admin_start += archiveDelBox ;
}
String archive_start = "" ;
String archive_stop = "" ;
if ( inactive ) {
archive_start+="<em><i>" ;
archive_stop+="</i></em>" ;
}
if ( archived ) {
archive_start="<strike>"+archive_start ;
archive_stop+="</strike>" ;
}
props.setProperty("#adminStart#",admin_start) ;
props.setProperty("#adminStop#",admin_stop) ;
//props.setProperty("#to_meta_id#",to_meta_id) ;
//props.setProperty("#manual_sort_order#",child_manual_sort_order) ;
if ( "_other".equals(child_target) ) {
child_target = (String)child_frame_name ;
}
if ( child_target.length() != 0 ) {
child_target = " target=\""+child_target+"\"" ;
}
// If this doc is a file, we'll want to put in the filename
// as an escaped translated path
// For example: /servlet/GetDoc/filename.ext?meta_id=1234
// ^^^^^^^^^^^^^
if ( child_filename != null && "8".equals(child_doc_type) ) {
child_filename = "/"+java.net.URLEncoder.encode(child_filename) ;
} else {
child_filename = "" ;
}
if ( child_meta_headline.length() == 0 ) {
child_meta_headline = " " ;
}
child_meta_headline = archive_start+child_meta_headline+archive_stop ;
if ( !"".equals(child_meta_image) ) {
child_meta_image = "<img src=\""+child_meta_image+"\" border=\"0\">" ;
}
String href = "\"GetDoc"+child_filename+"?meta_id="+child_meta_id+"\""+child_target ;
props.setProperty("#getChildRef#",href) ;
props.setProperty("#childMetaImage#",child_meta_image) ;
props.setProperty("#childMetaHeadline#",child_meta_headline) ;
props.setProperty("#childMetaText#",child_meta_text) ;
props.setProperty("#childCreatedDate#",child_date_created) ;
// Put the data in the proper tags.
props.setProperty("#/menuitemlink#", "</a>"+admin_stop) ;
props.setProperty("#menuitemlink#", admin_start+"<a href="+href+">") ;
props.setProperty("#menuitemheadline#", child_meta_headline) ;
props.setProperty("#menuitemtext#", child_meta_text) ;
props.setProperty("#menuitemdatecreated#", child_date_created) ;
props.setProperty("#menuitemdatemodified#", child_date_modified) ;
props.setProperty("#menuitemimage#", child_meta_image) ;
currentMenu.add(props) ; // Add the Properties for this menuitem to the current menus list.
}
//log.log(Log.WILD, "Getting templateinfo.", null) ;
// I need a list of tags that have numbers that need to be parsed in in their data.
Properties numberedtags = new Properties () ;
// I also need a list of files to load, and their corresponding tag...
Properties toload = new Properties () ;
// Oh! I need a set of tags to be replaced in the templatefiles we'll load...
Properties temptags = new Properties () ;
// Put tags and corresponding data in Properties
tags.setProperty("#userName#", user.getString("first_name").trim()+" "+user.getString("last_name").trim()) ;
tags.setProperty("#session_counter#", String.valueOf(m_SessionCounter)) ;
tags.setProperty("#session_counter_date#", m_SessionCounterDate) ;
tags.setProperty("#lastDate#", meta.get(0).toString()) ;
tags.setProperty("#metaHeadline#", meta.get(1).toString()) ;
String meta_image = meta.get(2).toString() ;
if (!"".equals(meta_image)) {
meta_image = "<img src=\""+meta_image+"\" border=\"0\">" ;
}
tags.setProperty("#metaImage#", meta_image) ;
tags.setProperty("#sys_message#", sysData.getSystemMessage()) ;
tags.setProperty("#servlet_url#", m_ServletUrl) ;
tags.setProperty("#webMaster#", sysData.getWebMaster()) ;
tags.setProperty("#webMasterEmail#", sysData.getWebMasterAddress()) ;
tags.setProperty("#serverMaster#", sysData.getServerMaster()) ;
tags.setProperty("#serverMasterEmail#", sysData.getServerMasterAddress()) ;
tags.setProperty("#addDoc*#","") ;
tags.setProperty("#saveSortStart*#","") ;
tags.setProperty("#saveSortStop*#","") ;
if ( imagemode ) { // imagemode
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
tags.setProperty("#img*#", "<a href=\"ChangeImage?meta_id="+meta_id+"&img=#img_no#\"><img src=\""+m_ImageFolder+"bild.gif\" border=\"0\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
numberedtags.setProperty("#img*#","#img_no#") ;
}
if ( textmode ) { // Textmode
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
tags.setProperty("#txt*#", "<img src=\""+m_ImageFolder+"red.gif\" border=\"0\"> <a href=\""+m_ServletUrl+"ChangeText?meta_id="+meta_id+"&txt=#txt_no#&type=1\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
numberedtags.setProperty("#txt*#","#txt_no#") ;
}
// Give the user a row of buttons if he is privileged enough.
if ( checkDocAdminRights(meta_id,user) && flags >= 0 ) {
tags.setProperty("#adminMode#",getMenuButtons(meta_id,user)) ;
}
if ( templatemode ) { //Templatemode! :)
String group_name ;
if (!groupnamevec.isEmpty()) {
group_name = (String)groupnamevec.elementAt(0) ;
} else {
group_name = "" ;
}
StringBuffer templatelist = new StringBuffer() ;
// Make a HTML option-list of them...
while ( !templates.isEmpty() ) {
String temp_id = (String)templates.remove(0) ;
templatelist.append("<option value=\""+temp_id) ;
if (temp_id.equals(template_id)) {
templatelist.append("\" selected>"+templates.remove(0)+"</option>") ;
} else {
templatelist.append("\">"+templates.remove(0)+"</option>") ;
}
}
// Fetch all templategroups the user may use.
StringBuffer grouplist = new StringBuffer() ;
// Make a HTML option-list of the templategroups
while ( !templategroups.isEmpty() ) {
String temp_id = (String)templategroups.remove(0) ;
grouplist.append("<option value=\""+temp_id) ;
if (selected_group == Integer.parseInt(temp_id)) {
grouplist.append("\" selected>"+templategroups.remove(0)+"</option>") ;
} else {
grouplist.append("\">"+templategroups.remove(0)+"</option>") ;
}
}
temptags.setProperty("#getDocType#","") ;
temptags.setProperty("#DocMenuNo#","") ;
temptags.setProperty("#group#",group_name) ;
temptags.setProperty("#getTemplateGroups#", grouplist.toString()) ;
temptags.setProperty("#simple_name#",simple_name) ;
temptags.setProperty("#getTemplates#",templatelist.toString()) ;
// Put templateadmintemplate in list of files to load.
toload.setProperty("#changePage#",m_TemplateHome + lang_prefix + "/admin/inPage_admin.html") ;
} // if (templatemode)
temptags.setProperty("#servlet_url#",m_ServletUrl) ;
if ( menumode ) {
// I'll put the doc-types in a html-list
Iterator dt_it = doc_types_vec.iterator() ;
StringBuffer doc_types_sb = new StringBuffer(256) ;
while ( dt_it.hasNext() ) {
String dt = (String)dt_it.next() ;
String dtt = (String)dt_it.next() ;
doc_types_sb.append("<option value=\"") ;
doc_types_sb.append(dt) ;
doc_types_sb.append("\">") ;
doc_types_sb.append(dtt) ;
doc_types_sb.append("</option>") ;
}
// Add an option for an existing doc, too
String existing_doc_filename = m_TemplateHome + lang_prefix + "/admin/existing_doc_name.html" ;
String existing_doc_name = null ;
existing_doc_name = fileCache.getCachedFileString(existing_doc_filename) ;
if (doc_types_vec != null && doc_types_vec.size() > 0) {
doc_types_sb.append("<option value=\"0\">"+existing_doc_name+"</option>") ;
}
// List of files to load, and tags to parse them into
toload.setProperty("addDoc",m_TemplateHome + lang_prefix + "/admin/add_doc.html") ;
toload.setProperty("saveSortStart",m_TemplateHome + lang_prefix + "/admin/sort_order.html") ;
toload.setProperty("saveSortStop",m_TemplateHome + lang_prefix + "/admin/archive_del_button.html") ;
toload.setProperty("sort_button",m_TemplateHome + lang_prefix + "/admin/sort_button.html") ;
// Some tags to parse in the files we'll load.
temptags.setProperty("#doc_types#",doc_types_sb.toString()) ; // The doc-types.
temptags.setProperty("#sortOrder"+sort_order+"#","checked") ; // The sortorder for this document.
} // if (menumode)
temptags.setProperty("#getMetaId#",String.valueOf(meta_id)) ;
// Now load the files specified in "toload", and place them in "tags"
//System.out.println("Loading template-files.") ;
//log.log(Log.WILD,"Loading template-files.",null) ;
MapSubstitution temptagsmapsubstitution = new MapSubstitution(temptags, false) ;
try {
char[] charbuffer = new char[4096] ;
StringBuffer templatebuffer = new StringBuffer() ;
Enumeration propenum = toload.propertyNames() ;
while ( propenum.hasMoreElements() ) {
String filetag = (String)propenum.nextElement() ;
String templatebufferfilename = toload.getProperty(filetag) ;
String templatebufferstring = fileCache.getCachedFileString(templatebufferfilename) ;
// Humm... Now we must replace the tags in the loaded files too.
templatebufferstring = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,temptagsmapsubstitution,templatebufferstring,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
tags.setProperty(filetag,templatebufferstring) ;
templatebuffer.setLength(0) ;
}
} catch(IOException e) {
log.log(Log.ERROR, "An error occurred reading file during parsing.", e) ;
return ("Error occurred reading file during parsing.\n"+e).getBytes("8859_1") ;
}
//log.log(Log.WILD, "Loaded and parsed other templatefiles.", null) ;
if ( menumode ) { //Menumode! :)
// Make a Properties of all tags that contain numbers, and what the number is supposed to replace
// in the tag's corresponding data
// I.e. "tags" contains the data to replace the numbered tag, but you probably want that number
// to be inserted somewhere in that data.
// BTW, "*" represents the number in the tag.
//numberedtags.setProperty("#addDoc*#","#doc_menu_no#") ;
//numberedtags.setProperty("#saveSortStart*#","#doc_menu_no#") ;
String savesortstop = tags.getProperty("saveSortStop") ;
// We must display the sortbutton, which we read into the tag "#sort_button#"
savesortstop = tags.getProperty("sort_button")+savesortstop ;
tags.setProperty("saveSortStop",savesortstop) ;
} else { // Not menumode...
tags.setProperty("saveSortStop", "") ;
} // if (menumode)
// Now... let's load the template!
// Get templatedir and read the file.
StringBuffer templatebuffer = new StringBuffer(fileCache.getCachedFileString(m_TemplateHome + "text/" + template_id + ".html")) ;
// Check file for tags
String template = templatebuffer.toString() ;
StringBuffer result = new StringBuffer(template.length()+16384) ; // This value is the amount i expect the document to increase in size.
MenuParserSubstitution menuparsersubstitution = new MenuParserSubstitution(menus,menumode,tags) ;
HashTagSubstitution hashtagsubstitution = new HashTagSubstitution(tags,numberedtags) ;
ImcmsTagSubstitution imcmstagsubstitution = new ImcmsTagSubstitution(user,meta_id,included_docs,includemode,includelevel,textMap,textmode,imageMap,imagemode) ;
LinkedList parse = new LinkedList() ;
perl5util.split(parse,"/<!-(-\\/?)IMSCRIPT-->/i",template) ;
Iterator pit = parse.iterator() ;
boolean parsing = false ;
//log.log(Log.WILD, "Entering parseloop.") ;
// Well. Here we have it. The main parseloop.
// The Inner Sanctum of imCMS. Have fun.
while ( pit.hasNext() ) {
// So, let's jump in and out of blocks delimited by <!--IMSCRIPT--> and <!--/IMSCRIPT-->
String nextbit = (String)pit.next() ;
if (nextbit.equals("-/")) { // We matched <!--/IMSCRIPT-->
parsing = false ; // So, we're not parsing.
continue ;
} else if (nextbit.equals("-")) { // We matched <!--IMSCRIPT-->
parsing = true ; // So let's get to parsing.
continue ;
}
if (!parsing) {
result.append(nextbit) ;
continue ;
}
// String nextbit now contains the bit to parse. (Within the imscript-tags.)
// Parse the new-style menus.
// Aah... the magic of OO...
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,MENU_PATTERN, menuparsersubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// Parse the obsolete menus.
// You know... the ones that suck so bad it isn't even funny anymore...
// Just look what happens when you have something that isn't properly delimited.
// Without this, we could get something similar to efficiency into this so-called parser.
PatternMatcherInput pmin = new PatternMatcherInput(nextbit) ;
StringBuffer sbtemp = new StringBuffer(nextbit) ;
while (patMat.contains(pmin, OBSOLETE_MENU_PATTERN)) {
MatchResult matres = patMat.getMatch() ;
int [] menu_param = { Integer.parseInt(matres.group(1)), Integer.parseInt(matres.group(2)), Integer.parseInt(matres.group(3)) } ;
int endoffset = matres.endOffset(0) ;
obsoleteMenuParser(sbtemp,matres.beginOffset(0), endoffset, menu_param, menus, menumode, sort_order, patMat,tags) ;
String newinput = sbtemp.toString() ;
pmin.setInput(newinput, endoffset, newinput.length()-endoffset ) ;
}
nextbit = sbtemp.toString() ;
// Parse the <?imcms:tags?>
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,IMCMS_TAG_PATTERN,imcmstagsubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// Parse the hashtags
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,hashtagsubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// So, append the result from this loop-iteration to the result.
result.append(nextbit) ;
} // end while (pit.hasNext()) // End of the main parseloop
String returnresult = result.toString() ;
/*
So, it is here i shall have to put my magical markupemphasizing code.
First, i'll split the html (returnresult) on html-tags, and then go through every non-tag part and parse it for keywords to emphasize,
and then i'll puzzle it together again. Whe-hey. This will be fun. Not to mention fast. Oh yes, siree.
*/
if (emp!=null) { // If we have something to emphasize...
StringBuffer emphasized_result = new StringBuffer(returnresult.length()) ; // A StringBuffer to hold the result
PatternMatcherInput emp_input = new PatternMatcherInput(returnresult) ; // A PatternMatcherInput to match on
int last_html_offset = 0 ;
int current_html_offset = 0 ;
String non_html_tag_string = null ;
String html_tag_string = null ;
while (patMat.contains(emp_input,HTML_TAG_PATTERN)) {
current_html_offset = emp_input.getMatchBeginOffset() ;
non_html_tag_string = result.substring(last_html_offset,current_html_offset) ;
last_html_offset = emp_input.getMatchEndOffset() ;
html_tag_string = result.substring(current_html_offset,last_html_offset) ;
non_html_tag_string = emphasizeString(non_html_tag_string,emp,emphasize_substitution,patMat) ;
// for each string to emphasize
emphasized_result.append(non_html_tag_string) ;
emphasized_result.append(html_tag_string) ;
} // while
non_html_tag_string = result.substring(last_html_offset) ;
non_html_tag_string = emphasizeString(non_html_tag_string,emp,emphasize_substitution,patMat) ;
emphasized_result.append(non_html_tag_string) ;
returnresult = emphasized_result.toString() ;
}
return returnresult.getBytes("8859_1") ;
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Error occurred during parsing.",ex ) ;
return ex.toString().getBytes("8859_1") ;
}
}
private String emphasizeString(String str,
String[] emp,
Substitution emphasize_substitution,
PatternMatcher patMat) {
Perl5Compiler empCompiler = new Perl5Compiler() ;
// for each string to emphasize
for (int i = 0 ; i < emp.length ; ++i) {
try {
Pattern empPattern = empCompiler.compile("("+Perl5Compiler.quotemeta(emp[i])+")",Perl5Compiler.CASE_INSENSITIVE_MASK) ;
str = org.apache.oro.text.regex.Util.substitute( // Threadsafe
patMat,
empPattern,
emphasize_substitution,
str,
org.apache.oro.text.regex.Util.SUBSTITUTE_ALL
) ;
} catch (MalformedPatternException ex) {
log.log(Log.WARNING, "Dynamic Pattern-compilation failed in IMCService.emphasizeString(). Suspected bug in jakarta-oro Perl5Compiler.quotemeta(). The String was '"+emp[i]+"'",ex) ;
}
}
return str ;
}
private String hashTagHandler(PatternMatcher patMat, PatternCompiler patComp, Properties tags, Properties numberedtags) {
MatchResult matres = patMat.getMatch() ;
String tag = matres.group(0) ;
String tagdata = tags.getProperty(tag) ; // Get value of tag from hash
if ( tagdata == null ) {
if (patMat.contains(tag,HASHTAGNUMBER_PATTERN) ) {
String numbertag ;
matres = patMat.getMatch() ;
String tagnumber = matres.group(1) ;
String tagexp = tag.substring(0,matres.beginOffset(0))+"*#" ;
tagdata = tags.getProperty(tagexp) ;
if (tagdata == null) {
tagdata = "" ;
} else if ( (numbertag = numberedtags.getProperty(tagexp))!=null ) { // Is it a numbered tag which has data to insert the number in? (Is the four first chars listed in "numberedtags"?) Get the tag to replace with the number.
String qm = Perl5Compiler.quotemeta(numbertag) ; // FIXME: Run quotemeta on them before putting them in numberedtags, instead of doing it every iteration.
try {
tagdata = org.apache.oro.text.regex.Util.substitute(patMat,patComp.compile(qm),new StringSubstitution(tagnumber),tagdata,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
} catch (MalformedPatternException ex) {
log.log(Log.WARNING, "Dynamic Pattern-compilation failed in IMCService.hashTagHandler(). Suspected bug in jakarta-oro Perl5Compiler.quotemeta(). The String was '"+numbertag+"'",ex) ;
}
}
} else {
tagdata = "" ;
}
}
return tagdata ;
}
private String getMenuModePrefix(PatternMatcher patMat, int menu_id, Properties tags) {
String temp = tags.getProperty("addDoc") +
tags.getProperty("saveSortStart") ;
return org.apache.oro.text.regex.Util.substitute(patMat,MENU_NO_PATTERN,new StringSubstitution(""+menu_id),temp,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
}
private String getMenuModeSuffix(Properties tags) {
return tags.getProperty("saveSortStop") ;
}
/**
Invoked when you have found a block of data that is within menu-tags.
*/
protected String menuParser (String input, PatternMatcher patMat, Map menus, int[] implicitMenus, boolean menumode, Properties tags) {
try {
MatchResult menuMatres = patMat.getMatch() ;
StringBuffer result = new StringBuffer() ; // FIXME: Optimize size?
// Get the id of the menu
int menu_id = 0 ;
try {
menu_id = Integer.parseInt(menuMatres.group(1)) ;
} catch (NumberFormatException ex) {
menu_id = implicitMenus[0]++ ;
}
// Get the linked list that is the menu
LinkedList currentMenu = getMenuById(menus,menu_id) ;
// Get the data between the menutags.
String menutemplate = menuMatres.group(2) ;
String menustarttemplate = "" , menustoptemplate = "" ;
String looptemplate ;
// Check if the looptags are present
if (patMat.contains(menutemplate,MENULOOP_PATTERN)) {
MatchResult menuloopMatres = patMat.getMatch() ;
// Get the data between the looptags.
looptemplate = menuloopMatres.group(1) ;
menustarttemplate = menutemplate.substring(0,menuloopMatres.beginOffset(0)) ;
menustoptemplate = menutemplate.substring(menuloopMatres.endOffset(0)) ;
} else {
// No looptags are present. The whole menu will loop.
looptemplate = menutemplate ;
}
// Create a list of menuitemtemplates
LinkedList menuitemtemplatelist = new LinkedList() ;
// Loop over the list and insert the menuitemtemplates
PatternMatcherInput pmin = new PatternMatcherInput(looptemplate) ;
while (patMat.contains(pmin, MENUITEM_PATTERN)) {
MatchResult menuitemMatres = patMat.getMatch() ;
String menuitemtemplate = menuitemMatres.group(1) ;
menuitemtemplatelist.add(menuitemtemplate) ;
}
if (menuitemtemplatelist.isEmpty()) { // Well, were there any menuitemtags present?
menuitemtemplatelist.add(looptemplate) ; // No? Use the looptemplate. (Which will be the entire menu if the looptags are missing.)
}
if (currentMenu != null && currentMenu.size() > 0) {
// Now i begin outputting the results.
result.append(menustarttemplate) ;
// Create an iterator over the menuitemtemplates
Iterator mitit = menuitemtemplatelist.iterator() ;
// Loop over the menus
MapSubstitution mapsubstitution = new MapSubstitution() ;
Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
for (Iterator mit = currentMenu.iterator() ; mit.hasNext() ; ) {
// Make sure we loop over the templates.
if (!mitit.hasNext()) {
mitit = menuitemtemplatelist.iterator() ;
}
String menuitemtemplate = (String)mitit.next() ;
Properties menuitemprops = (Properties)mit.next() ;
// Now i need to replace all tags in this template.
mapsubstitution.setMap(menuitemprops, true) ;
String menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,mapsubstitution,menuitemtemplate,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,MENUITEMHIDETAG_PATTERN, NULL_SUBSTITUTION, menuitemresult,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
result.append(menuitemresult) ;
}
// If we still have menuitemtemplates left, loop over them, and hide everything that is supposed to be hidden.
while (mitit.hasNext()) {
String menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,MENUITEMHIDE_PATTERN, NULL_SUBSTITUTION, (String)mitit.next(), org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
result.append(menuitemresult) ;
}
result.append(menustoptemplate) ;
}
String resultstring = result.toString() ;
if (menumode) { // If in menumode, make sure to include all the stuff from the proper admintemplates.
resultstring = getMenuModePrefix(patMat,menu_id,tags)+resultstring+getMenuModeSuffix(tags) ;
}
return resultstring ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR, "Error during parsing.", ex) ;
return null ;
}
}
protected class MapSubstitution implements Substitution {
Map map ;
boolean removeNulls ;
public MapSubstitution() {
}
public MapSubstitution(Map map, boolean removeNulls) {
this.map = map ;
this.removeNulls = removeNulls ;
}
public void setMap (Map map, boolean removeNulls) {
this.map = map ;
this.removeNulls = removeNulls ;
}
public Map getMap () {
return map ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
String match = matres.group(0) ;
String replace = (String)map.get(match) ;
if (replace == null ) {
if (removeNulls) {
replace = "" ;
} else {
replace = match ;
}
}
sb.append(replace) ;
}
}
protected class MenuParserSubstitution implements Substitution {
Map menus ;
boolean menumode ;
Properties tags ;
int[] implicitMenus = {1} ;
public MenuParserSubstitution (Map menus,boolean menumode, Properties tags ) {
this.menumode = menumode ;
this.menus = menus ;
this.tags = tags ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
sb.append(menuParser(originalInput,patMat,menus,implicitMenus,menumode,tags)) ;
}
}
protected class ImcmsTagSubstitution implements Substitution {
User user ;
int implicitIncludeNumber = 1 ;
int implicitTextNumber = 1 ;
int implicitImageNumber = 1 ;
int meta_id ;
boolean includeMode ;
int includelevel ;
Map textMap ;
boolean textMode ;
Map imageMap ;
boolean imageMode ;
private final Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
HashMap included_docs = new HashMap() ;
/**
@param user The user
@param meta_id The document-id
@param included_list A list of (include-id, included-meta-id, ...)
@param includemode Whether to include the admin-template instead of the included document.
@param includelevel The number of levels of recursion we've gone through.
**/
ImcmsTagSubstitution (User user, int meta_id, List included_list, boolean includemode, int includelevel, Map textMap, boolean textmode, Map imageMap, boolean imagemode) {
this.user = user ;
this.meta_id = meta_id ;
this.includeMode = includemode ;
this.includelevel = includelevel ;
this.textMap = textMap ;
this.textMode = textmode ;
this.imageMap = imageMap ;
this.imageMode = imagemode ;
for (Iterator i = included_list.iterator(); i.hasNext() ;) {
included_docs.put(i.next(), i.next()) ;
}
}
/**
Handle a <?imcms:include ...?> tag
@param attributes The attributes of the include tag
@param patMat A pattern matcher.
**/
public String tagInclude (Properties attributes, PatternMatcher patMat) {
int no = 0 ;
String attributevalue ;
log.log(Log.DEBUG, "Found include tag with attributes "+attributes) ;
if (null != (attributevalue = attributes.getProperty("no"))) { // If we have the attribute no="number"...
// Set the number of this include-tag
try {
no = Integer.parseInt(attributevalue) ; // Then set the number wanted
}
catch (NumberFormatException ex) {
return "" ;
}
} else if (null != (attributevalue = attributes.getProperty("file"))) { // If we have the attribute file="filename"...
// Fetch a file from the disk
try {
return fileCache.getCachedFileString(new File(m_IncludePath, attributevalue)) ; // Get a file from the include directory
} catch (IOException ignored) {}
return "" ;
} else if (null != (attributevalue = attributes.getProperty("document"))) { // If we have the attribute document="meta-id"
try {
if (includelevel>0) {
int included_meta_id = Integer.parseInt(attributevalue) ;
// Recursively parse the wanted page.
String document = new String(parsePage(included_meta_id,user,-1,includelevel-1),"8859_1") ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_PREBODY_PATTERN,NULL_SUBSTITUTION,document) ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_POSTBODY_PATTERN,NULL_SUBSTITUTION,document) ;
return document ;
}
}
catch (NumberFormatException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (RuntimeException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
}
return "" ;
} else if (null != (attributevalue = attributes.getProperty("url"))) { // If we have an attribute of the form url="url:url"
try {
URL url = new URL(attributevalue) ;
if (url.getProtocol().equalsIgnoreCase("file")) { // Make sure we don't have to defend against file://urls...
return "" ;
}
InputStreamReader urlInput = new InputStreamReader(url.openConnection().getInputStream()) ;
int charsRead = -1 ;
final int URL_BUFFER_LEN = 16384 ;
char[] buffer = new char[URL_BUFFER_LEN] ;
StringBuffer urlResult = new StringBuffer() ;
while (-1 != (charsRead = urlInput.read(buffer,0,URL_BUFFER_LEN))) {
urlResult.append(buffer,0,charsRead) ;
}
return urlResult.toString() ;
} catch (MalformedURLException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (RuntimeException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
}
} else { // If we have none of the attributes no, file, or document
no = implicitIncludeNumber++ ; // Implicitly use the next number.
}
try {
if (includeMode) {
String included_meta_id_str = (String)included_docs.get(String.valueOf(no)) ;
return imcode.util.Parser.parseDoc(fileCache.getCachedFileString(new File(m_TemplateHome, user.getLangPrefix()+"/admin/change_include.html")),
new String[] {
"#meta_id#", String.valueOf(meta_id),
"#servlet_url#", m_ServletUrl,
"#include_id#", String.valueOf(no),
"#include_meta_id#", included_meta_id_str == null ? "" : included_meta_id_str
}
) ;
} else if (includelevel>0) {
int included_meta_id = Integer.parseInt((String)included_docs.get(String.valueOf(no))) ;
String document = new String(parsePage(included_meta_id,user,-1,includelevel-1),"8859_1") ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_PREBODY_PATTERN,NULL_SUBSTITUTION,document) ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_POSTBODY_PATTERN,NULL_SUBSTITUTION,document) ;
return document ;
}
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (NumberFormatException ex) {
// There was no such include in the db.
return "" ;
}
return "" ;
}
/**
Handle a <?imcms:text ...?> tag
@param attributes The attributes of the text tag
@param patMat A pattern matcher.
**/
public String tagText (Properties attributes, PatternMatcher patMat) {
// Get the 'no'-attribute of the <?imcms:text no="..."?>-tag
log.log(Log.DEBUG, "Found text tag with attributes "+attributes) ;
String noStr = attributes.getProperty("no") ;
String result = null ;
if (null != noStr) {
result = (String)textMap.get(noStr) ;
} else {
result = (String)textMap.get(noStr = String.valueOf(implicitTextNumber++)) ;
}
if (result == null || "".equals(result)) {
if (textMode) {
result = "<img src=\""+m_ImageFolder+"red.gif\" border=\"0\"> <a href=\""+m_ServletUrl+"ChangeText?meta_id="+meta_id+"&txt="+noStr+"&type=1\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
} else {
result = "" ;
}
log.log(Log.DEBUG, "Empty texttag in textmode '"+textMode+"' replaced by "+result) ;
}
return result ;
}
/**
Handle a <?imcms:image ...?> tag
@param attributes The attributes of the image tag
@param patMat A pattern matcher.
**/
public String tagImage (Properties attributes, PatternMatcher patMat) {
// Get the 'no'-attribute of the <?imcms:text no="..."?>-tag
log.log(Log.DEBUG, "Found image tag with attributes "+attributes) ;
String noStr = attributes.getProperty("no") ;
String result = null ;
if (null != noStr) {
result = (String)imageMap.get(noStr) ;
} else {
result = (String)imageMap.get(noStr = String.valueOf(implicitImageNumber++)) ;
}
if (result == null || "".equals(result)) {
if (imageMode) {
result = "<a href=\"ChangeImage?meta_id="+meta_id+"&img="+noStr+"\"><img src=\""+m_ImageFolder+"bild.gif\" border=\"0\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
} else {
result = "" ;
}
log.log(Log.DEBUG, "Empty imagetag in imagemode '"+imageMode+"' replaced by "+result) ;
}
return result ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
String tagname = matres.group(1) ;
String tagattributes = matres.group(2) ;
Properties attributes = new Properties() ;
PatternMatcherInput pminput = new PatternMatcherInput(tagattributes) ;
while(patMat.contains(pminput,IMCMS_TAG_ATTRIBUTES_PATTERN)) {
MatchResult attribute_matres = patMat.getMatch() ;
attributes.setProperty(attribute_matres.group(1), attribute_matres.group(3)) ;
}
String result ;
if ("text".equals(tagname)) {
result = tagText(attributes, patMat) ;
} else if ("image".equals(tagname)) {
result = tagImage(attributes, patMat) ;
} else if ("include".equals(tagname)) {
result = tagInclude(attributes, patMat) ;
} else {
result = matres.group(0) ;
}
sb.append(result) ;
}
}
protected class HashTagSubstitution implements Substitution {
Properties tags ;
Properties numberedtags ;
Perl5Compiler patComp = new Perl5Compiler() ;
public HashTagSubstitution (Properties tags, Properties numberedtags) {
this.tags = tags ;
this.numberedtags = numberedtags ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
sb.append(hashTagHandler(patMat,patComp,tags,numberedtags)) ;
}
}
private LinkedList getMenuById(Map menus, int id) {
return (LinkedList)menus.get(new Integer(id)) ;
}
/**
I sincerely apologize for this,
but i create this method only to remove the old stupid parser from the main block of the parseloop.
This method and way of parsing a template must die, as soon as possible.
@param sb The stringbuffer to work on
@param sbindex The start of the menu in the stringbuffer.
@param reindex The end of the first row of the stringbuffer. (Or the start of the next line, i don't remember.) At least i think that's correct...
@param menu_param The three ints of the menu. no, rows, and table_col
@param menus The HashMap containing all the menus.
@param menumode A boolean detailing whether or not we are in menu-admin-mode
@param sort_order The magic number that tells us which sort-order we are using.
@param tags Don't ask... this contains the other tags to parse in the page. Used for getMenuModePrefix
*/
private void obsoleteMenuParser (StringBuffer sb, int sbindex, int reindex, int[] menu_param, HashMap menus, boolean menumode, int sort_order, PatternMatcher patMat, Properties tags) {
log.log(Log.WILD, "Starting to parse an obsolete menu on offset "+sbindex) ;
int menurowsindex = sbindex ; // We'll store away the index of the start of the menu.
sbindex = reindex ;
// Now we'll read each row... so we'll need some storagespace...
String[] menu_rows = new String[menu_param[1]] ; //Allocate an array to hold the menurows
StringBuffer tmpsb = new StringBuffer() ;
// for each row in the template...
for ( int foo=0 ; foo<menu_param[1] ; ++foo ) {
char d ;
while ( Character.isWhitespace(sb.charAt(sbindex)) ) {
++sbindex ; //Skip whitespace...
}
while ( (d = sb.charAt(sbindex++)) != '\n' && d != '\r' ) { // Read a line
tmpsb.append(d) ;
}
menu_rows[foo] = tmpsb.toString()+"\r\n" ; // Store the line away... Note that "\r\n" is the standard html (as well as http and dos) end-of-line.
tmpsb.setLength(0) ; // Clear the stringbuffer
}
log.log(Log.WILD, "Read the "+menu_param[1]+" rows of the menu") ;
//sb.replace(menurowsindex,sbindex,"") ; // Remove the lines
//sbindex = menurowsindex ;
// Hohum... Now we should finally have the template rows of the menu in an array...
// Now to another problem... parsing the individual bastards.
// OK... so i have learned that the first two lines are used, seemingly as one string,
// and the second two are not used... Sigh...
// First thing i would do if i could would be to redesign these damned templates!
// And i will one day, so help me Phil, lord of heck!
LinkedList currentMenu = getMenuById(menus,menu_param[0]) ;
if ( currentMenu == null ) {
String menubuff_str = "" ;
if (menumode) {
log.log(Log.WILD, "We don't seem to have a menu... got null.") ;
menubuff_str = "<!-- inserted by imcms --><tr><td>"+getMenuModePrefix(patMat,menu_param[0],tags)+"</td></tr><!-- empty menu --><tr><td>"+getMenuModeSuffix(tags)+"</td></tr><!-- /inserted by imcms -->" ;
}
sb.replace( menurowsindex, sbindex,menubuff_str) ;
return ;
}
// Get an iterator over the elements in the current menu
Iterator menuit = currentMenu.iterator() ;
StringBuffer menubuff = new StringBuffer() ;
String menurowstr = menu_rows[0] ;
// If the "rows"-attribute of this menu is larger than 1, we need the second row too.
// Note that if there is only one row, we add the #adminStop# after parsing for <tr><td>
if ( menu_rows.length>1 ) {
menurowstr += "<!-- menuitem 2nd row -->#adminStop#"+menu_rows[1]+"<!-- /menuitem 2nd row -->" ;
}
// OK, menurowstr now contains a row of the menu, with all the tags and stuff.
// Now we need to check if it starts with <tr> or <td>
// and do something about it.
// These patterns are supposed to match <(/)tr whatever> and <(/)td whatever> at end and beginning of the string.
String trstart = "\r\n<!-- tr --><tr>" ; // Html-tag for start of tablerow (menurow)
String trstop = "</tr><!-- /tr -->\r\n" ; // Html-tag for end of tablerow (menurow)
String tdstart = "\r\n<!-- td --><td valign=\"top\">" ; // Html-tag for start of table-cell (menuelement)
String tdstop = "</td><!-- /td -->\r\n" ; // Html-tag for end of table-cell (menuelement)
Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
/** Added 010212 **/
if ( patMat.contains(menurowstr,TR_START_PATTERN) ) {
trstart = "\r\n<!-- t tr -->"+patMat.getMatch().group(1) ;
log.log(Log.WILD, "Using the menu's own tr.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TR_START_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TR_STOP_PATTERN) ) {
trstop = patMat.getMatch().group(1) + "<!-- t /tr -->\r\n" ;
log.log(Log.WILD, "Using the menu's own /tr.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TR_STOP_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TD_START_PATTERN) ) {
tdstart = "\r\n<!-- t td -->"+patMat.getMatch().group(1) ;
log.log(Log.WILD, "Using the menu's own td.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TD_START_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TD_STOP_PATTERN) ) {
tdstop = patMat.getMatch().group(1)+"<!-- t /td -->\r\n" ;
log.log(Log.WILD, "Using the menu's own /td.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TD_STOP_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
/** End of added 010212 **/
//// Make sure we add tags for the html-tags for inactive and archived documents,
//menurowstr = "#adminStart#"+menurowstr ;
// Add #adminStop# to the end, if there is only one line.
// Note that if there is more than one line, we do it before
// all the regexing for <tr><td>
if ( menu_rows.length==1 ) {
menurowstr = "#adminStart#"+menurowstr+"#adminStop#" ;
} else {
menurowstr = "#adminStart#"+menurowstr ;
}
// for each element of the menu...
log.log(Log.WILD, "Starting to parse the "+currentMenu.size()+" items of the menu." ) ;
MapSubstitution mapsubstitution = new MapSubstitution() ;
for ( int rowcount = 0 ; menuit.hasNext() ; ) {
if ( rowcount % menu_param[2]==0 ) { // If this is a new tablerow... (menu_param[2] contains the number of columns per row)
menubuff.append(trstart) ; // append tag for new row: "<TR>", or whatever was already used in the template.
}
menubuff.append(tdstart) ; // Begin new cell: "<TD>", or whatever was already used in the template.
// Here we are going to output one menuitem.
// All data is stored in a Properties, remember?
//StringBuffer menurow = new StringBuffer(menurowstr) ; // Allocate some workroom
Properties props = (Properties)menuit.next() ; // Retrieve the tags and data for this menuitem...
mapsubstitution.setMap(props, true) ;
log.log(Log.WILD, "Parsing the individual tags of one menuitem.") ;
String menurow = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,mapsubstitution,menurowstr,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
menubuff.append(menurow+tdstop) ; // OK... one row done. Append it to the menubuffer and end the cell.
++rowcount ; // And, of course... increase the rowcount.
if ( rowcount%menu_param[2]==0 ) { // If next row is a new tablerow...
menubuff.append(trstop) ; // append </tr>, or the equivalent from the template.
}
}
String menubuff_str = menubuff.toString() ;
if (menumode) {
log.log(Log.WILD, "We're in 'menumode'") ;
menubuff_str = "<tr><td>"+getMenuModePrefix(patMat,menu_param[0],tags)+"</td></tr><!-- menu -->"+menubuff_str+"<!-- /menu --><tr><td>"+getMenuModeSuffix(tags)+"</td></tr>" ;
}
log.log(Log.WILD, "We're finished with this menu."+sbindex) ;
// Yay! One menu done. Insert into the pagebuffer...
sb.replace( menurowsindex, sbindex,menubuff_str) ;
//sb.insert(sbindex,menubuff_str) ;
}
/**
Returns the menubuttonrow
*/
public String getMenuButtons(String meta_id, User user) {
try {
// Get the users language prefix
String lang_prefix = null ;
String sqlStr = "select lang_prefix from lang_prefixes where lang_id = "+user.getInt("lang_id") ; // Find language
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
if ( data.size() > 0 ) {
lang_prefix = data.elementAt(0).toString() ;
}
dbc.clearResultSet() ;
// Find out what permissions the user has
sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector permissions = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (permissions.size() == 0) {
return "" ;
}
StringBuffer tempbuffer = null ;
StringBuffer templatebuffer = null ;
StringBuffer superadmin = null ;
int doc_type = getDocType(Integer.parseInt(meta_id)) ;
try {
String tempbuffer_filename = lang_prefix + "/admin/adminbuttons/adminbuttons"+doc_type+".html" ;
String templatebuffer_filename = lang_prefix + "/admin/adminbuttons/adminbuttons.html" ;
String superadmin_filename = lang_prefix + "/admin/adminbuttons/superadminbutton.html" ;
tempbuffer = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, tempbuffer_filename))) ;
templatebuffer = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, templatebuffer_filename))) ;
superadmin = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, superadmin_filename))) ;
} catch(IOException e) {
log.log(Log.ERROR, "An error occurred reading adminbuttonfile", e );
return null ;
}
int user_permission_set_id = Integer.parseInt((String)permissions.elementAt(0)) ;
int user_permission_set = Integer.parseInt((String)permissions.elementAt(1)) ;
// Replace #getMetaId# with meta_id
String doctype = dbc.sqlQueryStr("select type from doc_types where doc_type = "+doc_type) ;
imcode.util.AdminButtonParser doc_tags = new imcode.util.AdminButtonParser(m_TemplateHome + lang_prefix + "/admin/adminbuttons/adminbutton"+doc_type+"_", ".html",user_permission_set_id,user_permission_set) ;
doc_tags.put("getMetaId",meta_id) ;
imcode.util.Parser.parseTags(tempbuffer,'#'," <>\n\r\t",(Map)doc_tags,true,1) ;
imcode.util.AdminButtonParser tags = new imcode.util.AdminButtonParser(m_TemplateHome + lang_prefix + "/admin/adminbuttons/adminbutton_", ".html",user_permission_set_id,user_permission_set) ;
tags.put("getMetaId",meta_id) ;
tags.put("doc_buttons",tempbuffer.toString()) ;
tags.put("doc_type",doctype) ;
Vector temp = (Vector)dbc.sqlQuery("select user_id from user_roles_crossref where role_id = 0 and user_id = "+user.getInt("user_id")) ;
if ( temp.size() > 0 ) {
tags.put("superadmin",superadmin.toString()) ;
} else {
tags.put("superadmin","") ;
}
imcode.util.Parser.parseTags(templatebuffer,'#'," <>\n\r\t",(Map)tags,true,1) ;
return templatebuffer.toString() ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"Error occurred while parsing the adminbuttons.",ex) ;
return null ;
}
}
/**
Returns the menubuttonrow
*/
public String getMenuButtons(int meta_id, User user) {
return getMenuButtons(String.valueOf(meta_id),user) ;
}
protected StringBuffer loadFile(File file) {
StringBuffer tempbuffer = new StringBuffer() ;
try {
char[] charbuffer = new char[16384] ;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"8859_1"));
// Load the file
int chars_read = 0 ;
while (-1 < (chars_read = br.read(charbuffer))) {
tempbuffer.append(charbuffer,0,chars_read) ;
}
br.close();
} catch (IOException ex) {
log.log(Log.ERROR, "File not found during parsing.", ex) ;
tempbuffer.append(ex.getMessage()) ;
}
return tempbuffer ;
}
public void saveText(int meta_id,imcode.server.User user,int txt_no,String text,int toHTMLSpecial) {
String sqlStr = "" ;
Table meta ;
String htmlStr = "" ;
// create a db connection an get meta data
sqlStr = "delete from texts where meta_id = " + meta_id
+" and name = "+txt_no ;
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
// update text
sqlStr = "insert into texts (text,type,meta_id,name)" ;
if ( toHTMLSpecial == 0)
text = imcode.server.HTMLConv.toHTMLSpecial(text) ;
// allways convert character >= 160
text = imcode.server.HTMLConv.toHTML(text) ;
sqlStr += " values('" + text + "',"
+ toHTMLSpecial + ","+meta_id+","+txt_no+")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("Text " + txt_no + " in " + "[" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save an imageref.
*/
public void saveImage(int meta_id,User user,int img_no,imcode.server.Image image) {
String sqlStr = "" ;
Table meta ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select * from images where meta_id = "+meta_id+" and name = "+img_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
if (((Vector)dbc.executeQuery()).size() > 0) {
sqlStr = "update images" ;
sqlStr += " set imgurl = '" + image.getImageRef() + "'" ;
sqlStr += ",width = " + image.getImageWidth() ;
sqlStr += ",height = " + image.getImageHeight() ;
sqlStr += ",border = " + image.getImageBorder() ;
sqlStr += ",v_space = " + image.getVerticalSpace() ;
sqlStr += ",h_space = " + image.getHorizontalSpace() ;
sqlStr += ",image_name = '" + image.getImageName() + "'" ;
sqlStr += ",target = '" + image.getTarget() + "'" ;
sqlStr += ",target_name = '" + image.getTargetName() + "'" ;
sqlStr += ",align = '" + image.getImageAlign() + "'" ;
sqlStr += ",alt_text = '" + image.getAltText() + "'" ;
sqlStr += ",low_scr = '" + image.getLowScr() + "'" ;
sqlStr += ",linkurl = '" + image.getImageRefLink() + "'" ;
sqlStr += " where meta_id = " + meta_id ;
sqlStr += " and name = " + img_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
} else {
sqlStr = "insert into images (imgurl, width, height, border, v_space, h_space, image_name, target, target_name, align, alt_text, low_scr, linkurl, meta_id, name)"
+ " values('" + image.getImageRef() + "'" ;
sqlStr += "," + image.getImageWidth() ;
sqlStr += "," + image.getImageHeight() ;
sqlStr += "," + image.getImageBorder() ;
sqlStr += "," + image.getVerticalSpace() ;
sqlStr += "," + image.getHorizontalSpace() ;
sqlStr += ",'" + image.getImageName() + "'" ;
sqlStr += ",'" + image.getTarget() + "'" ;
sqlStr += ",'" + image.getTargetName() + "'" ;
sqlStr += ",'" + image.getImageAlign() + "'" ;
sqlStr += ",'" + image.getAltText() + "'" ;
sqlStr += ",'" + image.getLowScr() + "'" ;
sqlStr += ",'" + image.getImageRefLink() + "'" ;
sqlStr += "," + meta_id ;
sqlStr += "," + img_no+")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
}
this.updateLogs("ImageRef " + img_no + " =" + image.getImageRef() +
" in " + "[" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
// close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Save template -> text_docs, sort
*/
public void saveTextDoc(int meta_id,imcode.server.User user,imcode.server.Table doc) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update text_docs\n" ;
sqlStr += "set template_id= " + doc.getString("template") ;
sqlStr += ", group_id= " + doc.getString("group_id") ;
sqlStr += " where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("Text docs [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
}
/**
* <p>Delete a doc and all data related.
*/
public void deleteDocAll(int meta_id,imcode.server.User user) {
String sqlStr = "DocumentDelete " + meta_id ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Document " + "[" + meta_id + "] ALL deleted by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Add a existing doc.
*/
public void addExistingDoc(int meta_id,User user,int existing_meta_id,int doc_menu_no) {
String sqlStr = "" ;
int newSortNo ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// test if this is the first child
sqlStr = "select to_meta_id from childs where meta_id =" + meta_id + " and menu_sort = " + doc_menu_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector child_test = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( child_test.size() > 0 ) {
// update child table
sqlStr = "select max(manual_sort_order) from childs\n" ;
sqlStr += "where meta_id = " + meta_id + " and menu_sort = " + doc_menu_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector max_sort_no = (Vector)dbc.executeQuery() ;
if ( max_sort_no.size() > 0 )
newSortNo = Integer.parseInt(max_sort_no.elementAt(0).toString()) + 10 ;
else
newSortNo = 500 ;
dbc.clearResultSet() ;
} else
newSortNo = 500 ;
sqlStr = "insert into childs(meta_id,to_meta_id,menu_sort,manual_sort_order)\n" ;
sqlStr += "values(" + meta_id + "," + existing_meta_id + "," + doc_menu_no + "," + newSortNo + ")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("(AddExisting) Child links for [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Save manual sort.
*/
public void saveManualSort(int meta_id,User user,java.util.Vector childs,
java.util.Vector sort_no) {
String sqlStr = "" ;
// create a db connection
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// m_output.append("Childs" + childs.toString() + "\n");
// m_output.append("sort_no" + sort_no.toString() + "\n");
// update child table
for ( int i = 0 ; i < childs.size() ; i++ ) {
sqlStr = "update childs\n" ;
sqlStr += "set manual_sort_order = " + sort_no.elementAt(i).toString() + "\n" ;
sqlStr += "where meta_id = " + meta_id + " and \n" ;
sqlStr += "to_meta_id=" + childs.elementAt(i).toString() ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
// m_output.append(" Done \n");
this.updateLogs("Child manualsort for [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Delete childs from a menu.
*/
public void deleteChilds(int meta_id,int menu,User user,String childsThisMenu[]) {
String sqlStr = "" ;
String childStr = "[" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
for ( int i = 0 ; i < childsThisMenu.length ; i++ ) {
sqlStr = "delete from childs\n" ;
sqlStr += " where to_meta_id =" + childsThisMenu[i] + "\n" ;
sqlStr += " and meta_id = " + meta_id ;
sqlStr += " and menu_sort = "+ menu ;
// sqlStr += "delete from meta where meta_id =" + meta_id + "\n" ;
// sqlStr += "delete from text_docs where meta_id =" + meta_id + "\n" ;
// sqlStr += "delete from texts where meta_id =" + meta_id + "\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
childStr += childsThisMenu[i] ;
if ( i < childsThisMenu.length -1 )
childStr += "," ;
}
childStr += "]" ;
this.updateLogs("Childs " + childStr + " from " +
"[" + meta_id + "] deleted by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
Makes copies of the documents given in the String-array, and inserts them into the given document and menu.
@param meta_id The document to insert into
@param doc_menu_no The menu to insert into
@param user The user
@param childsThisMenu The id's to copy.
**/
public void copyDocs( int meta_id, int doc_menu_no, User user, String[] childsThisMenu) {
if (childsThisMenu != null && childsThisMenu.length > 0) {
StringBuffer childs = new StringBuffer("CopyDocs '"+childsThisMenu[0]) ;
for (int i=1; i<childsThisMenu.length; ++i) {
childs.append(",").append(childsThisMenu[i]) ;
}
childs.append("',"+meta_id+","+doc_menu_no+","+user.getUserId()) ;
sqlUpdateProcedure(childs.toString()) ;
}
}
/**
* Archive childs for a menu.
**/
public void archiveChilds(int meta_id,User user,String childsThisMenu[]) {
String sqlStr = "" ;
String childStr = "[" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
for ( int i = 0 ; i < childsThisMenu.length ; i++ ) {
sqlStr = "update meta" ;
sqlStr += " set archive = 1" ;
sqlStr += " where meta_id =" + childsThisMenu[i] + "\n";
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
childStr += childsThisMenu[i] ;
if ( i < childsThisMenu.length -1 )
childStr += "," ;
}
childStr += "]" ;
this.updateLogs("Childs " + childStr + " from " +
"[" + meta_id + "] archived by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Check if browser doc. *
*/
public int isBrowserDoc(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
int to_meta_id ;
to_meta_id = meta_id ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 6 ) {
sqlStr = "select to_meta_id from browser_docs where meta_id = " + meta_id ;
sqlStr += " and browser = '" + user.getBrowserStr() + "'";
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_to_meta_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
to_meta_id = Integer.parseInt(vec_to_meta_id.elementAt(0).toString()) ;
if (to_meta_id == -1) {
sqlStr = "select to_meta_id from browser_docs where meta_id = " + meta_id ;
sqlStr += " and browser = 'other_" + user.getBrowserInfo()[2] + "'" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
vec_to_meta_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
to_meta_id = Integer.parseInt(vec_to_meta_id.elementAt(0).toString()) ;
}
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return to_meta_id ;
}
/**
* <p>Save an url document.
*/
public void saveUrlDoc(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// update url doc
sqlStr = "update url_docs\n" ;
sqlStr += "set url_ref ='" + doc.getString("url_ref") + "'" ;
sqlStr += ",url_txt ='" + doc.getString("url_txt") + "'" ;
sqlStr += " where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("UrlDoc [" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save a new url document.
*/
public void saveNewUrlDoc(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "insert into url_docs(meta_id,frame_name,target,url_ref,url_txt,lang_prefix)\n" ;
sqlStr += "values(" + meta_id + ",'" + doc.getString("frame_name") + "','" ;
sqlStr += doc.getString("destination") + "','" ;
sqlStr += doc.getString("url_ref") + "','" ;
sqlStr += doc.getString("url_txt") ;
sqlStr += "','se')" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.activateChild(meta_id,user) ;
this.updateLogs("UrlDoc [" + meta_id + "] created by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>List all archived docs.
*/
public String listArchive(int meta_id,User user) {
String sqlStr = "" ;
String htmlStr = "" ;
Vector child_meta_headlines = new Vector() ;
Vector childs = new Vector() ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// get child meta_headline
sqlStr = "select meta.meta_headline from meta,childs " ;
sqlStr += "where meta.meta_id = childs.to_meta_id and childs.meta_id = " ;
sqlStr += meta_id ;
sqlStr += " and meta.archive=1" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
child_meta_headlines = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// get childs
sqlStr = "select to_meta_id from meta,childs" ;
sqlStr += " where meta.meta_id = childs.to_meta_id" ;
sqlStr += " and childs.meta_id =" + meta_id ;
sqlStr += " and meta.archive=1" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
childs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
htmlStr += "<HTML><HEAD><TITLE>Janusarkivet</TITLE></HEAD><BODY>\n" ;
htmlStr += "<LINK href=\"../css/CSS-MALL/janus.css\" rel=stylesheet type=text/css>\n" ;
htmlStr += "<SPAN class=rubrik1>\n" ;
htmlStr += "<CENTER><BR>" ;
htmlStr += "<IMG SRC=\"" + m_ImageFolder + "arkivet.gif\" width=\"500\" height=\"27\">\n" ;
htmlStr += "<BR><BR><TABLE border=0 width=* cellpadding=0 cellspacing=8>" ;
htmlStr += "<TR><TD valign=\"top\" width=\"*\">" ;
for ( int i = 0 ; i < childs.size() ; i++ ) {
htmlStr += "<input type=checkbox name=\"archiveBox\" value=" ;
htmlStr += "\"" + childs.elementAt(i).toString() + "\">";
htmlStr += "<IMG SRC=\"" + m_ImageFolder + "pil2.gif\" width=\"7\" height=\"10\">" ;
htmlStr += child_meta_headlines.elementAt(i).toString() + "<BR>\n";
}
htmlStr += "</TD></TR>\n" ;
htmlStr += "</TABLE></CENTER></SPAN>\n" ;
htmlStr += "</BODY></HTML>" ;
return htmlStr ;
}
/**
* <p>Check if url doc.
*/
public imcode.server.Table isUrlDoc(int meta_id,User user) {
String sqlStr = "" ;
int to_meta_id ;
imcode.server.Table url_doc ;
to_meta_id = meta_id ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 5 ) {
sqlStr = "select * from url_docs where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
url_doc = new Table(dbc.executeQuery()) ;
url_doc.addFieldNames(dbc.getMetaData()) ;
dbc.clearResultSet() ;
} else
url_doc = null ;
//close connection
dbc.closeConnection() ;
dbc = null ;
return url_doc ;
}
/**
* <p>Save a new frameset.
*/
public void saveNewFrameset(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "insert into frameset_docs(meta_id,frame_set)\n" ;
sqlStr += "values(" + meta_id + ",'" + doc.getString("frame_set") + "')" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.activateChild(meta_id,user) ;
this.updateLogs("FramesetDoc [" + meta_id + "] created by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save a frameset
*/
public void saveFrameset(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "update frameset_docs\n";
sqlStr += "set frame_set ='" + doc.getString("frame_set") + "'\n";
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
this.updateLogs("FramesetDoc [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Update logs.
*/
public void updateLogs(String event) {
String sqlStr = "" ;
java.util.Calendar cal = java.util.Calendar.getInstance() ;
String year = Integer.toString(cal.get(Calendar.YEAR)) ;
int month = Integer.parseInt(Integer.toString(cal.get(Calendar.MONTH))) + 1;
int day = Integer.parseInt(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) ;
int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR))) ;
int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ;
int sec = Integer.parseInt(Integer.toString(cal.get(Calendar.SECOND))) ;
String dateToDay = year + "-" ;
dateToDay += month < 10 ? "0" + Integer.toString(month) : Integer.toString(month) ;
dateToDay += "-" ;
dateToDay += day < 10 ? "0" + Integer.toString(day) : Integer.toString(day) + " " ;
dateToDay += " " ;
dateToDay += hour < 10 ? "0" + Integer.toString(hour) : Integer.toString(hour) ;
dateToDay += ":" ;
dateToDay += min < 10 ? "0" + Integer.toString(min) : Integer.toString(min) ;
dateToDay += ":" ;
dateToDay += sec < 10 ? "0" + Integer.toString(min) : Integer.toString(sec) ;
dateToDay += ".000" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "insert into main_log(log_datetime,event)\n" ;
sqlStr += "values('" + dateToDay + "','" + event + "')\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Update track log.
*/
public void updateTrackLog(int from_meta_id,int to_meta_id,imcode.server.User user) {
String sqlStr = "" ;
int cookie_id = user.getInt("user_id") ;
java.util.Calendar cal = java.util.Calendar.getInstance() ;
String year = Integer.toString(cal.get(Calendar.YEAR)) ;
int month = Integer.parseInt(Integer.toString(cal.get(Calendar.MONTH))) + 1;
int day = Integer.parseInt(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) ;
int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR))) ;
int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ;
int sec = Integer.parseInt(Integer.toString(cal.get(Calendar.SECOND))) ;
String dateToDay = year + "-" ;
dateToDay += month < 10 ? "0" + Integer.toString(month) : Integer.toString(month) ;
dateToDay += "-" ;
dateToDay += day < 10 ? "0" + Integer.toString(day) : Integer.toString(day) + " " ;
dateToDay += " " ;
dateToDay += hour < 10 ? "0" + Integer.toString(hour) : Integer.toString(hour) ;
dateToDay += ":" ;
dateToDay += min < 10 ? "0" + Integer.toString(min) : Integer.toString(min) ;
dateToDay += ":" ;
dateToDay += sec < 10 ? "0" + Integer.toString(min) : Integer.toString(sec) ;
dateToDay += ".000" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "insert into track_log(user_id,log_datetime,from_meta_id,to_meta_id,cookie_id)\n" ;
sqlStr += "values(" + user.getInt("user_id") + ",'"
+ dateToDay + "'," + from_meta_id + "," + to_meta_id + "," + cookie_id +")\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Check if frameset doc. *
*/
public String isFramesetDoc(int meta_id,User user) {
String sqlStr = "" ;
Vector frame_set = new Vector() ;
String html_str = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 7 ) {
sqlStr = "select frame_set from frameset_docs where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
frame_set = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
html_str = frame_set.elementAt(0).toString() ;
} else
html_str = null ;
//close connection
dbc.closeConnection() ;
dbc = null ;
return html_str ;
}
/**
* <p>Search docs.
*/
public Vector searchDocs(int meta_id,User user,String question_str,
String search_type,String string_match,String search_area) {
// search_area : all,not_archived,archived
String sqlStr = "" ;
Vector tokens = new Vector() ;
Vector meta_docs = new Vector() ;
String match = "%" ;
if ( string_match.equals("match") )
match = "" ;
StringTokenizer parser = new StringTokenizer(question_str.trim()," ") ;
while ( parser.hasMoreTokens() )
tokens.addElement(parser.nextToken()) ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
if ( !search_type.equals("atc_icd10") ) {
// text fields // texts.meta_id
if (tokens.size() > 0)
sqlStr += "select distinct meta.meta_id,meta.meta_headline,meta.meta_text from texts,meta where (" ;
for ( int i = 0 ; i < tokens.size() ; i++ ) {
sqlStr += " text like '%" + tokens.elementAt(i).toString() + match + "'" ;
if ( i < tokens.size() -1 )
sqlStr += " " + search_type + " " ;
}
sqlStr += ") " ;
if (tokens.size() > 0) {
sqlStr += " and meta.meta_id = texts.meta_id" ;
sqlStr += " and meta.activate = 1 and meta.disable_search = 0\n" ;
}
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
if ( tokens.size() > 0 ) {
sqlStr += "\n union \n" ;
}
// meta_headline
if (tokens.size() > 0)
sqlStr += "select distinct meta_id,meta_headline,meta_text from meta where " ;
for ( int i = 0 ; i < tokens.size() ; i++ ) {
sqlStr += " (meta_headline like '%" + tokens.elementAt(i).toString() + match + "' " ;
sqlStr += " or meta_text like '%" + tokens.elementAt(i).toString() + match + "' " ;
sqlStr += " or classification like '%" + tokens.elementAt(i).toString() + match + "') " ;
if ( i < tokens.size() -1 )
sqlStr += " " + search_type + " " ;
}
sqlStr += " and activate = 1 and disable_search = 0\n" ;
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
if ( tokens.size() > 0 ) {
sqlStr += " order by meta.meta_id" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
meta_docs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
} else {
sqlStr = "select distinct meta_id,meta_headline,meta_text from meta where " ;
sqlStr += "classification = '" + question_str + "'";
sqlStr += " and activate = 1 and disable_search = 0\n" ;
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
meta_docs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return meta_docs ;
}
/**
* <p>Check if external doc.
*/
public ExternalDocType isExternalDoc(int meta_id,User user) {
String sqlStr = "" ;
ExternalDocType external_doc = null ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
int doc_type = Integer.parseInt(vec_doc_type.elementAt(0).toString()) ;
if ( doc_type > 100 ) {
for ( int i = 0 ; i < m_ExDoc.length && m_ExDoc[i] != null ; i++ )
if ( m_ExDoc[i].getDocType() == doc_type ) {
// external_doc = new ExternalDocType(m_ExDoc[i].getDocType(),m_ExDoc[i].getCallServlet(),
// m_ExDoc[i].getDocName(),m_ExDoc[i].getParamStr()) ;
external_doc = m_ExDoc[i] ;
}
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return external_doc ;
}
/**
* <p>Remove child from child-table.
*/
public void removeChild(int meta_id,int parent_meta_id,User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "delete from childs where meta_id = " + parent_meta_id ;
sqlStr += "and to_meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] removed from " + parent_meta_id +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Activate child to child-table.
*/
public void activateChild(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update meta\n" ;
sqlStr += "set activate=1\n" ;
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] activated " +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
Deactivate (sigh) child from child-table.
**/
public void inActiveChild(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update meta\n" ;
sqlStr += "set activate=0\n" ;
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] made inactive " +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Send a sqlquery to the database and return a string array.
*/
public String[] sqlQuery(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a sqlquery to the database and return a string array.
*/
public String[] sqlQuery(String sqlQuery,String catalog) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery(catalog) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a sqlquery to the database and return a string
*/
public String sqlQueryStr(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data.size() > 0 )
return data.elementAt(0).toString() ;
else
return null ;
}
/**
* <p>Send a sql update query to the database
*/
public void sqlUpdateQuery(String sqlStr) {
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
dbc.executeUpdateQuery();
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Send a procedure to the database and return a string array
*/
public String[] sqlProcedure(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
// dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a procedure to the database and return a string.
*/
public String sqlProcedureStr(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
//dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if (data != null) {
if ( data.size() > 0)
return data.elementAt(0).toString() ;
else
return null ;
} else
return null ;
}
/**
* <p>Send a procedure to the database and return a int.
*/
public int sqlProcedureInt(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
//dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null )
return Integer.parseInt(data.elementAt(0).toString()) ;
else
return -1 ;
}
/**
* <p>Send a update procedure to the database
*/
public void sqlUpdateProcedure(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
dbc.executeUpdateProcedure();
dbc.closeConnection() ;
dbc = null ;
}
/**
Parse doc replace variables with data
*/
public String parseDoc(String htmlStr,java.util.Vector variables) {
try {
String[] foo = new String[variables.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo)) ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"parseDoc(String,Vector): RuntimeException", ex );
throw ex ;
}
}
/**
Parse doc replace variables with data, uses two vectors
*/
public String parseDoc(String htmlStr,java.util.Vector variables,java.util.Vector data) {
try {
String[] foo = new String[variables.size()] ;
String[] bar = new String[data.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo),(String[])data.toArray(bar)) ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"parseDoc(String,Vector,Vector): RuntimeException", ex );
throw ex ;
}
}
/**
Parse doc replace variables with data , use template
*/
public String parseDoc(java.util.Vector variables, String admin_template_name, String lang_prefix) {
try {
String htmlStr = fileCache.getCachedFileString(new File(m_TemplateHome,lang_prefix+"/admin/"+admin_template_name)) ;
if (variables == null) {
return htmlStr ;
}
String[] foo = new String[variables.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo)) ;
} catch ( RuntimeException e ) {
log.log(Log.ERROR,"parseDoc(Vector, String, String): RuntimeException", e );
throw e ;
} catch ( IOException e ) {
log.log(Log.ERROR,"parseDoc(Vector, String, String): IOException", e );
return "" ;
}
}
/**
* <p>Return the external doctypes templates folder.
*/
public String getExternalTemplateFolder(int meta_id) {
Vector data = new Vector() ;
String folder = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
String sqlStr = "select doc_type,lang_prefix from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( Integer.parseInt(data.elementAt(0).toString()) > 100 )
folder = m_TemplateHome + data.elementAt(1).toString() +
"/" + data.elementAt(0).toString() + "/" ;
else
folder = m_TemplateHome + data.elementAt(1).toString() + "/" ;
return folder ;
}
/**
* <p>Return templatehome.
*/
public String getTemplateHome() {
return m_TemplateHome ;
}
/**
* <p>Return imagehome.
*/
public String getImageHome() {
return m_ImageFolder ;
}
/**
* <p>Return language.
*/
public String getLanguage() {
return m_Language ;
}
/**
* <p>Get internal template folder.
*/
public String getInternalTemplateFolder(int meta_id) {
Vector data = new Vector() ;
String folder = "" ;
if ( meta_id != -1 ) {
DBConnect dbc = new DBConnect(m_conPool) ;
String sqlStr = "select doc_type,lang_prefix from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
folder = m_TemplateHome + data.elementAt(1).toString() + "/" ;
} else
folder = m_TemplateHome ;
return folder ;
}
/**
* <p>Increment session counter.
*/
public int incCounter() {
m_SessionCounter += 1 ;
return m_SessionCounter ;
}
/**
* <p>Get session counter.
*/
public int getCounter() {
return m_SessionCounter ;
}
/**
* <p>Set session counter.
*/
public int setCounter(int value) {
m_SessionCounter = value ;
return m_SessionCounter ;
}
/**
* <p>Set session counter date.
*/
public boolean setCounterDate(String date) {
m_SessionCounterDate = date ;
this.sqlUpdateProcedure("SetSessionCounterDate '" + date + "'") ;
return true ;
}
/**
* <p>Get session counter date.
*/
public String getCounterDate() {
return m_SessionCounterDate ;
}
/**
Remove elements from a vector.
*/
private Vector removeElement(Vector vec,int elements) {
Vector tempVec = new Vector() ;
for ( int i = 0 ; i < vec.size() ; i+=(elements+1) )
tempVec.addElement(vec.elementAt(i+elements)) ;
return tempVec ;
}
/**
Send a sqlQuery to the database and return a string array
Array[0] = number of field in the record
Array[1] - array[n] = metadata
Array[n+1] - array[size] = data
*/
public String[] sqlQueryExt(String sqlQuery) {
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
String[] meta = (String[])dbc.getMetaData() ;
if ( data.size() > 0 ) {
String result[] = new String[data.size() + dbc.getColumnCount() + 1] ;
// no of fields
result[0] = dbc.getColumnCount() + "" ;
// meta
int i = 0 ;
for ( i = 0 ; i < dbc.getColumnCount() ; i++ )
result[i+1] = meta[i] ;
// data
for ( int j = 0 ; j < data.size() ; j++ )
result[j+i+1] = data.elementAt(j).toString() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return result ;
} else {
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return null ;
}
}
/**
Send a procedure to the database and return a string array
Array[0] = number of field in the record
Array[1] - array[n] = metadata
Array[n+1] - array[size] = data
*/
public String[] sqlProcedureExt(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
if ( data != null && data.size() > 0 ) {
String result[] = new String[data.size() + dbc.getColumnCount() + 1] ;
// no of fields
result[0] = dbc.getColumnCount() + "" ;
// meta
int i = 0 ;
for ( i = 0 ; i < dbc.getColumnCount() ; i++ )
result[i+1] = meta[i] ;
// data
for ( int j = 0 ; j < data.size() ; j++ )
result[j+i+1] = data.elementAt(j).toString() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return result ;
} else {
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return null ;
}
}
/**
Send a sqlQuery to the database and return a Hastable
*/
public Hashtable sqlQueryHash(String sqlQuery) {
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
Hashtable result = new Hashtable(columns,0.5f) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
Send a procedure to the database and return a Hashtable
*/
public Hashtable sqlProcedureHash(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
Hashtable result = new Hashtable(columns,0.5f) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
Send a procedure to the database and return a multi string array
*/
public String[][] sqlProcedureMulti(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
data = (Vector)dbc.executeProcedure() ;
int columns = dbc.getColumnCount() ;
if (columns == 0)
return new String[0][0] ;
int rows = data.size() / columns ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
String result[][] = new String[rows][columns] ;
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < columns ; j++) {
result[i][j] = data.elementAt(i * columns + j).toString() ;
}
}
return result ;
}
/**
Send a sqlquery to the database and return a multi string array
*/
public String[][] sqlQueryMulti(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
int columns = dbc.getColumnCount() ;
if (columns == 0)
return new String[0][0] ;
int rows = data.size() / columns ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
String result[][] = new String[rows][columns] ;
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < columns ; j++) {
result[i][j] = data.elementAt(i * columns + j).toString() ;
}
}
return result ;
}
/*
/**
restart server
*/
/*
public void restartServer() {
ImcServer.imc_server.restartServer();
}
*/
/**
get doctype
*/
public int getDocType(int meta_id) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure("GetDocType " + meta_id) ;
Vector data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
if ( data.size() > 0)
return Integer.parseInt(data.elementAt(0).toString()) ;
else
return 0 ;
}
return -1 ;
}
/**
checkDocAdminRights
*/
public boolean checkDocAdminRights(int meta_id, User user) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() > 0 && Integer.parseInt((String)perms.elementAt(0)) < 3 ) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRights(int,User)",ex) ;
throw ex ;
}
}
/**
checkDocRights
*/
public boolean checkDocRights(int meta_id, User user) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() > 0 && Integer.parseInt((String)perms.elementAt(0)) < 4 ) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocRights(int,User)",ex) ;
throw ex ;
}
}
/**
Checks to see if a user has any permission of a particular set of permissions for a document.
@param meta_id The document-id
@param user The user
@param A bitmap containing the permissions.
*/
public boolean checkDocAdminRightsAny (int meta_id, User user, int permission) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
int set_id = Integer.parseInt((String)perms.elementAt(0)) ;
int set = Integer.parseInt((String)perms.elementAt(1)) ;
if (perms.size() > 0
&& set_id == 0 // User has full permission for this document
|| (set_id < 3 && ((set & permission) > 0)) // User has at least one of the permissions given.
) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRightsAny(int,User,int)",ex) ;
throw ex ;
}
}
/**
Checks to see if a user has a particular set of permissions for a document.
@param meta_id The document-id
@param user The user
@param permissions A bitmap containing the permissions.
*/
public boolean checkDocAdminRights (int meta_id, User user, int permission) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() == 0) {
return false ;
}
int set_id = Integer.parseInt((String)perms.elementAt(0)) ;
int set = Integer.parseInt((String)perms.elementAt(1)) ;
if (set_id == 0 // User has full permission for this document
|| (set_id < 3 && ((set & permission) == permission)) // User has all the permissions given.
) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRights(int,User,int)",ex) ;
throw ex ;
}
}
/**
save template to disk
*/
public int saveTemplate(String name, String file_name, byte[] template, boolean overwrite,String lang_prefix) {
BufferedOutputStream out ;
String sqlStr = "" ;
String file ;
String new_template_id = "";
try {
file = new String(template,"8859_1") ;
} catch(UnsupportedEncodingException e) {
return -2 ;
}
int no_of_txt = 0 ;
int no_of_img = 0 ;
int no_of_url = 0 ;
for ( int index=0 ; (index = file.indexOf("#txt",index))!=-1 ; no_of_txt++ )
index += 4 ;
for ( int index=0 ; (index = file.indexOf("#img",index))!=-1 ; no_of_img++ )
index += 4 ;
for ( int index=0 ; (index = file.indexOf("#url",index))!=-1 ; no_of_url++ )
index += 4 ;
// create connectionobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// check if template exists
sqlStr = "select template_id from templates\n" ;
sqlStr += "where simple_name = '" + name + "'" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
Vector template_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if (template_id.size() == 0) {
// get new template_id
sqlStr = "select max(template_id) + 1 from templates\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
new_template_id = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
sqlStr = "insert into templates\n" ;
sqlStr += "values (" + new_template_id + ",'"+file_name+"','"+name +
"','"+ lang_prefix + "'," + no_of_txt+","+no_of_img+","+no_of_url+")" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
} else { //update
if (!overwrite) {
dbc.closeConnection() ;
dbc = null ;
return -1;
}
new_template_id = template_id.elementAt(0).toString() ;
sqlStr = "update templates\n"
+ "set template_name = '" + file_name + "',"
+ "no_of_txt =" + no_of_txt + ","
+ "no_of_img =" + no_of_img + ","
+ "no_of_url =" + no_of_url
+ "where template_id = " + new_template_id ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
dbc.closeConnection() ;
dbc = null ;
File f = new File(m_TemplateHome, "text/" + new_template_id + ".html") ;
// if (!f.exists())
// overwrite = true ;
// save template data
// if (overwrite) {
try {
FileOutputStream fw = new FileOutputStream(f) ;
fw.write(template) ;
fw.flush() ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
// } else {
// return -1;
//
// }
// save template demo
/* if ( demo_template != null) {
if (demo_template.length > 0) {
try {
FileOutputStream fw = new FileOutputStream(m_TemplateHome + lang_prefix + "/text/demo/" + file_name) ;
fw.write(demo_template) ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
}
}*/
// 0 = OK
// -1 = file exist
// -2 = write error
return 0 ;
}
/**
get demo template
*/
public Object[] getDemoTemplate(int template_id) throws IOException {
//String str = "" ;
StringBuffer str = new StringBuffer() ;
BufferedReader fr = null;
String suffix = null;
String[] suffixList =
{"jpg","jpeg","gif","png","html","htm"};
for(int i=0;i<=5;i++)
{ // Looking for a template with one of six suffixes
String path = m_TemplateHome + "/text/demo/" + template_id + "." + suffixList[i];
File fileObj = new File(path);
long date = 0;
long fileDate = fileObj.lastModified();
if (fileObj.exists() && fileDate>date)
{
// if a template was not properly removed, the template
// with the most recens modified-date is returned
date = fileDate;
try {
fr = new BufferedReader(new InputStreamReader(new FileInputStream(fileObj),"8859_1")) ;
suffix = suffixList[i];
} catch(IOException e) {
return null ; //Could not read
}
} // end IF
} // end FOR
char[] buffer = new char[4096] ;
try {
int read ;
while ( (read = fr.read(buffer,0,4096)) != -1 ) {
str.append(buffer,0,read) ;
}
} catch(IOException e) {
return null ;
}
catch(NullPointerException e) {
return null ;
}
return new Object[] {suffix , str.toString().getBytes("8859_1")} ; //return the buffer
}
/**
get template
*/
public byte[] getTemplate(int template_id) throws IOException {
String str = "" ;
BufferedReader fr ;
try {
fr = new BufferedReader( new FileReader(m_TemplateHome + "/text/" + template_id + ".html")) ;
} catch(FileNotFoundException e) {
log.log(Log.INFO, "Failed to find template number "+template_id) ;
return null ;
}
try {
int temp ;
while ((temp = fr.read())!=-1) {
str+=(char)temp;
}
} catch(IOException e) {
log.log(Log.INFO, "Failed to read template number "+template_id) ;
return null ;
}
return str.getBytes("8859_1") ;
}
/**
delete template from db/disk
*/
public void deleteTemplate(int template_id) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// delete from database
sqlStr = "delete from templates_cref\n" ;
sqlStr += "where template_id = " + template_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// delete from database
sqlStr = "delete from templates\n" ;
sqlStr += "where template_id = " + template_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
// test if template exists and delete it
File f = new File(m_TemplateHome + "/text/" + template_id + ".html") ;
if (f.exists()) {
f.delete() ;
}
}
/**
save demo template
*/
public int saveDemoTemplate(int template_id,byte [] data, String suffix) {
// save template demo
// See if there are templete_id:s with other file-formats and delete them
// WARNING: Uggly Code
String[] suffixes = {"jpg","jpeg","gif","png","htm","html"};
for(int i=0;i<=5;i++) {
File file = new File(m_TemplateHome + "/text/demo/" + template_id + "." + suffixes[i]);
if(file.exists())
file.delete();
// doesn't always delete the file, made sure the right template is
// shown using the file-date & time in getDemoTemplate
}
try {
FileOutputStream fw = new FileOutputStream(m_TemplateHome + "/text/demo/" + template_id + "." + suffix) ;
fw.write(data) ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
return 0 ;
}
/**
save templategroup
*/
public void saveTemplateGroup(String group_name,User user) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// get lang prefix
sqlStr = "select lang_prefix from users,lang_prefixes\n" ;
sqlStr += "where users.lang_id = lang_prefixes.lang_id\n" ;
sqlStr += "and user_id =" + user.getInt("user_id") ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
String lang_prefix = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
// get new group_id
sqlStr = "select max(group_id) + 1 from templategroups\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
String new_group_id = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
// change name
sqlStr = "insert into templategroups\n" ;
sqlStr += "values(" + new_group_id + ",'" + lang_prefix + "','" + group_name + "')" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
delete templategroup
*/
public void deleteTemplateGroup(int group_id) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// change name
sqlStr = "delete from templategroups\n" ;
sqlStr += "where group_id = " + group_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
change templategroupname
*/
public void changeTemplateGroupName(int group_id,String new_name) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// change name
sqlStr = "update templategroups\n" ;
sqlStr += "set group_name = '" + new_name + "'" ;
sqlStr += "where group_id = " + group_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
unassign template from templategroups
*/
public void unAssignTemplate(int template_id,int group_id[]) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// delete current refs
for( int i = 0 ; i < group_id.length ; i++) {
sqlStr = "delete from templates_cref\n" ;
sqlStr += "where template_id = " + template_id ;
sqlStr += "and group_id = " + group_id[i] ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
dbc.closeConnection() ;
dbc = null ;
}
/** get server date
*/
public java.util.Date getCurrentDate() {
return new java.util.Date() ;
}
final static FileFilter DEMOTEMPLATEFILTER = new FileFilter () {
public boolean accept (File file) {
return file.length() > 0 ;
}
} ;
// get demotemplates
public String[] getDemoTemplateList() {
File demoDir = new File(m_TemplateHome + "/text/demo/" ) ;
File[] file_list = demoDir.listFiles(DEMOTEMPLATEFILTER) ;
String[] name_list = new String[file_list.length] ;
if (file_list != null) {
for(int i = 0 ; i < name_list.length ; i++) {
String filename = file_list[i].getName() ;
int dot = filename.indexOf(".") ;
name_list[i] = dot > -1 ? filename.substring(0,dot) : filename ;
}
} else {
return new String[0];
}
return name_list;
}
// delete demotemplate
public int deleteDemoTemplate(int template_id) {
File f = new File(m_TemplateHome + "/text/demo/" + template_id + ".html") ;
if (f.exists()) {
f.delete() ;
return 0;
}
return -2 ;
}
/**
* <p>Return language. Returns the langprefix from the db. Takes a lang id
as argument. Will return null if something goes wrong.
Example: If the language id number for swedish is 1. then the call
myObject.getLanguage("1") will return 'se'
That is, provided that the prefix for swedish is 'se', which it isn't.
Or rather, it shouldn't be.
*/
public String getLanguage(String lang_id) {
return sqlProcedureStr("GetLangPrefixFromId " + lang_id) ;
}
/** Fetch the systemdata from the db */
protected SystemData getSystemDataFromDb() {
/** Fetch everything from the DB */
String serverMaster[] = this.sqlProcedure("ServerMasterGet") ;
String webMaster[] = this.sqlProcedure("WebMasterGet") ;
String systemMessage = this.sqlProcedureStr("SystemMessageGet") ;
/** Create a new SystemData object */
SystemData sd = new SystemData() ;
/** Store everything in the object */
sd.setSystemMessage(systemMessage) ;
if (serverMaster.length > 0) {
sd.setServerMaster(serverMaster[0]) ;
if (serverMaster.length > 1) {
sd.setServerMasterAddress(serverMaster[1]) ;
}
}
if (webMaster.length > 0) {
sd.setWebMaster(webMaster[0]) ;
if (webMaster.length > 1) {
sd.setWebMasterAddress(webMaster[1]) ;
}
}
return sd ;
}
public SystemData getSystemData () {
return sysData ;
}
public void setSystemData (SystemData sd) {
sysData = sd ;
String sqlStr = "WebMasterSet '"+sd.getWebMaster()+"','"+sd.getWebMasterAddress()+"'" ;
sqlUpdateProcedure(sqlStr) ;
sqlStr = "ServerMasterSet '"+sd.getServerMaster()+"','"+sd.getServerMasterAddress()+"'" ;
sqlUpdateProcedure(sqlStr) ;
sqlStr = "SystemMessageSet '"+sd.getSystemMessage()+"'" ;
sqlUpdateProcedure(sqlStr) ;
}
/**
Returns the information for each meta id passed as argument.
*/
public Hashtable ExistingDocsGetMetaIdInfo(String[] meta_id) {
// Lets build a comma separed string to send to the sproc
StringBuffer sBuf = new StringBuffer() ;
for( int i = 0; i< meta_id.length; i++ ) {
sBuf.append(meta_id[i]) ;
if(i != meta_id.length)
sBuf.append(",") ;
}
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure("ExistingDocsGetSelectedMetaIds ", sBuf.toString() ) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
// Lets build the result into an hashtable
Hashtable result = new Hashtable(columns,0.5f) ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
* Returns an array with with all the documenttypes stored in the database
* the array consists of pairs of id:, value. Suitable for parsing into select boxes etc.
*/
public String[] getDocumentTypesInList(String langPrefixStr) {
return this.sqlProcedure("GetDocTypes '" + langPrefixStr + "'" ) ;
}
/**
* Returns an hashtable with with all the documenttypes stored in the database
* the hashtable consists of pairs of id:, value.
*/
public Hashtable getDocumentTypesInHash(String langPrefixStr) {
return this.sqlQueryHash("GetDocTypes '" + langPrefixStr + "'") ;
}
public boolean checkUserDocSharePermission(User user, int meta_id) {
return sqlProcedure("CheckUserDocSharePermission "+user.getUserId()+","+meta_id).length>0 ;
}
} // END CLASS IMCService
| server/src/imcode/server/IMCService.java | package imcode.server ;
import org.apache.oro.util.* ;
import org.apache.oro.text.* ;
import org.apache.oro.text.regex.* ;
import org.apache.oro.text.perl.* ;
import java.sql.*;
import java.sql.Date ;
import java.io.*;
import java.util.*;
import imcode.server.* ;
import java.text.Collator ;
import java.text.SimpleDateFormat ;
import java.net.URL ;
import java.net.MalformedURLException ;
import imcode.util.log.* ;
/**
Main services for the Imcode Net Server.
Made final, since only a complete and utter moron would want to extend it.
**/
final public class IMCService implements IMCServiceInterface, IMCConstants {
private class FileCache {
private final int m_FileCacheSize = 50 ;
private CacheLRU fileCache = new CacheLRU(m_FileCacheSize) ;
/**
Fetch a file from the cache, if it hasn't changed on disc.
*/
synchronized private String getCachedFileString(String filename) throws IOException {
return getCachedFileString(new File(filename)) ;
}
/**
Fetch a file from the cache, if it hasn't changed on disc.
*/
synchronized String getCachedFileString(File file) throws IOException {
if (m_FileCacheSize > 0) {
Object[] file_and_date = (Object[])(fileCache.getElement(file)) ; // Get the cached file, if any.
if (file_and_date == null || file.lastModified() > ((Long)file_and_date[1]).longValue() ) {
// No (new) file found?
String temp = loadFile(file).toString() ; // Load it.
fileCache.addElement(file, new Object[] {temp,new Long(System.currentTimeMillis())}) ; // Cache it.
return temp ;
}
return (String)file_and_date[0] ;
} else {
return loadFile(file).toString() ;
}
}
}
private final imcode.server.InetPoolManager m_conPool ; // inet pool of connections
private String m_TemplateHome ; // template home
private String m_IncludePath ;
private int m_DefaultHomePage ; // default home page
private String m_ServletUrl ; // servlet url
private String m_ImageFolder ; // image folder
private String m_Language = "" ; // language
private String m_serverName = "" ; // servername
private SystemData sysData ;
private ExternalDocType m_ExDoc[] ;
private String m_SessionCounterDate = "" ;
private int m_SessionCounter = 0 ;
private int m_NoOfTemplates ;
private FileCache fileCache = new FileCache() ;
private final static Perl5Util perl5util = new Perl5Util() ; // Internally synchronized
private static Pattern OBSOLETE_MENU_PATTERN = null ;
private static Pattern HASHTAG_PATTERN = null ;
private static Pattern HASHTAGNUMBER_PATTERN = null ;
private static Pattern MENU_PATTERN = null ;
private static Pattern MENULOOP_PATTERN = null ;
private static Pattern MENUITEM_PATTERN = null ;
private static Pattern MENUITEMHIDE_PATTERN = null ;
private static Pattern MENUITEMHIDETAG_PATTERN = null ;
private static Pattern IMCMS_TAG_PATTERN = null ;
private static Pattern IMCMS_TAG_ATTRIBUTES_PATTERN = null ;
private static Pattern HTML_PREBODY_PATTERN = null ;
private static Pattern HTML_POSTBODY_PATTERN = null ;
private static Pattern TR_START_PATTERN = null ;
private static Pattern TR_STOP_PATTERN = null ;
private static Pattern TD_START_PATTERN = null ;
private static Pattern TD_STOP_PATTERN = null ;
private static Pattern MENU_NO_PATTERN = null ;
private static Pattern HTML_TAG_PATTERN = null ;
private Log log = Log.getLog("server") ;
static {
Perl5Compiler patComp = new Perl5Compiler() ;
try {
OBSOLETE_MENU_PATTERN = patComp.compile("[\\r\\n]\\s*menu\\s+no=(\\d+)\\s+rows=(\\d+)\\s+table_col=(\\d+)\\s*",Perl5Compiler.READ_ONLY_MASK) ;
// newline menu no=123456 rows=123456 table_col=123456
HASHTAG_PATTERN = patComp.compile("#[^#\"<> \\t\\r\\n]+#",Perl5Compiler.READ_ONLY_MASK) ;
// # none of the above #
HASHTAGNUMBER_PATTERN = patComp.compile("(\\d+)#$", Perl5Compiler.READ_ONLY_MASK) ;
// 123456#
MENU_PATTERN = patComp.compile("<\\?imcms:menu(?:\\s+no=\"(\\d+)\")?\\?>(.*?)<\\?\\/imcms:menu\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENULOOP_PATTERN = patComp.compile("<\\?imcms:menuloop\\?>(.*?)<\\?\\/imcms:menuloop\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEM_PATTERN = patComp.compile("<\\?imcms:menuitem\\?>(.*?)<\\?\\/imcms:menuitem\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEMHIDE_PATTERN = patComp.compile("<\\?imcms:menuitemhide\\?>(.*?)<\\?\\/imcms:menuitemhide\\?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENUITEMHIDETAG_PATTERN = patComp.compile("<\\?\\/?imcms:menuitemhide\\?>", Perl5Compiler.READ_ONLY_MASK) ;
IMCMS_TAG_PATTERN = patComp.compile("<\\?imcms:(\\w+)(.*?)\\?>", Perl5Compiler.READ_ONLY_MASK) ;
IMCMS_TAG_ATTRIBUTES_PATTERN = patComp.compile("\\s*(\\w+)\\s*=\\s*([\"'])(.*?)\\2", Perl5Compiler.READ_ONLY_MASK) ;
HTML_PREBODY_PATTERN = patComp.compile("^.*?<[Bb][Oo][Dd][Yy].*?>", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
HTML_POSTBODY_PATTERN = patComp.compile("<\\/[Bb][Oo][Dd][Yy]>.*$", Perl5Compiler.SINGLELINE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TR_START_PATTERN = patComp.compile("^(\\<tr[^>]*?\\>)",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TR_STOP_PATTERN = patComp.compile("(\\<\\/tr\\>)\\s*$",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TD_START_PATTERN = patComp.compile("^(\\<td[^>]*?\\>)",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
TD_STOP_PATTERN = patComp.compile("(\\<\\/td\\>)\\s*$",Perl5Compiler.CASE_INSENSITIVE_MASK|Perl5Compiler.READ_ONLY_MASK) ;
MENU_NO_PATTERN = patComp.compile("#doc_menu_no#",Perl5Compiler.READ_ONLY_MASK) ;
// OK, so this is simple, ugly, and prone to give a lot of errors.
// Very good. Very good. Know something? NO SOUP FOR YOU!
HTML_TAG_PATTERN = patComp.compile("<[^>]+?>",Perl5Compiler.READ_ONLY_MASK) ;
} catch (MalformedPatternException ignored) {
// I ignore the exception because i know that these patterns work, and that the exception will never be thrown.
Log log = Log.getLog("server") ;
log.log(Log.CRITICAL, "Danger, Will Robinson!") ;
}
}
/**
* <p>Contructs an IMCService object.
*/
// public IMCService(ConnectionPool conPool,javax.swing.JTextArea output,String serverName)
public IMCService(imcode.server.InetPoolManager conPool,Properties props) {
super();
m_conPool = conPool ;
sysData = getSystemDataFromDb() ;
m_TemplateHome = props.getProperty("TemplatePath") ;
log.log(Log.INFO, "TemplatePath: " + m_TemplateHome) ;
m_IncludePath = props.getProperty("IncludePath") ;
log.log(Log.INFO, "IncludePath: " + m_IncludePath) ;
try {
m_DefaultHomePage = Integer.parseInt(props.getProperty("StartDocument")) ; //FIXME: Get from DB
} catch (NumberFormatException ex) {
throw new RuntimeException ("No StartDocument given in properties-file.") ;
}
log.log(Log.INFO, "StartDocument: " + m_DefaultHomePage) ;
m_ServletUrl = props.getProperty("ServletUrl") ; //FIXME: Get from webserver, or get rid of if possible.
log.log(Log.INFO, "ServletUrl: " + m_ServletUrl) ;
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
m_ImageFolder = props.getProperty("ImageUrl") ; //FIXME: Get from webserver, or get rid of if possible.
log.log(Log.INFO, "ImageUrl: " + m_ImageFolder) ;
String externalDocTypes = props.getProperty("ExternalDoctypes") ; //FIXME: Get rid of, if possible.
log.log(Log.INFO, "ExternalDoctypes: " + externalDocTypes) ;
m_Language = props.getProperty("DefaultLanguage") ; //FIXME: Get from DB
log.log(Log.INFO, "DefaultLanguage: " + m_Language) ;
StringTokenizer doc_types = new StringTokenizer(externalDocTypes,";",false) ;
m_ExDoc = new ExternalDocType[doc_types.countTokens()] ;
try {
for (int doc_count=0; doc_types.hasMoreTokens() ; ++doc_count) {
StringTokenizer tempStr = new StringTokenizer(doc_types.nextToken(),":",false) ;
String items[] = new String[tempStr.countTokens()] ;
for ( int i=0 ; tempStr.hasMoreTokens() ; ++i ) {
items[i] = tempStr.nextToken() ;
}
m_ExDoc[doc_count] = new ExternalDocType(Integer.parseInt(items[0]),items[1],items[2],"") ;
}
}
catch(NoSuchElementException e) {
e.printStackTrace() ;
}
try {
m_SessionCounter = Integer.parseInt(this.sqlProcedureStr("GetCurrentSessionCounter")) ;
m_SessionCounterDate = this.sqlProcedureStr("GetCurrentSessionCounterDate") ;
//m_NoOfTemplates = this.sqlProcedureInt("GetNoOfTemplates") ;
} catch ( NumberFormatException ex ) {
log.log(Log.CRITICAL, "Failed to get SessionCounter from db.", ex) ;
throw ex ;
}
//m_Template = new Template[m_NoOfTemplates] ;
log.log(Log.INFO, "SessionCounter: "+m_SessionCounter) ;
log.log(Log.INFO, "SessionCounterDate: "+m_SessionCounterDate) ;
//log.log(Log.INFO, "TemplateCount: "+m_NoOfTemplates) ;
}
/**
* <p>Get me page _id.
*/
public int getDefaultHomePage() {
return m_DefaultHomePage ;
}
/**
* <p>Verify a Internet/Intranet user. User data retrived from SQL Database.
*/
public imcode.server.User verifyUser(LoginUser login_user,String fieldNames[]) {
String sqlStr = "" ;
User user = new User() ;
DBConnect dbc = new DBConnect(m_conPool,login_user.createLoginQuery()) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector user_data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// if resultSet > 0 a user is found
if ( user_data.size() > 0 ) {
user.setFields(fieldNames,user_data) ;
// add roles to user
sqlStr = "select role_id from user_roles_crossref where user_id = " ;
sqlStr += user.getInt("user_id") ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector user_roles = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
user.addObject("user_roles",user_roles) ;
String login_password_from_db = user.getString(login_user.getLoginPasswordFieldName()).trim() ;
String login_password_from_form = login_user.getLoginPassword() ;
if ( login_password_from_db.equals(login_password_from_form) && user.getBoolean("active"))
this.updateLogs(new java.util.Date() + "->User " + login_user.getLoginName()
+ " succesfully logged in.") ;
else if (!user.getBoolean("active") ) {
this.updateLogs(new java.util.Date() + "->User " + (login_user.getLoginName()).trim()
+ " tried to logged in: User deleted!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
} else {
this.updateLogs(new java.util.Date() + "->User " + (login_user.getLoginName()).trim()
+ " tried to logged in: Wrong password!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
}
} else {
this.updateLogs(new java.util.Date() + "->User " + login_user.getLoginName()
+ " tried to logged in: User not found!") ;
dbc.closeConnection() ;
dbc = null ;
return null ;
}
// Get the users language prefix
String lang_prefix = null ;
sqlStr = "select lang_prefix from lang_prefixes where lang_id = "+user.getLangId() ; // Find language
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector lang_prefix_data = (Vector)dbc.executeQuery() ;
if ( lang_prefix_data.size() > 0 ) {
lang_prefix = lang_prefix_data.elementAt(0).toString() ;
user.put("lang_prefix",lang_prefix) ;
}
dbc.closeConnection() ;
dbc = null ;
return user ;
}
public byte[] parsePage (int meta_id, User user, int flags) throws IOException {
return parsePage(meta_id,user,flags,1) ;
}
public byte[] parsePage (int meta_id, User user, int flags, int includelevel) throws IOException {
try {
long totaltime = System.currentTimeMillis() ;
String meta_id_str = String.valueOf(meta_id) ;
int user_id = user.getInt("user_id") ;
String user_id_str = String.valueOf(user_id) ;
//log.log(Log.WILD, "Starting parsing of page for meta_id "+meta_id_str+", user "+user_id_str+", flags "+flags, null) ;
DBConnect dbc = new DBConnect(m_conPool) ;
//log.log(Log.WILD, "Getting connection", null) ;
dbc.getConnection() ;
dbc.createStatement() ;
String lang_prefix = user.getLangPrefix() ; // Find language
String[] sqlAry = {
meta_id_str,
user_id_str
} ;
//log.log(Log.WILD, "Getting permissions", null) ;
dbc.setProcedure("GetUserPermissionSet (?,?)",sqlAry) ;
Vector user_permission_set = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( user_permission_set == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetUserPermissionset returned null") ;
return ("GetUserPermissionset returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Setting permissionstate", null) ;
int user_set_id = Integer.parseInt((String)user_permission_set.elementAt(0)) ;
int user_perm_set = Integer.parseInt((String)user_permission_set.elementAt(1)) ;
int currentdoc_perms = Integer.parseInt((String)user_permission_set.elementAt(2)) ;
boolean textmode = false ;
boolean imagemode = false ;
boolean menumode = false ;
boolean templatemode = false ;
boolean includemode = false ;
if (flags > 0) {
textmode = (flags & PERM_DT_TEXT_EDIT_TEXTS) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_TEXTS) != 0) ;
imagemode = (flags & PERM_DT_TEXT_EDIT_IMAGES) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_IMAGES) != 0) ;
menumode = (flags & PERM_DT_TEXT_EDIT_MENUS) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_MENUS) != 0) ;
templatemode = (flags & PERM_DT_TEXT_CHANGE_TEMPLATE) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_CHANGE_TEMPLATE) != 0) ;
includemode = (flags & PERM_DT_TEXT_EDIT_INCLUDES) != 0 && (user_set_id == 0
|| (user_perm_set & PERM_DT_TEXT_EDIT_INCLUDES) != 0 ) ;
}
dbc.setProcedure("GetIncludes",String.valueOf(meta_id)) ;
Vector included_docs = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.setProcedure("GetTextDocData",String.valueOf(meta_id)) ;
Vector text_docs = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( text_docs == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTextDocData returned null") ;
return "parsePage: GetTextDocData returned null".getBytes("8859_1") ;
}
if ( text_docs.size() == 0 ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTextDocData returned nothing") ;
return "parsePage: GetTextDocData returned nothing".getBytes("8859_1") ;
}
String template_id = (String)text_docs.remove(0) ;
String simple_name = (String)text_docs.remove(0) ;
int sort_order = Integer.parseInt((String)text_docs.remove(0)) ;
String group_id = (String)text_docs.remove(0) ;
log.log(Log.WILD, "Got templateinfo. TemplateId: "+template_id, null) ;
Vector doc_types_vec = null ;
String sqlStr = null ;
if (menumode) {
// I'll retrieve a list of all doc-types the user may create.
sqlStr = "GetDocTypesForUser (?,?,?)" ;
String[] sqlAry2 = {
String.valueOf(meta_id),
String.valueOf(user.getInt("user_id")),
lang_prefix
} ;
dbc.setProcedure(sqlStr,sqlAry2) ;
doc_types_vec = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
}
Vector templategroups = null ;
Vector templates = null ;
Vector groupnamevec = null ;
int selected_group = user.getTemplateGroup() ;
if (templatemode) {
sqlStr = "GetTemplategroupsForUser (?,?)" ;
String[] sqlAry2 = {
String.valueOf(meta_id),
String.valueOf(user.getInt("user_id"))
} ;
dbc.setProcedure(sqlStr,sqlAry2) ;
templategroups = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
// do templatemode queries
if ( selected_group == -1 ) {
selected_group = Integer.parseInt(group_id) ;
}
sqlStr = "GetTemplatesInGroup";
dbc.setProcedure(sqlStr,String.valueOf(selected_group)) ;
templates = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
sqlStr = "select group_name from templategroups where group_id = " + selected_group ;
dbc.setSQLString(sqlStr);
groupnamevec = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
String[] emp = (String[])user.get("emphasize") ;
// Now we'll get the texts from the db.
//log.log(Log.WILD, "Starting texts.", null) ;
dbc.setProcedure("GetTexts",String.valueOf(meta_id)) ;
Vector texts = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
if ( texts == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetTexts returned null") ;
return ("GetTexts returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Getting images.", null) ;
// Get the images from the db
// sqlStr = "select '#img'+convert(varchar(5), name)+'#',name,imgurl,linkurl,width,height,border,v_space,h_space,image_name,align,alt_text,low_scr,target,target_name from images where meta_id = " + meta_id ;
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
sqlStr = "select date_modified, meta_headline, meta_image from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr);
Vector meta = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( meta == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: Query for date_modified returned null") ;
return ("Query for date_modified returned null").getBytes("8859_1") ;
}
//log.log(Log.WILD, "Got docinfo. Getting childs.", null) ;
// Here we have the most timeconsuming part of parsing the page.
// Selecting all the documents with permissions from the DB
sqlStr = "getChilds (?,?)" ;
//String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector childs = (Vector)dbc.executeProcedure() ;
if ( childs == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetChilds returned null") ;
return ("GetChilds returned null").getBytes("8859_1") ;
}
int child_cols = dbc.getColumnCount() ;
int child_rows = childs.size() / child_cols ;
dbc.clearResultSet() ;
dbc.setProcedure("GetImgs",String.valueOf(meta_id)) ;
Vector images = (Vector)dbc.executeProcedure() ;
if ( images == null ) {
dbc.closeConnection() ; // Close connection to db.
log.log(Log.ERROR, "parsePage: GetImgs returned null") ;
return ("GetImgs returned null").getBytes("8859_1") ;
}
dbc.closeConnection() ; // Close connection to db.
String emphasize_string = fileCache.getCachedFileString(m_TemplateHome + lang_prefix +"/admin/emphasize.html") ;
Perl5Compiler patComp = new Perl5Compiler() ;
Perl5Matcher patMat = new Perl5Matcher() ;
Perl5Substitution emphasize_substitution = new Perl5Substitution(emphasize_string) ;
Properties tags = new Properties() ; // A properties object to hold the results from the db...
HashMap textMap = new HashMap() ;
HashMap imageMap = new HashMap() ;
//log.log(Log.WILD, "Processing texts.", null) ;
Iterator it = texts.iterator() ;
while ( it.hasNext() ) {
String key = (String)it.next() ;
String txt_no = (String)it.next() ;
String txt_type = (String)it.next() ;
String value = (String)it.next() ;
if ( textmode ) { // Textmode
if ( value.length()>0 ) {
value = "<img src=\""
+ m_ImageFolder
+ "red.gif\" border=\"0\"> "
+ value
+ "<a href=\""
+ m_ServletUrl
+ "ChangeText?meta_id="
+ meta_id
+ "&txt="
+ txt_no
+ "&type="
+ txt_type
+ "\"><img src=\""
+ m_ImageFolder
+ "txt.gif\" border=\"0\"></a>" ;
tags.setProperty(key,value) ;
textMap.put(txt_no,value);
}
} else { // Not Textmode
if (emp!=null) {
value = emphasizeString(value,emp,emphasize_substitution,patMat) ;
}
if ( value.length()>0 ) {
tags.setProperty(key,value) ;
textMap.put(txt_no,value) ;
}
}
}
//log.log(Log.WILD, "Processing images.", null) ;
int images_cols = dbc.getColumnCount() ;
int images_rows = images.size() / images_cols ;
dbc.clearResultSet() ;
Iterator imit = images.iterator() ;
while ( imit.hasNext() ) {
String imgtag = (String)imit.next() ;
String imgnumber = (String)imit.next() ;
String imgurl = (String)imit.next() ;
String linkurl = (String)imit.next() ;
String width = (String)imit.next() ;
String height = (String)imit.next() ;
String border = (String)imit.next() ;
String vspace = (String)imit.next() ;
String hspace = (String)imit.next() ;
String image_name = (String)imit.next() ;
String align = (String)imit.next() ;
String alt = (String)imit.next() ;
String lowscr = (String)imit.next() ;
String target = (String)imit.next() ;
String target_name = (String)imit.next() ;
StringBuffer value = new StringBuffer (96) ;
if ( !"".equals(imgurl) ) {
if ( !"".equals(linkurl) ) {
value.append("<a href=\""+linkurl+"\"") ;
if ( target.equals("_other") ) {
value.append(" target=\""+target_name+"\">") ;
} else if ( !"".equals(target) ) {
value.append(" target=\""+target+"\">") ;
}
}
value.append("<img src=\""+m_ImageFolder+imgurl+"\"") ; // FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
if ( !"0".equals(width) ) {
value.append(" width=\""+width+"\"") ;
}
if ( !"0".equals(height) ) {
value.append(" height=\""+height+"\"") ;
}
value.append(" border=\""+border+"\"") ;
if ( !"0".equals(vspace) ) {
value.append(" vspace=\""+vspace+"\"") ;
}
if ( !"0".equals(hspace) ) {
value.append(" hspace=\""+hspace+"\"") ;
}
if ( !"".equals(image_name) ) {
value.append(" name=\""+image_name+"\"") ;
}
if ( !"".equals(alt) ) {
value.append(" alt=\""+alt+"\"") ;
}
if ( !"".equals(lowscr) ) {
value.append(" lowscr=\""+lowscr+"\"") ;
}
if ( !"".equals(align) && !"none".equals(align)) {
value.append(" align=\""+align+"\"") ;
}
if ( !"".equals(linkurl) || imagemode ) {
value.append("></a>") ;
} else {
value.append(">") ;
}
if ( imagemode ) { // Imagemode...
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
value.append("<a href=\"ChangeImage?meta_id="+meta_id+"&img="+imgnumber+"\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
}
}
log.log(Log.WILD, "Storing link '"+value.toString()+"' to image number '"+imgnumber+"'") ;
tags.setProperty(imgtag,value.toString()) ;
imageMap.put(imgnumber,value.toString()) ;
}
/*
OK.. we will now make a LinkedList for the entire page.
This LinkedList, menus, will contain one item for each menu on the page.
These items will also be instances of LinkedList.
These LinkedLists will in turn each hold one Properties for each item in each menu.
These Properties will hold the tags, and the corresponding data, that will go in each menuitem.
*/
HashMap menus = new HashMap () ; // Map to contain all the menus on the page.
LinkedList currentMenu = null ;
int old_menu = -1 ;
java.util.Date now = new java.util.Date() ;
Iterator childIt = childs.iterator() ;
while ( childIt.hasNext() ) {
// The menuitemproperties are retrieved in the following order:
// to_meta_id,
// c.menu_sort,
// manual_sort_order,
// doc_type,
// archive,
// target,
// date_created,
// date_modified,
// meta_headline,
// meta_text,
// meta_image,
// frame_name,
// activated_date+activated_time,
// archived_date+archived_time
// 0 if admin
// filename
String child_meta_id = (String)childIt.next() ; // The meta-id of the child
String child_menu_sort = (String)childIt.next() ; // What menu in the page the child is in.
String child_manual_sort_order = (String)childIt.next() ; // What order the document is sorted in in the menu, using sort-order 2 (manual sort)
String child_doc_type = (String)childIt.next() ; // The doctype of the child.
String child_archive = (String)childIt.next() ; // Child is considered archived?
String child_target = (String)childIt.next() ; // The target for this document.
String child_date_created = (String)childIt.next() ; // The datetime the child was created.
String child_date_modified = (String)childIt.next() ; // The datetime the child was modified.
String child_meta_headline = (String)childIt.next() ; // The headline of the child.
String child_meta_text = (String)childIt.next() ; // The subtext for the child.
String child_meta_image = (String)childIt.next() ; // An optional imageurl for this document.
String child_frame_name = (String)childIt.next() ; // The target fram for this document. Supposed to be replaced by 'target'.
String child_activated_date_time = (String)childIt.next() ; // The datetime the document is activated.
String child_archived_date_time = (String)childIt.next() ; // The datetime the document is archived.
String child_admin = (String)childIt.next() ; // "0" if the user may admin it.
String child_filename = (String)childIt.next() ; // The filename, if it is a file-doc.
// System.out.println((String)childs.get(i*child_cols+0)+" "+(String)childs.get(i*child_cols+1)+" "+(String)childs.get(i*child_cols+7)) ;
int menuno = Integer.parseInt(child_menu_sort) ;
if ( menuno != old_menu ) { //If we come upon a new menu...
old_menu = menuno ;
currentMenu = new LinkedList() ; // We make a new Menu,
menus.put(new Integer(menuno), currentMenu) ; // and add it to the page.
}
java.util.Date archived_date = null ;
java.util.Date activate_date = null ;
SimpleDateFormat DATETIMEFORMAT = new SimpleDateFormat("yyyy-MM-ddHH:mm") ;
try {
archived_date = DATETIMEFORMAT.parse(child_archived_date_time) ;
} catch ( java.text.ParseException ex ) {
}
try {
activate_date = DATETIMEFORMAT.parse(child_activated_date_time) ;
} catch ( java.text.ParseException ex ) {
}
boolean inactive = false ;
boolean archived = false ;
if ( activate_date != null && activate_date.compareTo(now) >= 0 ) {// If activated_date is greater than or equal to now
if ( !menumode ) { // and we're not in menumode...
continue ; // ...don't include this menuitem
} else {
inactive = true ;
}
}
if ( (archived_date != null && archived_date.compareTo(now) <= 0) // If archived_date is smaller than or equal to now
|| "1".equals(child_archive) ) { // or archive is set
if ( !menumode ) { // and we're not in menumode...
continue ; // ...don't include this menuitem
} else {
archived = true ;
}
}
Properties props = new Properties () ; // New Properties to hold the tags for this menuitem.
String admin_start = "" ;
String admin_stop = "" ;
if ( menumode ) {
String sortBox = "<input type=\"text\" name=\""+child_meta_id+"\" value=\""+child_manual_sort_order+"\" size=\"4\" maxlength=\"4\">" ;
String archiveDelBox = "<input type=\"checkbox\" name=\"archiveDelBox\" value=\""+child_meta_id+"\">" ;
//props.setProperty("#sortBox#",sortBox) ;
//props.setProperty("#archiveDelBox#",archiveDelBox) ;
if ( "0".equals(child_admin) ) {
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
admin_stop+=" <a href=\"AdminDoc?meta_id="+child_meta_id+"\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
}
if (sort_order == 2) {
admin_start += sortBox ;
}
admin_start += archiveDelBox ;
}
String archive_start = "" ;
String archive_stop = "" ;
if ( inactive ) {
archive_start+="<em><i>" ;
archive_stop+="</i></em>" ;
}
if ( archived ) {
archive_start="<strike>"+archive_start ;
archive_stop+="</strike>" ;
}
props.setProperty("#adminStart#",admin_start) ;
props.setProperty("#adminStop#",admin_stop) ;
//props.setProperty("#to_meta_id#",to_meta_id) ;
//props.setProperty("#manual_sort_order#",child_manual_sort_order) ;
if ( "_other".equals(child_target) ) {
child_target = (String)child_frame_name ;
}
if ( child_target.length() != 0 ) {
child_target = " target=\""+child_target+"\"" ;
}
// If this doc is a file, we'll want to put in the filename
// as an escaped translated path
// For example: /servlet/GetDoc/filename.ext?meta_id=1234
// ^^^^^^^^^^^^^
if ( child_filename != null && "8".equals(child_doc_type) ) {
child_filename = "/"+java.net.URLEncoder.encode(child_filename) ;
} else {
child_filename = "" ;
}
if ( child_meta_headline.length() == 0 ) {
child_meta_headline = " " ;
}
child_meta_headline = archive_start+child_meta_headline+archive_stop ;
if ( !"".equals(child_meta_image) ) {
child_meta_image = "<img src=\""+child_meta_image+"\" border=\"0\">" ;
}
String href = "\"GetDoc"+child_filename+"?meta_id="+child_meta_id+"\""+child_target ;
props.setProperty("#getChildRef#",href) ;
props.setProperty("#childMetaImage#",child_meta_image) ;
props.setProperty("#childMetaHeadline#",child_meta_headline) ;
props.setProperty("#childMetaText#",child_meta_text) ;
props.setProperty("#childCreatedDate#",child_date_created) ;
// Put the data in the proper tags.
props.setProperty("#/menuitemlink#", "</a>"+admin_stop) ;
props.setProperty("#menuitemlink#", admin_start+"<a href="+href+">") ;
props.setProperty("#menuitemheadline#", child_meta_headline) ;
props.setProperty("#menuitemtext#", child_meta_text) ;
props.setProperty("#menuitemdatecreated#", child_date_created) ;
props.setProperty("#menuitemdatemodified#", child_date_modified) ;
props.setProperty("#menuitemimage#", child_meta_image) ;
currentMenu.add(props) ; // Add the Properties for this menuitem to the current menus list.
}
//log.log(Log.WILD, "Getting templateinfo.", null) ;
// I need a list of tags that have numbers that need to be parsed in in their data.
Properties numberedtags = new Properties () ;
// I also need a list of files to load, and their corresponding tag...
Properties toload = new Properties () ;
// Oh! I need a set of tags to be replaced in the templatefiles we'll load...
Properties temptags = new Properties () ;
// Put tags and corresponding data in Properties
tags.setProperty("#userName#", user.getString("first_name").trim()+" "+user.getString("last_name").trim()) ;
tags.setProperty("#session_counter#", String.valueOf(m_SessionCounter)) ;
tags.setProperty("#session_counter_date#", m_SessionCounterDate) ;
tags.setProperty("#lastDate#", meta.get(0).toString()) ;
tags.setProperty("#metaHeadline#", meta.get(1).toString()) ;
String meta_image = meta.get(2).toString() ;
if (!"".equals(meta_image)) {
meta_image = "<img src=\""+meta_image+"\" border=\"0\">" ;
}
tags.setProperty("#metaImage#", meta_image) ;
tags.setProperty("#sys_message#", sysData.getSystemMessage()) ;
tags.setProperty("#servlet_url#", m_ServletUrl) ;
tags.setProperty("#webMaster#", sysData.getWebMaster()) ;
tags.setProperty("#webMasterEmail#", sysData.getWebMasterAddress()) ;
tags.setProperty("#serverMaster#", sysData.getServerMaster()) ;
tags.setProperty("#serverMasterEmail#", sysData.getServerMasterAddress()) ;
tags.setProperty("#addDoc*#","") ;
tags.setProperty("#saveSortStart*#","") ;
tags.setProperty("#saveSortStop*#","") ;
if ( imagemode ) { // imagemode
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
tags.setProperty("#img*#", "<a href=\"ChangeImage?meta_id="+meta_id+"&img=#img_no#\"><img src=\""+m_ImageFolder+"bild.gif\" border=\"0\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
numberedtags.setProperty("#img*#","#img_no#") ;
}
if ( textmode ) { // Textmode
// FIXME: Get imageurl from webserver somehow. The user-object, perhaps?
tags.setProperty("#txt*#", "<img src=\""+m_ImageFolder+"red.gif\" border=\"0\"> <a href=\""+m_ServletUrl+"ChangeText?meta_id="+meta_id+"&txt=#txt_no#&type=1\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>") ;
numberedtags.setProperty("#txt*#","#txt_no#") ;
}
// Give the user a row of buttons if he is privileged enough.
if ( checkDocAdminRights(meta_id,user) && flags >= 0 ) {
tags.setProperty("#adminMode#",getMenuButtons(meta_id,user)) ;
}
if ( templatemode ) { //Templatemode! :)
String group_name ;
if (!groupnamevec.isEmpty()) {
group_name = (String)groupnamevec.elementAt(0) ;
} else {
group_name = "" ;
}
StringBuffer templatelist = new StringBuffer() ;
// Make a HTML option-list of them...
while ( !templates.isEmpty() ) {
String temp_id = (String)templates.remove(0) ;
templatelist.append("<option value=\""+temp_id) ;
if (temp_id.equals(template_id)) {
templatelist.append("\" selected>"+templates.remove(0)+"</option>") ;
} else {
templatelist.append("\">"+templates.remove(0)+"</option>") ;
}
}
// Fetch all templategroups the user may use.
StringBuffer grouplist = new StringBuffer() ;
// Make a HTML option-list of the templategroups
while ( !templategroups.isEmpty() ) {
String temp_id = (String)templategroups.remove(0) ;
grouplist.append("<option value=\""+temp_id) ;
if (selected_group == Integer.parseInt(temp_id)) {
grouplist.append("\" selected>"+templategroups.remove(0)+"</option>") ;
} else {
grouplist.append("\">"+templategroups.remove(0)+"</option>") ;
}
}
temptags.setProperty("#getDocType#","") ;
temptags.setProperty("#DocMenuNo#","") ;
temptags.setProperty("#group#",group_name) ;
temptags.setProperty("#getTemplateGroups#", grouplist.toString()) ;
temptags.setProperty("#simple_name#",simple_name) ;
temptags.setProperty("#getTemplates#",templatelist.toString()) ;
// Put templateadmintemplate in list of files to load.
toload.setProperty("#changePage#",m_TemplateHome + lang_prefix + "/admin/inPage_admin.html") ;
} // if (templatemode)
temptags.setProperty("#servlet_url#",m_ServletUrl) ;
if ( menumode ) {
// I'll put the doc-types in a html-list
Iterator dt_it = doc_types_vec.iterator() ;
StringBuffer doc_types_sb = new StringBuffer(256) ;
while ( dt_it.hasNext() ) {
String dt = (String)dt_it.next() ;
String dtt = (String)dt_it.next() ;
doc_types_sb.append("<option value=\"") ;
doc_types_sb.append(dt) ;
doc_types_sb.append("\">") ;
doc_types_sb.append(dtt) ;
doc_types_sb.append("</option>") ;
}
// Add an option for an existing doc, too
String existing_doc_filename = m_TemplateHome + lang_prefix + "/admin/existing_doc_name.html" ;
String existing_doc_name = null ;
existing_doc_name = fileCache.getCachedFileString(existing_doc_filename) ;
if (doc_types_vec != null && doc_types_vec.size() > 0) {
doc_types_sb.append("<option value=\"0\">"+existing_doc_name+"</option>") ;
}
// List of files to load, and tags to parse them into
toload.setProperty("addDoc",m_TemplateHome + lang_prefix + "/admin/add_doc.html") ;
toload.setProperty("saveSortStart",m_TemplateHome + lang_prefix + "/admin/sort_order.html") ;
toload.setProperty("saveSortStop",m_TemplateHome + lang_prefix + "/admin/archive_del_button.html") ;
toload.setProperty("sort_button",m_TemplateHome + lang_prefix + "/admin/sort_button.html") ;
// Some tags to parse in the files we'll load.
temptags.setProperty("#doc_types#",doc_types_sb.toString()) ; // The doc-types.
temptags.setProperty("#sortOrder"+sort_order+"#","checked") ; // The sortorder for this document.
} // if (menumode)
temptags.setProperty("#getMetaId#",String.valueOf(meta_id)) ;
// Now load the files specified in "toload", and place them in "tags"
//System.out.println("Loading template-files.") ;
//log.log(Log.WILD,"Loading template-files.",null) ;
MapSubstitution temptagsmapsubstitution = new MapSubstitution(temptags, false) ;
try {
char[] charbuffer = new char[4096] ;
StringBuffer templatebuffer = new StringBuffer() ;
Enumeration propenum = toload.propertyNames() ;
while ( propenum.hasMoreElements() ) {
String filetag = (String)propenum.nextElement() ;
String templatebufferfilename = toload.getProperty(filetag) ;
String templatebufferstring = fileCache.getCachedFileString(templatebufferfilename) ;
// Humm... Now we must replace the tags in the loaded files too.
templatebufferstring = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,temptagsmapsubstitution,templatebufferstring,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
tags.setProperty(filetag,templatebufferstring) ;
templatebuffer.setLength(0) ;
}
} catch(IOException e) {
log.log(Log.ERROR, "An error occurred reading file during parsing.", e) ;
return ("Error occurred reading file during parsing.\n"+e).getBytes("8859_1") ;
}
//log.log(Log.WILD, "Loaded and parsed other templatefiles.", null) ;
if ( menumode ) { //Menumode! :)
// Make a Properties of all tags that contain numbers, and what the number is supposed to replace
// in the tag's corresponding data
// I.e. "tags" contains the data to replace the numbered tag, but you probably want that number
// to be inserted somewhere in that data.
// BTW, "*" represents the number in the tag.
//numberedtags.setProperty("#addDoc*#","#doc_menu_no#") ;
//numberedtags.setProperty("#saveSortStart*#","#doc_menu_no#") ;
String savesortstop = tags.getProperty("saveSortStop") ;
// We must display the sortbutton, which we read into the tag "#sort_button#"
savesortstop = tags.getProperty("sort_button")+savesortstop ;
tags.setProperty("saveSortStop",savesortstop) ;
} else { // Not menumode...
tags.setProperty("saveSortStop", "") ;
} // if (menumode)
// Now... let's load the template!
// Get templatedir and read the file.
StringBuffer templatebuffer = new StringBuffer(fileCache.getCachedFileString(m_TemplateHome + "text/" + template_id + ".html")) ;
// Check file for tags
String template = templatebuffer.toString() ;
StringBuffer result = new StringBuffer(template.length()+16384) ; // This value is the amount i expect the document to increase in size.
MenuParserSubstitution menuparsersubstitution = new MenuParserSubstitution(menus,menumode,tags) ;
HashTagSubstitution hashtagsubstitution = new HashTagSubstitution(tags,numberedtags) ;
ImcmsTagSubstitution imcmstagsubstitution = new ImcmsTagSubstitution(user,meta_id,included_docs,includemode,includelevel,textMap,textmode,imageMap,imagemode) ;
LinkedList parse = new LinkedList() ;
perl5util.split(parse,"/<!-(-\\/?)IMSCRIPT-->/i",template) ;
Iterator pit = parse.iterator() ;
boolean parsing = false ;
//log.log(Log.WILD, "Entering parseloop.") ;
// Well. Here we have it. The main parseloop.
// The Inner Sanctum of imCMS. Have fun.
while ( pit.hasNext() ) {
// So, let's jump in and out of blocks delimited by <!--IMSCRIPT--> and <!--/IMSCRIPT-->
String nextbit = (String)pit.next() ;
if (nextbit.equals("-/")) { // We matched <!--/IMSCRIPT-->
parsing = false ; // So, we're not parsing.
continue ;
} else if (nextbit.equals("-")) { // We matched <!--IMSCRIPT-->
parsing = true ; // So let's get to parsing.
continue ;
}
if (!parsing) {
result.append(nextbit) ;
continue ;
}
// String nextbit now contains the bit to parse. (Within the imscript-tags.)
// Parse the new-style menus.
// Aah... the magic of OO...
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,MENU_PATTERN, menuparsersubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// Parse the obsolete menus.
// You know... the ones that suck so bad it isn't even funny anymore...
// Just look what happens when you have something that isn't properly delimited.
// Without this, we could get something similar to efficiency into this so-called parser.
PatternMatcherInput pmin = new PatternMatcherInput(nextbit) ;
StringBuffer sbtemp = new StringBuffer(nextbit) ;
while (patMat.contains(pmin, OBSOLETE_MENU_PATTERN)) {
MatchResult matres = patMat.getMatch() ;
int [] menu_param = { Integer.parseInt(matres.group(1)), Integer.parseInt(matres.group(2)), Integer.parseInt(matres.group(3)) } ;
int endoffset = matres.endOffset(0) ;
obsoleteMenuParser(sbtemp,matres.beginOffset(0), endoffset, menu_param, menus, menumode, sort_order, patMat,tags) ;
String newinput = sbtemp.toString() ;
pmin.setInput(newinput, endoffset, newinput.length()-endoffset ) ;
}
nextbit = sbtemp.toString() ;
// Parse the <?imcms:tags?>
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,IMCMS_TAG_PATTERN,imcmstagsubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// Parse the hashtags
nextbit = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,hashtagsubstitution,nextbit,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
// So, append the result from this loop-iteration to the result.
result.append(nextbit) ;
} // end while (pit.hasNext()) // End of the main parseloop
String returnresult = result.toString() ;
/*
So, it is here i shall have to put my magical markupemphasizing code.
First, i'll split the html (returnresult) on html-tags, and then go through every non-tag part and parse it for keywords to emphasize,
and then i'll puzzle it together again. Whe-hey. This will be fun. Not to mention fast. Oh yes, siree.
*/
if (emp!=null) { // If we have something to emphasize...
StringBuffer emphasized_result = new StringBuffer(returnresult.length()) ; // A StringBuffer to hold the result
PatternMatcherInput emp_input = new PatternMatcherInput(returnresult) ; // A PatternMatcherInput to match on
int last_html_offset = 0 ;
int current_html_offset = 0 ;
String non_html_tag_string = null ;
String html_tag_string = null ;
while (patMat.contains(emp_input,HTML_TAG_PATTERN)) {
current_html_offset = emp_input.getMatchBeginOffset() ;
non_html_tag_string = result.substring(last_html_offset,current_html_offset) ;
last_html_offset = emp_input.getMatchEndOffset() ;
html_tag_string = result.substring(current_html_offset,last_html_offset) ;
non_html_tag_string = emphasizeString(non_html_tag_string,emp,emphasize_substitution,patMat) ;
// for each string to emphasize
emphasized_result.append(non_html_tag_string) ;
emphasized_result.append(html_tag_string) ;
} // while
non_html_tag_string = result.substring(last_html_offset) ;
non_html_tag_string = emphasizeString(non_html_tag_string,emp,emphasize_substitution,patMat) ;
emphasized_result.append(non_html_tag_string) ;
returnresult = emphasized_result.toString() ;
}
return returnresult.getBytes("8859_1") ;
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Error occurred during parsing.",ex ) ;
return ex.toString().getBytes("8859_1") ;
}
}
private String emphasizeString(String str,
String[] emp,
Substitution emphasize_substitution,
PatternMatcher patMat) {
Perl5Compiler empCompiler = new Perl5Compiler() ;
// for each string to emphasize
for (int i = 0 ; i < emp.length ; ++i) {
try {
Pattern empPattern = empCompiler.compile("("+Perl5Compiler.quotemeta(emp[i])+")",Perl5Compiler.CASE_INSENSITIVE_MASK) ;
str = org.apache.oro.text.regex.Util.substitute( // Threadsafe
patMat,
empPattern,
emphasize_substitution,
str,
org.apache.oro.text.regex.Util.SUBSTITUTE_ALL
) ;
} catch (MalformedPatternException ex) {
log.log(Log.WARNING, "Dynamic Pattern-compilation failed in IMCService.emphasizeString(). Suspected bug in jakarta-oro Perl5Compiler.quotemeta(). The String was '"+emp[i]+"'",ex) ;
}
}
return str ;
}
private String hashTagHandler(PatternMatcher patMat, PatternCompiler patComp, Properties tags, Properties numberedtags) {
MatchResult matres = patMat.getMatch() ;
String tag = matres.group(0) ;
String tagdata = tags.getProperty(tag) ; // Get value of tag from hash
if ( tagdata == null ) {
if (patMat.contains(tag,HASHTAGNUMBER_PATTERN) ) {
String numbertag ;
matres = patMat.getMatch() ;
String tagnumber = matres.group(1) ;
String tagexp = tag.substring(0,matres.beginOffset(0))+"*#" ;
tagdata = tags.getProperty(tagexp) ;
if (tagdata == null) {
tagdata = "" ;
} else if ( (numbertag = numberedtags.getProperty(tagexp))!=null ) { // Is it a numbered tag which has data to insert the number in? (Is the four first chars listed in "numberedtags"?) Get the tag to replace with the number.
String qm = Perl5Compiler.quotemeta(numbertag) ; // FIXME: Run quotemeta on them before putting them in numberedtags, instead of doing it every iteration.
try {
tagdata = org.apache.oro.text.regex.Util.substitute(patMat,patComp.compile(qm),new StringSubstitution(tagnumber),tagdata,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
} catch (MalformedPatternException ex) {
log.log(Log.WARNING, "Dynamic Pattern-compilation failed in IMCService.hashTagHandler(). Suspected bug in jakarta-oro Perl5Compiler.quotemeta(). The String was '"+numbertag+"'",ex) ;
}
}
} else {
tagdata = "" ;
}
}
return tagdata ;
}
private String getMenuModePrefix(PatternMatcher patMat, int menu_id, Properties tags) {
String temp = tags.getProperty("addDoc") +
tags.getProperty("saveSortStart") ;
return org.apache.oro.text.regex.Util.substitute(patMat,MENU_NO_PATTERN,new StringSubstitution(""+menu_id),temp,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
}
private String getMenuModeSuffix(Properties tags) {
return tags.getProperty("saveSortStop") ;
}
/**
Invoked when you have found a block of data that is within menu-tags.
*/
protected String menuParser (String input, PatternMatcher patMat, Map menus, int[] implicitMenus, boolean menumode, Properties tags) {
try {
MatchResult menuMatres = patMat.getMatch() ;
StringBuffer result = new StringBuffer() ; // FIXME: Optimize size?
// Get the id of the menu
int menu_id = 0 ;
try {
menu_id = Integer.parseInt(menuMatres.group(1)) ;
} catch (NumberFormatException ex) {
menu_id = implicitMenus[0]++ ;
}
// Get the linked list that is the menu
LinkedList currentMenu = getMenuById(menus,menu_id) ;
// Get the data between the menutags.
String menutemplate = menuMatres.group(2) ;
String menustarttemplate = "" , menustoptemplate = "" ;
String looptemplate ;
// Check if the looptags are present
if (patMat.contains(menutemplate,MENULOOP_PATTERN)) {
MatchResult menuloopMatres = patMat.getMatch() ;
// Get the data between the looptags.
looptemplate = menuloopMatres.group(1) ;
menustarttemplate = menutemplate.substring(0,menuloopMatres.beginOffset(0)) ;
menustoptemplate = menutemplate.substring(menuloopMatres.endOffset(0)) ;
} else {
// No looptags are present. The whole menu will loop.
looptemplate = menutemplate ;
}
// Create a list of menuitemtemplates
LinkedList menuitemtemplatelist = new LinkedList() ;
// Loop over the list and insert the menuitemtemplates
PatternMatcherInput pmin = new PatternMatcherInput(looptemplate) ;
while (patMat.contains(pmin, MENUITEM_PATTERN)) {
MatchResult menuitemMatres = patMat.getMatch() ;
String menuitemtemplate = menuitemMatres.group(1) ;
menuitemtemplatelist.add(menuitemtemplate) ;
}
if (menuitemtemplatelist.isEmpty()) { // Well, were there any menuitemtags present?
menuitemtemplatelist.add(looptemplate) ; // No? Use the looptemplate. (Which will be the entire menu if the looptags are missing.)
}
if (currentMenu != null && currentMenu.size() > 0) {
// Now i begin outputting the results.
result.append(menustarttemplate) ;
// Create an iterator over the menuitemtemplates
Iterator mitit = menuitemtemplatelist.iterator() ;
// Loop over the menus
MapSubstitution mapsubstitution = new MapSubstitution() ;
Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
for (Iterator mit = currentMenu.iterator() ; mit.hasNext() ; ) {
// Make sure we loop over the templates.
if (!mitit.hasNext()) {
mitit = menuitemtemplatelist.iterator() ;
}
String menuitemtemplate = (String)mitit.next() ;
Properties menuitemprops = (Properties)mit.next() ;
// Now i need to replace all tags in this template.
mapsubstitution.setMap(menuitemprops, true) ;
String menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,mapsubstitution,menuitemtemplate,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,MENUITEMHIDETAG_PATTERN, NULL_SUBSTITUTION, menuitemresult,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
result.append(menuitemresult) ;
}
// If we still have menuitemtemplates left, loop over them, and hide everything that is supposed to be hidden.
while (mitit.hasNext()) {
String menuitemresult = org.apache.oro.text.regex.Util.substitute(patMat,MENUITEMHIDE_PATTERN, NULL_SUBSTITUTION, (String)mitit.next(), org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
result.append(menuitemresult) ;
}
result.append(menustoptemplate) ;
}
String resultstring = result.toString() ;
if (menumode) { // If in menumode, make sure to include all the stuff from the proper admintemplates.
resultstring = getMenuModePrefix(patMat,menu_id,tags)+resultstring+getMenuModeSuffix(tags) ;
}
return resultstring ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR, "Error during parsing.", ex) ;
return null ;
}
}
protected class MapSubstitution implements Substitution {
Map map ;
boolean removeNulls ;
public MapSubstitution() {
}
public MapSubstitution(Map map, boolean removeNulls) {
this.map = map ;
this.removeNulls = removeNulls ;
}
public void setMap (Map map, boolean removeNulls) {
this.map = map ;
this.removeNulls = removeNulls ;
}
public Map getMap () {
return map ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
String match = matres.group(0) ;
String replace = (String)map.get(match) ;
if (replace == null ) {
if (removeNulls) {
replace = "" ;
} else {
replace = match ;
}
}
sb.append(replace) ;
}
}
protected class MenuParserSubstitution implements Substitution {
Map menus ;
boolean menumode ;
Properties tags ;
int[] implicitMenus = {1} ;
public MenuParserSubstitution (Map menus,boolean menumode, Properties tags ) {
this.menumode = menumode ;
this.menus = menus ;
this.tags = tags ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
sb.append(menuParser(originalInput,patMat,menus,implicitMenus,menumode,tags)) ;
}
}
protected class ImcmsTagSubstitution implements Substitution {
User user ;
int implicitIncludeNumber = 1 ;
int implicitTextNumber = 1 ;
int implicitImageNumber = 1 ;
int meta_id ;
boolean includeMode ;
int includelevel ;
Map textMap ;
boolean textMode ;
Map imageMap ;
boolean imageMode ;
private final Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
HashMap included_docs = new HashMap() ;
/**
@param user The user
@param meta_id The document-id
@param included_list A list of (include-id, included-meta-id, ...)
@param includemode Whether to include the admin-template instead of the included document.
@param includelevel The number of levels of recursion we've gone through.
**/
ImcmsTagSubstitution (User user, int meta_id, List included_list, boolean includemode, int includelevel, Map textMap, boolean textmode, Map imageMap, boolean imagemode) {
this.user = user ;
this.meta_id = meta_id ;
this.includeMode = includemode ;
this.includelevel = includelevel ;
this.textMap = textMap ;
this.textMode = textmode ;
this.imageMap = imageMap ;
this.imageMode = imagemode ;
for (Iterator i = included_list.iterator(); i.hasNext() ;) {
included_docs.put(i.next(), i.next()) ;
}
}
/**
Handle a <?imcms:include ...?> tag
@param attributes The attributes of the include tag
@param patMat A pattern matcher.
**/
public String tagInclude (Properties attributes, PatternMatcher patMat) {
int no = 0 ;
String attributevalue ;
log.log(Log.DEBUG, "Found include tag with attributes "+attributes) ;
if (null != (attributevalue = attributes.getProperty("no"))) { // If we have the attribute no="number"...
// Set the number of this include-tag
try {
no = Integer.parseInt(attributevalue) ; // Then set the number wanted
}
catch (NumberFormatException ex) {
return "" ;
}
} else if (null != (attributevalue = attributes.getProperty("file"))) { // If we have the attribute file="filename"...
// Fetch a file from the disk
try {
return fileCache.getCachedFileString(new File(m_IncludePath, attributevalue)) ; // Get a file from the include directory
} catch (IOException ignored) {}
return "" ;
} else if (null != (attributevalue = attributes.getProperty("document"))) { // If we have the attribute document="meta-id"
try {
if (includelevel>0) {
int included_meta_id = Integer.parseInt(attributevalue) ;
// Recursively parse the wanted page.
String document = new String(parsePage(included_meta_id,user,-1,includelevel-1),"8859_1") ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_PREBODY_PATTERN,NULL_SUBSTITUTION,document) ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_POSTBODY_PATTERN,NULL_SUBSTITUTION,document) ;
return document ;
}
}
catch (NumberFormatException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (RuntimeException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
}
return "" ;
} else if (null != (attributevalue = attributes.getProperty("url"))) { // If we have an attribute of the form url="url:url"
try {
URL url = new URL(attributevalue) ;
if (url.getProtocol().equalsIgnoreCase("file")) { // Make sure we don't have to defend against file://urls...
return "" ;
}
InputStreamReader urlInput = new InputStreamReader(url.openConnection().getInputStream()) ;
int charsRead = -1 ;
final int URL_BUFFER_LEN = 16384 ;
char[] buffer = new char[URL_BUFFER_LEN] ;
StringBuffer urlResult = new StringBuffer() ;
while (-1 != (charsRead = urlInput.read(buffer,0,URL_BUFFER_LEN))) {
urlResult.append(buffer,0,charsRead) ;
}
return urlResult.toString() ;
} catch (MalformedURLException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
} catch (RuntimeException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
}
} else { // If we have none of the attributes no, file, or document
no = implicitIncludeNumber++ ; // Implicitly use the next number.
}
try {
if (includeMode) {
String included_meta_id_str = (String)included_docs.get(String.valueOf(no)) ;
return imcode.util.Parser.parseDoc(fileCache.getCachedFileString(new File(m_TemplateHome, user.getLangPrefix()+"/admin/change_include.html")),
new String[] {
"#meta_id#", String.valueOf(meta_id),
"#servlet_url#", m_ServletUrl,
"#include_id#", String.valueOf(no),
"#include_meta_id#", included_meta_id_str == null ? "" : included_meta_id_str
}
) ;
} else if (includelevel>0) {
int included_meta_id = Integer.parseInt((String)included_docs.get(String.valueOf(no))) ;
String document = new String(parsePage(included_meta_id,user,-1,includelevel-1),"8859_1") ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_PREBODY_PATTERN,NULL_SUBSTITUTION,document) ;
document = org.apache.oro.text.regex.Util.substitute(patMat,HTML_POSTBODY_PATTERN,NULL_SUBSTITUTION,document) ;
return document ;
}
} catch (IOException ex) {
return "<!-- imcms:include failed: "+ex+" -->" ;
}
return "" ;
}
/**
Handle a <?imcms:text ...?> tag
@param attributes The attributes of the text tag
@param patMat A pattern matcher.
**/
public String tagText (Properties attributes, PatternMatcher patMat) {
// Get the 'no'-attribute of the <?imcms:text no="..."?>-tag
log.log(Log.DEBUG, "Found text tag with attributes "+attributes) ;
String noStr = attributes.getProperty("no") ;
String result = null ;
if (null != noStr) {
result = (String)textMap.get(noStr) ;
} else {
result = (String)textMap.get(noStr = String.valueOf(implicitTextNumber++)) ;
}
if (result == null || "".equals(result)) {
if (textMode) {
result = "<img src=\""+m_ImageFolder+"red.gif\" border=\"0\"> <a href=\""+m_ServletUrl+"ChangeText?meta_id="+meta_id+"&txt="+noStr+"&type=1\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
} else {
result = "" ;
}
log.log(Log.DEBUG, "Empty texttag in textmode '"+textMode+"' replaced by "+result) ;
}
return result ;
}
/**
Handle a <?imcms:image ...?> tag
@param attributes The attributes of the image tag
@param patMat A pattern matcher.
**/
public String tagImage (Properties attributes, PatternMatcher patMat) {
// Get the 'no'-attribute of the <?imcms:text no="..."?>-tag
log.log(Log.DEBUG, "Found image tag with attributes "+attributes) ;
String noStr = attributes.getProperty("no") ;
String result = null ;
if (null != noStr) {
result = (String)imageMap.get(noStr) ;
} else {
result = (String)imageMap.get(noStr = String.valueOf(implicitImageNumber++)) ;
}
if (result == null || "".equals(result)) {
if (imageMode) {
result = "<a href=\"ChangeImage?meta_id="+meta_id+"&img="+noStr+"\"><img src=\""+m_ImageFolder+"bild.gif\" border=\"0\"><img src=\""+m_ImageFolder+"txt.gif\" border=\"0\"></a>" ;
} else {
result = "" ;
}
log.log(Log.DEBUG, "Empty imagetag in imagemode '"+imageMode+"' replaced by "+result) ;
}
return result ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
String tagname = matres.group(1) ;
String tagattributes = matres.group(2) ;
Properties attributes = new Properties() ;
PatternMatcherInput pminput = new PatternMatcherInput(tagattributes) ;
while(patMat.contains(pminput,IMCMS_TAG_ATTRIBUTES_PATTERN)) {
MatchResult attribute_matres = patMat.getMatch() ;
attributes.setProperty(attribute_matres.group(1), attribute_matres.group(3)) ;
}
String result ;
if ("text".equals(tagname)) {
result = tagText(attributes, patMat) ;
} else if ("image".equals(tagname)) {
result = tagImage(attributes, patMat) ;
} else if ("include".equals(tagname)) {
result = tagInclude(attributes, patMat) ;
} else {
result = matres.group(0) ;
}
sb.append(result) ;
}
}
protected class HashTagSubstitution implements Substitution {
Properties tags ;
Properties numberedtags ;
Perl5Compiler patComp = new Perl5Compiler() ;
public HashTagSubstitution (Properties tags, Properties numberedtags) {
this.tags = tags ;
this.numberedtags = numberedtags ;
}
public void appendSubstitution( StringBuffer sb, MatchResult matres, int sc, String originalInput, PatternMatcher patMat, Pattern pat) {
sb.append(hashTagHandler(patMat,patComp,tags,numberedtags)) ;
}
}
private LinkedList getMenuById(Map menus, int id) {
return (LinkedList)menus.get(new Integer(id)) ;
}
/**
I sincerely apologize for this,
but i create this method only to remove the old stupid parser from the main block of the parseloop.
This method and way of parsing a template must die, as soon as possible.
@param sb The stringbuffer to work on
@param sbindex The start of the menu in the stringbuffer.
@param reindex The end of the first row of the stringbuffer. (Or the start of the next line, i don't remember.) At least i think that's correct...
@param menu_param The three ints of the menu. no, rows, and table_col
@param menus The HashMap containing all the menus.
@param menumode A boolean detailing whether or not we are in menu-admin-mode
@param sort_order The magic number that tells us which sort-order we are using.
@param tags Don't ask... this contains the other tags to parse in the page. Used for getMenuModePrefix
*/
private void obsoleteMenuParser (StringBuffer sb, int sbindex, int reindex, int[] menu_param, HashMap menus, boolean menumode, int sort_order, PatternMatcher patMat, Properties tags) {
log.log(Log.WILD, "Starting to parse an obsolete menu on offset "+sbindex) ;
int menurowsindex = sbindex ; // We'll store away the index of the start of the menu.
sbindex = reindex ;
// Now we'll read each row... so we'll need some storagespace...
String[] menu_rows = new String[menu_param[1]] ; //Allocate an array to hold the menurows
StringBuffer tmpsb = new StringBuffer() ;
// for each row in the template...
for ( int foo=0 ; foo<menu_param[1] ; ++foo ) {
char d ;
while ( Character.isWhitespace(sb.charAt(sbindex)) ) {
++sbindex ; //Skip whitespace...
}
while ( (d = sb.charAt(sbindex++)) != '\n' && d != '\r' ) { // Read a line
tmpsb.append(d) ;
}
menu_rows[foo] = tmpsb.toString()+"\r\n" ; // Store the line away... Note that "\r\n" is the standard html (as well as http and dos) end-of-line.
tmpsb.setLength(0) ; // Clear the stringbuffer
}
log.log(Log.WILD, "Read the "+menu_param[1]+" rows of the menu") ;
//sb.replace(menurowsindex,sbindex,"") ; // Remove the lines
//sbindex = menurowsindex ;
// Hohum... Now we should finally have the template rows of the menu in an array...
// Now to another problem... parsing the individual bastards.
// OK... so i have learned that the first two lines are used, seemingly as one string,
// and the second two are not used... Sigh...
// First thing i would do if i could would be to redesign these damned templates!
// And i will one day, so help me Phil, lord of heck!
LinkedList currentMenu = getMenuById(menus,menu_param[0]) ;
if ( currentMenu == null ) {
String menubuff_str = "" ;
if (menumode) {
log.log(Log.WILD, "We don't seem to have a menu... got null.") ;
menubuff_str = "<!-- inserted by imcms --><tr><td>"+getMenuModePrefix(patMat,menu_param[0],tags)+"</td></tr><!-- empty menu --><tr><td>"+getMenuModeSuffix(tags)+"</td></tr><!-- /inserted by imcms -->" ;
}
sb.replace( menurowsindex, sbindex,menubuff_str) ;
return ;
}
// Get an iterator over the elements in the current menu
Iterator menuit = currentMenu.iterator() ;
StringBuffer menubuff = new StringBuffer() ;
String menurowstr = menu_rows[0] ;
// If the "rows"-attribute of this menu is larger than 1, we need the second row too.
// Note that if there is only one row, we add the #adminStop# after parsing for <tr><td>
if ( menu_rows.length>1 ) {
menurowstr += "<!-- menuitem 2nd row -->#adminStop#"+menu_rows[1]+"<!-- /menuitem 2nd row -->" ;
}
// OK, menurowstr now contains a row of the menu, with all the tags and stuff.
// Now we need to check if it starts with <tr> or <td>
// and do something about it.
// These patterns are supposed to match <(/)tr whatever> and <(/)td whatever> at end and beginning of the string.
String trstart = "\r\n<!-- tr --><tr>" ; // Html-tag for start of tablerow (menurow)
String trstop = "</tr><!-- /tr -->\r\n" ; // Html-tag for end of tablerow (menurow)
String tdstart = "\r\n<!-- td --><td valign=\"top\">" ; // Html-tag for start of table-cell (menuelement)
String tdstop = "</td><!-- /td -->\r\n" ; // Html-tag for end of table-cell (menuelement)
Substitution NULL_SUBSTITUTION = new StringSubstitution("") ;
/** Added 010212 **/
if ( patMat.contains(menurowstr,TR_START_PATTERN) ) {
trstart = "\r\n<!-- t tr -->"+patMat.getMatch().group(1) ;
log.log(Log.WILD, "Using the menu's own tr.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TR_START_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TR_STOP_PATTERN) ) {
trstop = patMat.getMatch().group(1) + "<!-- t /tr -->\r\n" ;
log.log(Log.WILD, "Using the menu's own /tr.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TR_STOP_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TD_START_PATTERN) ) {
tdstart = "\r\n<!-- t td -->"+patMat.getMatch().group(1) ;
log.log(Log.WILD, "Using the menu's own td.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TD_START_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
if ( patMat.contains(menurowstr,TD_STOP_PATTERN) ) {
tdstop = patMat.getMatch().group(1)+"<!-- t /td -->\r\n" ;
log.log(Log.WILD, "Using the menu's own /td.") ;
menurowstr = org.apache.oro.text.regex.Util.substitute(patMat,TD_STOP_PATTERN,NULL_SUBSTITUTION,menurowstr) ;
}
/** End of added 010212 **/
//// Make sure we add tags for the html-tags for inactive and archived documents,
//menurowstr = "#adminStart#"+menurowstr ;
// Add #adminStop# to the end, if there is only one line.
// Note that if there is more than one line, we do it before
// all the regexing for <tr><td>
if ( menu_rows.length==1 ) {
menurowstr = "#adminStart#"+menurowstr+"#adminStop#" ;
} else {
menurowstr = "#adminStart#"+menurowstr ;
}
// for each element of the menu...
log.log(Log.WILD, "Starting to parse the "+currentMenu.size()+" items of the menu." ) ;
MapSubstitution mapsubstitution = new MapSubstitution() ;
for ( int rowcount = 0 ; menuit.hasNext() ; ) {
if ( rowcount % menu_param[2]==0 ) { // If this is a new tablerow... (menu_param[2] contains the number of columns per row)
menubuff.append(trstart) ; // append tag for new row: "<TR>", or whatever was already used in the template.
}
menubuff.append(tdstart) ; // Begin new cell: "<TD>", or whatever was already used in the template.
// Here we are going to output one menuitem.
// All data is stored in a Properties, remember?
//StringBuffer menurow = new StringBuffer(menurowstr) ; // Allocate some workroom
Properties props = (Properties)menuit.next() ; // Retrieve the tags and data for this menuitem...
mapsubstitution.setMap(props, true) ;
log.log(Log.WILD, "Parsing the individual tags of one menuitem.") ;
String menurow = org.apache.oro.text.regex.Util.substitute(patMat,HASHTAG_PATTERN,mapsubstitution,menurowstr,org.apache.oro.text.regex.Util.SUBSTITUTE_ALL) ;
menubuff.append(menurow+tdstop) ; // OK... one row done. Append it to the menubuffer and end the cell.
++rowcount ; // And, of course... increase the rowcount.
if ( rowcount%menu_param[2]==0 ) { // If next row is a new tablerow...
menubuff.append(trstop) ; // append </tr>, or the equivalent from the template.
}
}
String menubuff_str = menubuff.toString() ;
if (menumode) {
log.log(Log.WILD, "We're in 'menumode'") ;
menubuff_str = "<tr><td>"+getMenuModePrefix(patMat,menu_param[0],tags)+"</td></tr><!-- menu -->"+menubuff_str+"<!-- /menu --><tr><td>"+getMenuModeSuffix(tags)+"</td></tr>" ;
}
log.log(Log.WILD, "We're finished with this menu."+sbindex) ;
// Yay! One menu done. Insert into the pagebuffer...
sb.replace( menurowsindex, sbindex,menubuff_str) ;
//sb.insert(sbindex,menubuff_str) ;
}
/**
Returns the menubuttonrow
*/
public String getMenuButtons(String meta_id, User user) {
try {
// Get the users language prefix
String lang_prefix = null ;
String sqlStr = "select lang_prefix from lang_prefixes where lang_id = "+user.getInt("lang_id") ; // Find language
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
if ( data.size() > 0 ) {
lang_prefix = data.elementAt(0).toString() ;
}
dbc.clearResultSet() ;
// Find out what permissions the user has
sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector permissions = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (permissions.size() == 0) {
return "" ;
}
StringBuffer tempbuffer = null ;
StringBuffer templatebuffer = null ;
StringBuffer superadmin = null ;
int doc_type = getDocType(Integer.parseInt(meta_id)) ;
try {
String tempbuffer_filename = lang_prefix + "/admin/adminbuttons/adminbuttons"+doc_type+".html" ;
String templatebuffer_filename = lang_prefix + "/admin/adminbuttons/adminbuttons.html" ;
String superadmin_filename = lang_prefix + "/admin/adminbuttons/superadminbutton.html" ;
tempbuffer = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, tempbuffer_filename))) ;
templatebuffer = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, templatebuffer_filename))) ;
superadmin = new StringBuffer(fileCache.getCachedFileString(new File(m_TemplateHome, superadmin_filename))) ;
} catch(IOException e) {
log.log(Log.ERROR, "An error occurred reading adminbuttonfile", e );
return null ;
}
int user_permission_set_id = Integer.parseInt((String)permissions.elementAt(0)) ;
int user_permission_set = Integer.parseInt((String)permissions.elementAt(1)) ;
// Replace #getMetaId# with meta_id
String doctype = dbc.sqlQueryStr("select type from doc_types where doc_type = "+doc_type) ;
imcode.util.AdminButtonParser doc_tags = new imcode.util.AdminButtonParser(m_TemplateHome + lang_prefix + "/admin/adminbuttons/adminbutton"+doc_type+"_", ".html",user_permission_set_id,user_permission_set) ;
doc_tags.put("getMetaId",meta_id) ;
imcode.util.Parser.parseTags(tempbuffer,'#'," <>\n\r\t",(Map)doc_tags,true,1) ;
imcode.util.AdminButtonParser tags = new imcode.util.AdminButtonParser(m_TemplateHome + lang_prefix + "/admin/adminbuttons/adminbutton_", ".html",user_permission_set_id,user_permission_set) ;
tags.put("getMetaId",meta_id) ;
tags.put("doc_buttons",tempbuffer.toString()) ;
tags.put("doc_type",doctype) ;
Vector temp = (Vector)dbc.sqlQuery("select user_id from user_roles_crossref where role_id = 0 and user_id = "+user.getInt("user_id")) ;
if ( temp.size() > 0 ) {
tags.put("superadmin",superadmin.toString()) ;
} else {
tags.put("superadmin","") ;
}
imcode.util.Parser.parseTags(templatebuffer,'#'," <>\n\r\t",(Map)tags,true,1) ;
return templatebuffer.toString() ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"Error occurred while parsing the adminbuttons.",ex) ;
return null ;
}
}
/**
Returns the menubuttonrow
*/
public String getMenuButtons(int meta_id, User user) {
return getMenuButtons(String.valueOf(meta_id),user) ;
}
protected StringBuffer loadFile(File file) {
StringBuffer tempbuffer = new StringBuffer() ;
try {
char[] charbuffer = new char[16384] ;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"8859_1"));
// Load the file
int chars_read = 0 ;
while (-1 < (chars_read = br.read(charbuffer))) {
tempbuffer.append(charbuffer,0,chars_read) ;
}
br.close();
} catch (IOException ex) {
log.log(Log.ERROR, "File not found during parsing.", ex) ;
tempbuffer.append(ex.getMessage()) ;
}
return tempbuffer ;
}
public void saveText(int meta_id,imcode.server.User user,int txt_no,String text,int toHTMLSpecial) {
String sqlStr = "" ;
Table meta ;
String htmlStr = "" ;
// create a db connection an get meta data
sqlStr = "delete from texts where meta_id = " + meta_id
+" and name = "+txt_no ;
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
// update text
sqlStr = "insert into texts (text,type,meta_id,name)" ;
if ( toHTMLSpecial == 0)
text = imcode.server.HTMLConv.toHTMLSpecial(text) ;
// allways convert character >= 160
text = imcode.server.HTMLConv.toHTML(text) ;
sqlStr += " values('" + text + "',"
+ toHTMLSpecial + ","+meta_id+","+txt_no+")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("Text " + txt_no + " in " + "[" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save an imageref.
*/
public void saveImage(int meta_id,User user,int img_no,imcode.server.Image image) {
String sqlStr = "" ;
Table meta ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select * from images where meta_id = "+meta_id+" and name = "+img_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
if (((Vector)dbc.executeQuery()).size() > 0) {
sqlStr = "update images" ;
sqlStr += " set imgurl = '" + image.getImageRef() + "'" ;
sqlStr += ",width = " + image.getImageWidth() ;
sqlStr += ",height = " + image.getImageHeight() ;
sqlStr += ",border = " + image.getImageBorder() ;
sqlStr += ",v_space = " + image.getVerticalSpace() ;
sqlStr += ",h_space = " + image.getHorizontalSpace() ;
sqlStr += ",image_name = '" + image.getImageName() + "'" ;
sqlStr += ",target = '" + image.getTarget() + "'" ;
sqlStr += ",target_name = '" + image.getTargetName() + "'" ;
sqlStr += ",align = '" + image.getImageAlign() + "'" ;
sqlStr += ",alt_text = '" + image.getAltText() + "'" ;
sqlStr += ",low_scr = '" + image.getLowScr() + "'" ;
sqlStr += ",linkurl = '" + image.getImageRefLink() + "'" ;
sqlStr += " where meta_id = " + meta_id ;
sqlStr += " and name = " + img_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
} else {
sqlStr = "insert into images (imgurl, width, height, border, v_space, h_space, image_name, target, target_name, align, alt_text, low_scr, linkurl, meta_id, name)"
+ " values('" + image.getImageRef() + "'" ;
sqlStr += "," + image.getImageWidth() ;
sqlStr += "," + image.getImageHeight() ;
sqlStr += "," + image.getImageBorder() ;
sqlStr += "," + image.getVerticalSpace() ;
sqlStr += "," + image.getHorizontalSpace() ;
sqlStr += ",'" + image.getImageName() + "'" ;
sqlStr += ",'" + image.getTarget() + "'" ;
sqlStr += ",'" + image.getTargetName() + "'" ;
sqlStr += ",'" + image.getImageAlign() + "'" ;
sqlStr += ",'" + image.getAltText() + "'" ;
sqlStr += ",'" + image.getLowScr() + "'" ;
sqlStr += ",'" + image.getImageRefLink() + "'" ;
sqlStr += "," + meta_id ;
sqlStr += "," + img_no+")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.clearResultSet() ;
}
this.updateLogs("ImageRef " + img_no + " =" + image.getImageRef() +
" in " + "[" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
// close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Save template -> text_docs, sort
*/
public void saveTextDoc(int meta_id,imcode.server.User user,imcode.server.Table doc) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update text_docs\n" ;
sqlStr += "set template_id= " + doc.getString("template") ;
sqlStr += ", group_id= " + doc.getString("group_id") ;
sqlStr += " where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("Text docs [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
}
/**
* <p>Delete a doc and all data related.
*/
public void deleteDocAll(int meta_id,imcode.server.User user) {
String sqlStr = "DocumentDelete " + meta_id ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Document " + "[" + meta_id + "] ALL deleted by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Add a existing doc.
*/
public void addExistingDoc(int meta_id,User user,int existing_meta_id,int doc_menu_no) {
String sqlStr = "" ;
int newSortNo ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// test if this is the first child
sqlStr = "select to_meta_id from childs where meta_id =" + meta_id + " and menu_sort = " + doc_menu_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector child_test = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( child_test.size() > 0 ) {
// update child table
sqlStr = "select max(manual_sort_order) from childs\n" ;
sqlStr += "where meta_id = " + meta_id + " and menu_sort = " + doc_menu_no ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector max_sort_no = (Vector)dbc.executeQuery() ;
if ( max_sort_no.size() > 0 )
newSortNo = Integer.parseInt(max_sort_no.elementAt(0).toString()) + 10 ;
else
newSortNo = 500 ;
dbc.clearResultSet() ;
} else
newSortNo = 500 ;
sqlStr = "insert into childs(meta_id,to_meta_id,menu_sort,manual_sort_order)\n" ;
sqlStr += "values(" + meta_id + "," + existing_meta_id + "," + doc_menu_no + "," + newSortNo + ")" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("(AddExisting) Child links for [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Save manual sort.
*/
public void saveManualSort(int meta_id,User user,java.util.Vector childs,
java.util.Vector sort_no) {
String sqlStr = "" ;
// create a db connection
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// m_output.append("Childs" + childs.toString() + "\n");
// m_output.append("sort_no" + sort_no.toString() + "\n");
// update child table
for ( int i = 0 ; i < childs.size() ; i++ ) {
sqlStr = "update childs\n" ;
sqlStr += "set manual_sort_order = " + sort_no.elementAt(i).toString() + "\n" ;
sqlStr += "where meta_id = " + meta_id + " and \n" ;
sqlStr += "to_meta_id=" + childs.elementAt(i).toString() ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
// m_output.append(" Done \n");
this.updateLogs("Child manualsort for [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " +
user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Delete childs from a menu.
*/
public void deleteChilds(int meta_id,int menu,User user,String childsThisMenu[]) {
String sqlStr = "" ;
String childStr = "[" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
for ( int i = 0 ; i < childsThisMenu.length ; i++ ) {
sqlStr = "delete from childs\n" ;
sqlStr += " where to_meta_id =" + childsThisMenu[i] + "\n" ;
sqlStr += " and meta_id = " + meta_id ;
sqlStr += " and menu_sort = "+ menu ;
// sqlStr += "delete from meta where meta_id =" + meta_id + "\n" ;
// sqlStr += "delete from text_docs where meta_id =" + meta_id + "\n" ;
// sqlStr += "delete from texts where meta_id =" + meta_id + "\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
childStr += childsThisMenu[i] ;
if ( i < childsThisMenu.length -1 )
childStr += "," ;
}
childStr += "]" ;
this.updateLogs("Childs " + childStr + " from " +
"[" + meta_id + "] deleted by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
Makes copies of the documents given in the String-array, and inserts them into the given document and menu.
@param meta_id The document to insert into
@param doc_menu_no The menu to insert into
@param user The user
@param childsThisMenu The id's to copy.
**/
public void copyDocs( int meta_id, int doc_menu_no, User user, String[] childsThisMenu) {
if (childsThisMenu != null && childsThisMenu.length > 0) {
StringBuffer childs = new StringBuffer("CopyDocs '"+childsThisMenu[0]) ;
for (int i=1; i<childsThisMenu.length; ++i) {
childs.append(",").append(childsThisMenu[i]) ;
}
childs.append("',"+meta_id+","+doc_menu_no+","+user.getUserId()) ;
sqlUpdateProcedure(childs.toString()) ;
}
}
/**
* Archive childs for a menu.
**/
public void archiveChilds(int meta_id,User user,String childsThisMenu[]) {
String sqlStr = "" ;
String childStr = "[" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
for ( int i = 0 ; i < childsThisMenu.length ; i++ ) {
sqlStr = "update meta" ;
sqlStr += " set archive = 1" ;
sqlStr += " where meta_id =" + childsThisMenu[i] + "\n";
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
childStr += childsThisMenu[i] ;
if ( i < childsThisMenu.length -1 )
childStr += "," ;
}
childStr += "]" ;
this.updateLogs("Childs " + childStr + " from " +
"[" + meta_id + "] archived by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Check if browser doc. *
*/
public int isBrowserDoc(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
int to_meta_id ;
to_meta_id = meta_id ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 6 ) {
sqlStr = "select to_meta_id from browser_docs where meta_id = " + meta_id ;
sqlStr += " and browser = '" + user.getBrowserStr() + "'";
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_to_meta_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
to_meta_id = Integer.parseInt(vec_to_meta_id.elementAt(0).toString()) ;
if (to_meta_id == -1) {
sqlStr = "select to_meta_id from browser_docs where meta_id = " + meta_id ;
sqlStr += " and browser = 'other_" + user.getBrowserInfo()[2] + "'" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
vec_to_meta_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
to_meta_id = Integer.parseInt(vec_to_meta_id.elementAt(0).toString()) ;
}
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return to_meta_id ;
}
/**
* <p>Save an url document.
*/
public void saveUrlDoc(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// update url doc
sqlStr = "update url_docs\n" ;
sqlStr += "set url_ref ='" + doc.getString("url_ref") + "'" ;
sqlStr += ",url_txt ='" + doc.getString("url_txt") + "'" ;
sqlStr += " where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.updateLogs("UrlDoc [" + meta_id + "] modified by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save a new url document.
*/
public void saveNewUrlDoc(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "insert into url_docs(meta_id,frame_name,target,url_ref,url_txt,lang_prefix)\n" ;
sqlStr += "values(" + meta_id + ",'" + doc.getString("frame_name") + "','" ;
sqlStr += doc.getString("destination") + "','" ;
sqlStr += doc.getString("url_ref") + "','" ;
sqlStr += doc.getString("url_txt") ;
sqlStr += "','se')" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.activateChild(meta_id,user) ;
this.updateLogs("UrlDoc [" + meta_id + "] created by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>List all archived docs.
*/
public String listArchive(int meta_id,User user) {
String sqlStr = "" ;
String htmlStr = "" ;
Vector child_meta_headlines = new Vector() ;
Vector childs = new Vector() ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// get child meta_headline
sqlStr = "select meta.meta_headline from meta,childs " ;
sqlStr += "where meta.meta_id = childs.to_meta_id and childs.meta_id = " ;
sqlStr += meta_id ;
sqlStr += " and meta.archive=1" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
child_meta_headlines = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// get childs
sqlStr = "select to_meta_id from meta,childs" ;
sqlStr += " where meta.meta_id = childs.to_meta_id" ;
sqlStr += " and childs.meta_id =" + meta_id ;
sqlStr += " and meta.archive=1" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
childs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
htmlStr += "<HTML><HEAD><TITLE>Janusarkivet</TITLE></HEAD><BODY>\n" ;
htmlStr += "<LINK href=\"../css/CSS-MALL/janus.css\" rel=stylesheet type=text/css>\n" ;
htmlStr += "<SPAN class=rubrik1>\n" ;
htmlStr += "<CENTER><BR>" ;
htmlStr += "<IMG SRC=\"" + m_ImageFolder + "arkivet.gif\" width=\"500\" height=\"27\">\n" ;
htmlStr += "<BR><BR><TABLE border=0 width=* cellpadding=0 cellspacing=8>" ;
htmlStr += "<TR><TD valign=\"top\" width=\"*\">" ;
for ( int i = 0 ; i < childs.size() ; i++ ) {
htmlStr += "<input type=checkbox name=\"archiveBox\" value=" ;
htmlStr += "\"" + childs.elementAt(i).toString() + "\">";
htmlStr += "<IMG SRC=\"" + m_ImageFolder + "pil2.gif\" width=\"7\" height=\"10\">" ;
htmlStr += child_meta_headlines.elementAt(i).toString() + "<BR>\n";
}
htmlStr += "</TD></TR>\n" ;
htmlStr += "</TABLE></CENTER></SPAN>\n" ;
htmlStr += "</BODY></HTML>" ;
return htmlStr ;
}
/**
* <p>Check if url doc.
*/
public imcode.server.Table isUrlDoc(int meta_id,User user) {
String sqlStr = "" ;
int to_meta_id ;
imcode.server.Table url_doc ;
to_meta_id = meta_id ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 5 ) {
sqlStr = "select * from url_docs where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
url_doc = new Table(dbc.executeQuery()) ;
url_doc.addFieldNames(dbc.getMetaData()) ;
dbc.clearResultSet() ;
} else
url_doc = null ;
//close connection
dbc.closeConnection() ;
dbc = null ;
return url_doc ;
}
/**
* <p>Save a new frameset.
*/
public void saveNewFrameset(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "insert into frameset_docs(meta_id,frame_set)\n" ;
sqlStr += "values(" + meta_id + ",'" + doc.getString("frame_set") + "')" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
dbc = null ;
this.activateChild(meta_id,user) ;
this.updateLogs("FramesetDoc [" + meta_id + "] created by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Save a frameset
*/
public void saveFrameset(int meta_id,User user,imcode.server.Table doc) {
String sqlStr = "" ;
// create a db connection an get meta data
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// create new url doc
sqlStr = "update frameset_docs\n";
sqlStr += "set frame_set ='" + doc.getString("frame_set") + "'\n";
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// close connection
dbc.closeConnection() ;
this.updateLogs("FramesetDoc [" + meta_id + "] updated by user: [" +
user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
}
/**
* <p>Update logs.
*/
public void updateLogs(String event) {
String sqlStr = "" ;
java.util.Calendar cal = java.util.Calendar.getInstance() ;
String year = Integer.toString(cal.get(Calendar.YEAR)) ;
int month = Integer.parseInt(Integer.toString(cal.get(Calendar.MONTH))) + 1;
int day = Integer.parseInt(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) ;
int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR))) ;
int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ;
int sec = Integer.parseInt(Integer.toString(cal.get(Calendar.SECOND))) ;
String dateToDay = year + "-" ;
dateToDay += month < 10 ? "0" + Integer.toString(month) : Integer.toString(month) ;
dateToDay += "-" ;
dateToDay += day < 10 ? "0" + Integer.toString(day) : Integer.toString(day) + " " ;
dateToDay += " " ;
dateToDay += hour < 10 ? "0" + Integer.toString(hour) : Integer.toString(hour) ;
dateToDay += ":" ;
dateToDay += min < 10 ? "0" + Integer.toString(min) : Integer.toString(min) ;
dateToDay += ":" ;
dateToDay += sec < 10 ? "0" + Integer.toString(min) : Integer.toString(sec) ;
dateToDay += ".000" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "insert into main_log(log_datetime,event)\n" ;
sqlStr += "values('" + dateToDay + "','" + event + "')\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Update track log.
*/
public void updateTrackLog(int from_meta_id,int to_meta_id,imcode.server.User user) {
String sqlStr = "" ;
int cookie_id = user.getInt("user_id") ;
java.util.Calendar cal = java.util.Calendar.getInstance() ;
String year = Integer.toString(cal.get(Calendar.YEAR)) ;
int month = Integer.parseInt(Integer.toString(cal.get(Calendar.MONTH))) + 1;
int day = Integer.parseInt(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) ;
int hour = Integer.parseInt(Integer.toString(cal.get(Calendar.HOUR))) ;
int min = Integer.parseInt(Integer.toString(cal.get(Calendar.MINUTE))) ;
int sec = Integer.parseInt(Integer.toString(cal.get(Calendar.SECOND))) ;
String dateToDay = year + "-" ;
dateToDay += month < 10 ? "0" + Integer.toString(month) : Integer.toString(month) ;
dateToDay += "-" ;
dateToDay += day < 10 ? "0" + Integer.toString(day) : Integer.toString(day) + " " ;
dateToDay += " " ;
dateToDay += hour < 10 ? "0" + Integer.toString(hour) : Integer.toString(hour) ;
dateToDay += ":" ;
dateToDay += min < 10 ? "0" + Integer.toString(min) : Integer.toString(min) ;
dateToDay += ":" ;
dateToDay += sec < 10 ? "0" + Integer.toString(min) : Integer.toString(sec) ;
dateToDay += ".000" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "insert into track_log(user_id,log_datetime,from_meta_id,to_meta_id,cookie_id)\n" ;
sqlStr += "values(" + user.getInt("user_id") + ",'"
+ dateToDay + "'," + from_meta_id + "," + to_meta_id + "," + cookie_id +")\n" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Check if frameset doc. *
*/
public String isFramesetDoc(int meta_id,User user) {
String sqlStr = "" ;
Vector frame_set = new Vector() ;
String html_str = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if ( Integer.parseInt(vec_doc_type.elementAt(0).toString()) == 7 ) {
sqlStr = "select frame_set from frameset_docs where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
frame_set = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
html_str = frame_set.elementAt(0).toString() ;
} else
html_str = null ;
//close connection
dbc.closeConnection() ;
dbc = null ;
return html_str ;
}
/**
* <p>Search docs.
*/
public Vector searchDocs(int meta_id,User user,String question_str,
String search_type,String string_match,String search_area) {
// search_area : all,not_archived,archived
String sqlStr = "" ;
Vector tokens = new Vector() ;
Vector meta_docs = new Vector() ;
String match = "%" ;
if ( string_match.equals("match") )
match = "" ;
StringTokenizer parser = new StringTokenizer(question_str.trim()," ") ;
while ( parser.hasMoreTokens() )
tokens.addElement(parser.nextToken()) ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
if ( !search_type.equals("atc_icd10") ) {
// text fields // texts.meta_id
if (tokens.size() > 0)
sqlStr += "select distinct meta.meta_id,meta.meta_headline,meta.meta_text from texts,meta where (" ;
for ( int i = 0 ; i < tokens.size() ; i++ ) {
sqlStr += " text like '%" + tokens.elementAt(i).toString() + match + "'" ;
if ( i < tokens.size() -1 )
sqlStr += " " + search_type + " " ;
}
sqlStr += ") " ;
if (tokens.size() > 0) {
sqlStr += " and meta.meta_id = texts.meta_id" ;
sqlStr += " and meta.activate = 1 and meta.disable_search = 0\n" ;
}
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
if ( tokens.size() > 0 ) {
sqlStr += "\n union \n" ;
}
// meta_headline
if (tokens.size() > 0)
sqlStr += "select distinct meta_id,meta_headline,meta_text from meta where " ;
for ( int i = 0 ; i < tokens.size() ; i++ ) {
sqlStr += " (meta_headline like '%" + tokens.elementAt(i).toString() + match + "' " ;
sqlStr += " or meta_text like '%" + tokens.elementAt(i).toString() + match + "' " ;
sqlStr += " or classification like '%" + tokens.elementAt(i).toString() + match + "') " ;
if ( i < tokens.size() -1 )
sqlStr += " " + search_type + " " ;
}
sqlStr += " and activate = 1 and disable_search = 0\n" ;
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
if ( tokens.size() > 0 ) {
sqlStr += " order by meta.meta_id" ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
meta_docs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
} else {
sqlStr = "select distinct meta_id,meta_headline,meta_text from meta where " ;
sqlStr += "classification = '" + question_str + "'";
sqlStr += " and activate = 1 and disable_search = 0\n" ;
if (search_area.equals("not_archived")) {
sqlStr += " and meta.archive = 0" ;
}
if (search_area.equals("archived")) {
sqlStr += " and meta.archive = 1" ;
}
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
meta_docs = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return meta_docs ;
}
/**
* <p>Check if external doc.
*/
public ExternalDocType isExternalDoc(int meta_id,User user) {
String sqlStr = "" ;
ExternalDocType external_doc = null ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "select doc_type from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
Vector vec_doc_type = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
int doc_type = Integer.parseInt(vec_doc_type.elementAt(0).toString()) ;
if ( doc_type > 100 ) {
for ( int i = 0 ; i < m_ExDoc.length && m_ExDoc[i] != null ; i++ )
if ( m_ExDoc[i].getDocType() == doc_type ) {
// external_doc = new ExternalDocType(m_ExDoc[i].getDocType(),m_ExDoc[i].getCallServlet(),
// m_ExDoc[i].getDocName(),m_ExDoc[i].getParamStr()) ;
external_doc = m_ExDoc[i] ;
}
}
//close connection
dbc.closeConnection() ;
dbc = null ;
return external_doc ;
}
/**
* <p>Remove child from child-table.
*/
public void removeChild(int meta_id,int parent_meta_id,User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "delete from childs where meta_id = " + parent_meta_id ;
sqlStr += "and to_meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] removed from " + parent_meta_id +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Activate child to child-table.
*/
public void activateChild(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update meta\n" ;
sqlStr += "set activate=1\n" ;
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] activated " +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
Deactivate (sigh) child from child-table.
**/
public void inActiveChild(int meta_id,imcode.server.User user) {
String sqlStr = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
sqlStr = "update meta\n" ;
sqlStr += "set activate=0\n" ;
sqlStr += "where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
this.updateLogs("Child [" + meta_id + "] made inactive " +
"by user: [" + user.getString("first_name").trim() + " " + user.getString("last_name").trim() + "]") ;
//close connection
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Send a sqlquery to the database and return a string array.
*/
public String[] sqlQuery(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a sqlquery to the database and return a string array.
*/
public String[] sqlQuery(String sqlQuery,String catalog) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery(catalog) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a sqlquery to the database and return a string
*/
public String sqlQueryStr(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data.size() > 0 )
return data.elementAt(0).toString() ;
else
return null ;
}
/**
* <p>Send a sql update query to the database
*/
public void sqlUpdateQuery(String sqlStr) {
DBConnect dbc = new DBConnect(m_conPool,sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
dbc.executeUpdateQuery();
dbc.closeConnection() ;
dbc = null ;
}
/**
* <p>Send a procedure to the database and return a string array
*/
public String[] sqlProcedure(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
// dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
String result[] = new String[data.size()] ;
for ( int i = 0 ; i < data.size() ; i++ )
result[i] = data.elementAt(i).toString() ;
data = null ;
return result ;
} else
return null ;
}
/**
* <p>Send a procedure to the database and return a string.
*/
public String sqlProcedureStr(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
//dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if (data != null) {
if ( data.size() > 0)
return data.elementAt(0).toString() ;
else
return null ;
} else
return null ;
}
/**
* <p>Send a procedure to the database and return a int.
*/
public int sqlProcedureInt(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
//dbc.createStatement() ;
data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null )
return Integer.parseInt(data.elementAt(0).toString()) ;
else
return -1 ;
}
/**
* <p>Send a update procedure to the database
*/
public void sqlUpdateProcedure(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
dbc.executeUpdateProcedure();
dbc.closeConnection() ;
dbc = null ;
}
/**
Parse doc replace variables with data
*/
public String parseDoc(String htmlStr,java.util.Vector variables) {
try {
String[] foo = new String[variables.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo)) ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"parseDoc(String,Vector): RuntimeException", ex );
throw ex ;
}
}
/**
Parse doc replace variables with data, uses two vectors
*/
public String parseDoc(String htmlStr,java.util.Vector variables,java.util.Vector data) {
try {
String[] foo = new String[variables.size()] ;
String[] bar = new String[data.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo),(String[])data.toArray(bar)) ;
} catch ( RuntimeException ex ) {
log.log(Log.ERROR,"parseDoc(String,Vector,Vector): RuntimeException", ex );
throw ex ;
}
}
/**
Parse doc replace variables with data , use template
*/
public String parseDoc(java.util.Vector variables, String admin_template_name, String lang_prefix) {
try {
String htmlStr = fileCache.getCachedFileString(new File(m_TemplateHome,lang_prefix+"/admin/"+admin_template_name)) ;
if (variables == null) {
return htmlStr ;
}
String[] foo = new String[variables.size()] ;
return imcode.util.Parser.parseDoc(htmlStr,(String[])variables.toArray(foo)) ;
} catch ( RuntimeException e ) {
log.log(Log.ERROR,"parseDoc(Vector, String, String): RuntimeException", e );
throw e ;
} catch ( IOException e ) {
log.log(Log.ERROR,"parseDoc(Vector, String, String): IOException", e );
return "" ;
}
}
/**
* <p>Return the external doctypes templates folder.
*/
public String getExternalTemplateFolder(int meta_id) {
Vector data = new Vector() ;
String folder = "" ;
DBConnect dbc = new DBConnect(m_conPool) ;
String sqlStr = "select doc_type,lang_prefix from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( Integer.parseInt(data.elementAt(0).toString()) > 100 )
folder = m_TemplateHome + data.elementAt(1).toString() +
"/" + data.elementAt(0).toString() + "/" ;
else
folder = m_TemplateHome + data.elementAt(1).toString() + "/" ;
return folder ;
}
/**
* <p>Return templatehome.
*/
public String getTemplateHome() {
return m_TemplateHome ;
}
/**
* <p>Return imagehome.
*/
public String getImageHome() {
return m_ImageFolder ;
}
/**
* <p>Return language.
*/
public String getLanguage() {
return m_Language ;
}
/**
* <p>Get internal template folder.
*/
public String getInternalTemplateFolder(int meta_id) {
Vector data = new Vector() ;
String folder = "" ;
if ( meta_id != -1 ) {
DBConnect dbc = new DBConnect(m_conPool) ;
String sqlStr = "select doc_type,lang_prefix from meta where meta_id = " + meta_id ;
dbc.setSQLString(sqlStr) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
folder = m_TemplateHome + data.elementAt(1).toString() + "/" ;
} else
folder = m_TemplateHome ;
return folder ;
}
/**
* <p>Increment session counter.
*/
public int incCounter() {
m_SessionCounter += 1 ;
return m_SessionCounter ;
}
/**
* <p>Get session counter.
*/
public int getCounter() {
return m_SessionCounter ;
}
/**
* <p>Set session counter.
*/
public int setCounter(int value) {
m_SessionCounter = value ;
return m_SessionCounter ;
}
/**
* <p>Set session counter date.
*/
public boolean setCounterDate(String date) {
m_SessionCounterDate = date ;
this.sqlUpdateProcedure("SetSessionCounterDate '" + date + "'") ;
return true ;
}
/**
* <p>Get session counter date.
*/
public String getCounterDate() {
return m_SessionCounterDate ;
}
/**
Remove elements from a vector.
*/
private Vector removeElement(Vector vec,int elements) {
Vector tempVec = new Vector() ;
for ( int i = 0 ; i < vec.size() ; i+=(elements+1) )
tempVec.addElement(vec.elementAt(i+elements)) ;
return tempVec ;
}
/**
Send a sqlQuery to the database and return a string array
Array[0] = number of field in the record
Array[1] - array[n] = metadata
Array[n+1] - array[size] = data
*/
public String[] sqlQueryExt(String sqlQuery) {
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
String[] meta = (String[])dbc.getMetaData() ;
if ( data.size() > 0 ) {
String result[] = new String[data.size() + dbc.getColumnCount() + 1] ;
// no of fields
result[0] = dbc.getColumnCount() + "" ;
// meta
int i = 0 ;
for ( i = 0 ; i < dbc.getColumnCount() ; i++ )
result[i+1] = meta[i] ;
// data
for ( int j = 0 ; j < data.size() ; j++ )
result[j+i+1] = data.elementAt(j).toString() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return result ;
} else {
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return null ;
}
}
/**
Send a procedure to the database and return a string array
Array[0] = number of field in the record
Array[1] - array[n] = metadata
Array[n+1] - array[size] = data
*/
public String[] sqlProcedureExt(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
if ( data != null && data.size() > 0 ) {
String result[] = new String[data.size() + dbc.getColumnCount() + 1] ;
// no of fields
result[0] = dbc.getColumnCount() + "" ;
// meta
int i = 0 ;
for ( i = 0 ; i < dbc.getColumnCount() ; i++ )
result[i+1] = meta[i] ;
// data
for ( int j = 0 ; j < data.size() ; j++ )
result[j+i+1] = data.elementAt(j).toString() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return result ;
} else {
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
data = null ;
meta = null ;
return null ;
}
}
/**
Send a sqlQuery to the database and return a Hastable
*/
public Hashtable sqlQueryHash(String sqlQuery) {
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
Vector data = (Vector)dbc.executeQuery() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
Hashtable result = new Hashtable(columns,0.5f) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
Send a procedure to the database and return a Hashtable
*/
public Hashtable sqlProcedureHash(String procedure) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
Hashtable result = new Hashtable(columns,0.5f) ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
Send a procedure to the database and return a multi string array
*/
public String[][] sqlProcedureMulti(String procedure) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure(procedure) ;
data = (Vector)dbc.executeProcedure() ;
int columns = dbc.getColumnCount() ;
if (columns == 0)
return new String[0][0] ;
int rows = data.size() / columns ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
String result[][] = new String[rows][columns] ;
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < columns ; j++) {
result[i][j] = data.elementAt(i * columns + j).toString() ;
}
}
return result ;
}
/**
Send a sqlquery to the database and return a multi string array
*/
public String[][] sqlQueryMulti(String sqlQuery) {
Vector data = new Vector() ;
DBConnect dbc = new DBConnect(m_conPool,sqlQuery) ;
dbc.getConnection() ;
dbc.createStatement() ;
data = (Vector)dbc.executeQuery() ;
int columns = dbc.getColumnCount() ;
if (columns == 0)
return new String[0][0] ;
int rows = data.size() / columns ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
String result[][] = new String[rows][columns] ;
for(int i = 0 ; i < rows ; i++) {
for(int j = 0 ; j < columns ; j++) {
result[i][j] = data.elementAt(i * columns + j).toString() ;
}
}
return result ;
}
/*
/**
restart server
*/
/*
public void restartServer() {
ImcServer.imc_server.restartServer();
}
*/
/**
get doctype
*/
public int getDocType(int meta_id) {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure("GetDocType " + meta_id) ;
Vector data = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
if ( data != null ) {
if ( data.size() > 0)
return Integer.parseInt(data.elementAt(0).toString()) ;
else
return 0 ;
}
return -1 ;
}
/**
checkDocAdminRights
*/
public boolean checkDocAdminRights(int meta_id, User user) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() > 0 && Integer.parseInt((String)perms.elementAt(0)) < 3 ) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRights(int,User)",ex) ;
throw ex ;
}
}
/**
checkDocRights
*/
public boolean checkDocRights(int meta_id, User user) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() > 0 && Integer.parseInt((String)perms.elementAt(0)) < 4 ) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocRights(int,User)",ex) ;
throw ex ;
}
}
/**
Checks to see if a user has any permission of a particular set of permissions for a document.
@param meta_id The document-id
@param user The user
@param A bitmap containing the permissions.
*/
public boolean checkDocAdminRightsAny (int meta_id, User user, int permission) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
int set_id = Integer.parseInt((String)perms.elementAt(0)) ;
int set = Integer.parseInt((String)perms.elementAt(1)) ;
if (perms.size() > 0
&& set_id == 0 // User has full permission for this document
|| (set_id < 3 && ((set & permission) > 0)) // User has at least one of the permissions given.
) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRightsAny(int,User,int)",ex) ;
throw ex ;
}
}
/**
Checks to see if a user has a particular set of permissions for a document.
@param meta_id The document-id
@param user The user
@param permissions A bitmap containing the permissions.
*/
public boolean checkDocAdminRights (int meta_id, User user, int permission) {
try {
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
String sqlStr = "GetUserPermissionSet (?,?)" ;
String[] sqlAry = {String.valueOf(meta_id),String.valueOf(user.getInt("user_id"))} ;
dbc.setProcedure(sqlStr,sqlAry) ;
Vector perms = (Vector)dbc.executeProcedure() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
if (perms.size() == 0) {
return false ;
}
int set_id = Integer.parseInt((String)perms.elementAt(0)) ;
int set = Integer.parseInt((String)perms.elementAt(1)) ;
if (set_id == 0 // User has full permission for this document
|| (set_id < 3 && ((set & permission) == permission)) // User has all the permissions given.
) {
return true ;
} else {
return false ;
}
} catch (RuntimeException ex) {
log.log(Log.ERROR, "Exception in checkDocAdminRights(int,User,int)",ex) ;
throw ex ;
}
}
/**
save template to disk
*/
public int saveTemplate(String name, String file_name, byte[] template, boolean overwrite,String lang_prefix) {
BufferedOutputStream out ;
String sqlStr = "" ;
String file ;
String new_template_id = "";
try {
file = new String(template,"8859_1") ;
} catch(UnsupportedEncodingException e) {
return -2 ;
}
int no_of_txt = 0 ;
int no_of_img = 0 ;
int no_of_url = 0 ;
for ( int index=0 ; (index = file.indexOf("#txt",index))!=-1 ; no_of_txt++ )
index += 4 ;
for ( int index=0 ; (index = file.indexOf("#img",index))!=-1 ; no_of_img++ )
index += 4 ;
for ( int index=0 ; (index = file.indexOf("#url",index))!=-1 ; no_of_url++ )
index += 4 ;
// create connectionobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// check if template exists
sqlStr = "select template_id from templates\n" ;
sqlStr += "where simple_name = '" + name + "'" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
Vector template_id = (Vector)dbc.executeQuery() ;
dbc.clearResultSet() ;
if (template_id.size() == 0) {
// get new template_id
sqlStr = "select max(template_id) + 1 from templates\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
new_template_id = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
sqlStr = "insert into templates\n" ;
sqlStr += "values (" + new_template_id + ",'"+file_name+"','"+name +
"','"+ lang_prefix + "'," + no_of_txt+","+no_of_img+","+no_of_url+")" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
} else { //update
if (!overwrite) {
dbc.closeConnection() ;
dbc = null ;
return -1;
}
new_template_id = template_id.elementAt(0).toString() ;
sqlStr = "update templates\n"
+ "set template_name = '" + file_name + "',"
+ "no_of_txt =" + no_of_txt + ","
+ "no_of_img =" + no_of_img + ","
+ "no_of_url =" + no_of_url
+ "where template_id = " + new_template_id ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
dbc.closeConnection() ;
dbc = null ;
File f = new File(m_TemplateHome, "text/" + new_template_id + ".html") ;
// if (!f.exists())
// overwrite = true ;
// save template data
// if (overwrite) {
try {
FileOutputStream fw = new FileOutputStream(f) ;
fw.write(template) ;
fw.flush() ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
// } else {
// return -1;
//
// }
// save template demo
/* if ( demo_template != null) {
if (demo_template.length > 0) {
try {
FileOutputStream fw = new FileOutputStream(m_TemplateHome + lang_prefix + "/text/demo/" + file_name) ;
fw.write(demo_template) ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
}
}*/
// 0 = OK
// -1 = file exist
// -2 = write error
return 0 ;
}
/**
get demo template
*/
public Object[] getDemoTemplate(int template_id) throws IOException {
//String str = "" ;
StringBuffer str = new StringBuffer() ;
BufferedReader fr = null;
String suffix = null;
String[] suffixList =
{"jpg","jpeg","gif","png","html","htm"};
for(int i=0;i<=5;i++)
{ // Looking for a template with one of six suffixes
String path = m_TemplateHome + "/text/demo/" + template_id + "." + suffixList[i];
File fileObj = new File(path);
long date = 0;
long fileDate = fileObj.lastModified();
if (fileObj.exists() && fileDate>date)
{
// if a template was not properly removed, the template
// with the most recens modified-date is returned
date = fileDate;
try {
fr = new BufferedReader(new InputStreamReader(new FileInputStream(fileObj),"8859_1")) ;
suffix = suffixList[i];
} catch(IOException e) {
return null ; //Could not read
}
} // end IF
} // end FOR
char[] buffer = new char[4096] ;
try {
int read ;
while ( (read = fr.read(buffer,0,4096)) != -1 ) {
str.append(buffer,0,read) ;
}
} catch(IOException e) {
return null ;
}
catch(NullPointerException e) {
return null ;
}
return new Object[] {suffix , str.toString().getBytes("8859_1")} ; //return the buffer
}
/**
get template
*/
public byte[] getTemplate(int template_id) throws IOException {
String str = "" ;
BufferedReader fr ;
try {
fr = new BufferedReader( new FileReader(m_TemplateHome + "/text/" + template_id + ".html")) ;
} catch(FileNotFoundException e) {
log.log(Log.INFO, "Failed to find template number "+template_id) ;
return null ;
}
try {
int temp ;
while ((temp = fr.read())!=-1) {
str+=(char)temp;
}
} catch(IOException e) {
log.log(Log.INFO, "Failed to read template number "+template_id) ;
return null ;
}
return str.getBytes("8859_1") ;
}
/**
delete template from db/disk
*/
public void deleteTemplate(int template_id) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// delete from database
sqlStr = "delete from templates_cref\n" ;
sqlStr += "where template_id = " + template_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
// delete from database
sqlStr = "delete from templates\n" ;
sqlStr += "where template_id = " + template_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
// test if template exists and delete it
File f = new File(m_TemplateHome + "/text/" + template_id + ".html") ;
if (f.exists()) {
f.delete() ;
}
}
/**
save demo template
*/
public int saveDemoTemplate(int template_id,byte [] data, String suffix) {
// save template demo
// See if there are templete_id:s with other file-formats and delete them
// WARNING: Uggly Code
String[] suffixes = {"jpg","jpeg","gif","png","htm","html"};
for(int i=0;i<=5;i++) {
File file = new File(m_TemplateHome + "/text/demo/" + template_id + "." + suffixes[i]);
if(file.exists())
file.delete();
// doesn't always delete the file, made sure the right template is
// shown using the file-date & time in getDemoTemplate
}
try {
FileOutputStream fw = new FileOutputStream(m_TemplateHome + "/text/demo/" + template_id + "." + suffix) ;
fw.write(data) ;
fw.close() ;
} catch(IOException e) {
return -2 ;
}
return 0 ;
}
/**
save templategroup
*/
public void saveTemplateGroup(String group_name,User user) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// get lang prefix
sqlStr = "select lang_prefix from users,lang_prefixes\n" ;
sqlStr += "where users.lang_id = lang_prefixes.lang_id\n" ;
sqlStr += "and user_id =" + user.getInt("user_id") ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
String lang_prefix = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
// get new group_id
sqlStr = "select max(group_id) + 1 from templategroups\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
String new_group_id = ((Vector)dbc.executeQuery()).elementAt(0).toString() ;
dbc.clearResultSet() ;
// change name
sqlStr = "insert into templategroups\n" ;
sqlStr += "values(" + new_group_id + ",'" + lang_prefix + "','" + group_name + "')" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
delete templategroup
*/
public void deleteTemplateGroup(int group_id) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// change name
sqlStr = "delete from templategroups\n" ;
sqlStr += "where group_id = " + group_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
change templategroupname
*/
public void changeTemplateGroupName(int group_id,String new_name) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// change name
sqlStr = "update templategroups\n" ;
sqlStr += "set group_name = '" + new_name + "'" ;
sqlStr += "where group_id = " + group_id + "\n" ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
dbc.closeConnection() ;
dbc = null ;
}
/**
unassign template from templategroups
*/
public void unAssignTemplate(int template_id,int group_id[]) {
String sqlStr = "" ;
// create connectiobject
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
// delete current refs
for( int i = 0 ; i < group_id.length ; i++) {
sqlStr = "delete from templates_cref\n" ;
sqlStr += "where template_id = " + template_id ;
sqlStr += "and group_id = " + group_id[i] ;
dbc.setSQLString(sqlStr);
dbc.createStatement() ;
dbc.executeUpdateQuery() ;
}
dbc.closeConnection() ;
dbc = null ;
}
/** get server date
*/
public java.util.Date getCurrentDate() {
return new java.util.Date() ;
}
final static FileFilter DEMOTEMPLATEFILTER = new FileFilter () {
public boolean accept (File file) {
return file.length() > 0 ;
}
} ;
// get demotemplates
public String[] getDemoTemplateList() {
File demoDir = new File(m_TemplateHome + "/text/demo/" ) ;
File[] file_list = demoDir.listFiles(DEMOTEMPLATEFILTER) ;
String[] name_list = new String[file_list.length] ;
if (file_list != null) {
for(int i = 0 ; i < name_list.length ; i++) {
String filename = file_list[i].getName() ;
int dot = filename.indexOf(".") ;
name_list[i] = dot > -1 ? filename.substring(0,dot) : filename ;
}
} else {
return new String[0];
}
return name_list;
}
// delete demotemplate
public int deleteDemoTemplate(int template_id) {
File f = new File(m_TemplateHome + "/text/demo/" + template_id + ".html") ;
if (f.exists()) {
f.delete() ;
return 0;
}
return -2 ;
}
/**
* <p>Return language. Returns the langprefix from the db. Takes a lang id
as argument. Will return null if something goes wrong.
Example: If the language id number for swedish is 1. then the call
myObject.getLanguage("1") will return 'se'
That is, provided that the prefix for swedish is 'se', which it isn't.
Or rather, it shouldn't be.
*/
public String getLanguage(String lang_id) {
return sqlProcedureStr("GetLangPrefixFromId " + lang_id) ;
}
/** Fetch the systemdata from the db */
protected SystemData getSystemDataFromDb() {
/** Fetch everything from the DB */
String serverMaster[] = this.sqlProcedure("ServerMasterGet") ;
String webMaster[] = this.sqlProcedure("WebMasterGet") ;
String systemMessage = this.sqlProcedureStr("SystemMessageGet") ;
/** Create a new SystemData object */
SystemData sd = new SystemData() ;
/** Store everything in the object */
sd.setSystemMessage(systemMessage) ;
if (serverMaster.length > 0) {
sd.setServerMaster(serverMaster[0]) ;
if (serverMaster.length > 1) {
sd.setServerMasterAddress(serverMaster[1]) ;
}
}
if (webMaster.length > 0) {
sd.setWebMaster(webMaster[0]) ;
if (webMaster.length > 1) {
sd.setWebMasterAddress(webMaster[1]) ;
}
}
return sd ;
}
public SystemData getSystemData () {
return sysData ;
}
public void setSystemData (SystemData sd) {
sysData = sd ;
String sqlStr = "WebMasterSet '"+sd.getWebMaster()+"','"+sd.getWebMasterAddress()+"'" ;
sqlUpdateProcedure(sqlStr) ;
sqlStr = "ServerMasterSet '"+sd.getServerMaster()+"','"+sd.getServerMasterAddress()+"'" ;
sqlUpdateProcedure(sqlStr) ;
sqlStr = "SystemMessageSet '"+sd.getSystemMessage()+"'" ;
sqlUpdateProcedure(sqlStr) ;
}
/**
Returns the information for each meta id passed as argument.
*/
public Hashtable ExistingDocsGetMetaIdInfo(String[] meta_id) {
// Lets build a comma separed string to send to the sproc
StringBuffer sBuf = new StringBuffer() ;
for( int i = 0; i< meta_id.length; i++ ) {
sBuf.append(meta_id[i]) ;
if(i != meta_id.length)
sBuf.append(",") ;
}
DBConnect dbc = new DBConnect(m_conPool) ;
dbc.getConnection() ;
dbc.setProcedure("ExistingDocsGetSelectedMetaIds ", sBuf.toString() ) ;
Vector data = (Vector)dbc.executeProcedure() ;
String[] meta = (String[])dbc.getMetaData() ;
int columns = dbc.getColumnCount() ;
dbc.clearResultSet() ;
dbc.closeConnection() ;
dbc = null ;
// Lets build the result into an hashtable
Hashtable result = new Hashtable(columns,0.5f) ;
if ( data.size() > 0 ) {
for ( int i = 0 ; i < columns ; i++ ) {
String temp_str[] = new String[data.size() / columns] ;
int counter = 0 ;
for ( int j = i ; j < data.size() ; j+=columns )
temp_str[counter++] = data.elementAt(j).toString() ;
result.put(meta[i],temp_str) ;
}
return result ;
} else {
return new Hashtable(1,0.5f) ;
}
}
/**
* Returns an array with with all the documenttypes stored in the database
* the array consists of pairs of id:, value. Suitable for parsing into select boxes etc.
*/
public String[] getDocumentTypesInList(String langPrefixStr) {
return this.sqlProcedure("GetDocTypes '" + langPrefixStr + "'" ) ;
}
/**
* Returns an hashtable with with all the documenttypes stored in the database
* the hashtable consists of pairs of id:, value.
*/
public Hashtable getDocumentTypesInHash(String langPrefixStr) {
return this.sqlQueryHash("GetDocTypes '" + langPrefixStr + "'") ;
}
public boolean checkUserDocSharePermission(User user, int meta_id) {
return sqlProcedure("CheckUserDocSharePermission "+user.getUserId()+","+meta_id).length>0 ;
}
} // END CLASS IMCService
| Fixed bug 145: <?imcms:include> made the parser throw a NumberFormatException.
git-svn-id: b7e9aa1d6cd963481915708f70423d437278b157@780 bd66a97b-2aff-0310-9095-89ca5cabf5a6
| server/src/imcode/server/IMCService.java | Fixed bug 145: <?imcms:include> made the parser throw a NumberFormatException. |
|
Java | agpl-3.0 | 3f2839907bc26321e152d80199abf36e6b5ce9b5 | 0 | cstroe/spendhawk-java,cstroe/spendhawk-java,cstroe/spendhawk-java | package com.github.cstroe.spendhawk.web;
import com.github.cstroe.spendhawk.web.user.UserManagerServlet;
import com.github.cstroe.spendhawk.web.user.UsersServlet;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import static com.github.cstroe.spendhawk.util.ServletUtil.servletPath;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
@RunWith(Arquillian.class)
public class BasicFeaturesIT {
@ArquillianResource
URL deploymentUrl;
private static String userDetailPath;
private HttpResponse<String> response;
@Test
@RunAsClient
@InSequence(100)
public void connectToWelcomeServlet() throws Exception {
response = connect(WelcomeServlet.class);
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
boolean usersLinkExists = findLink(fullServletPath(UsersServlet.class), doc);
assertEquals("A link from the welcome page to the users page must exist.", usersLinkExists, true);
}
@Test
@RunAsClient
@InSequence(200)
public void connectToUsersServlet() throws Exception {
response = connect(UsersServlet.class);
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
Elements links = doc.getElementsByClass("userLink");
assertThat(links.size(), is(equalTo(0)));
}
@Test
@RunAsClient
@InSequence(300)
public void connectToUserManagerServlet() throws Exception {
response = connect(UserManagerServlet.class);
assertResponseStatus(200, response);
}
@Test
@RunAsClient
@InSequence(400)
public void createUser() throws Exception {
HttpResponse<String> response = Unirest.post(url(UserManagerServlet.class))
.field("user.name", "testuser")
.field("action", "Add User")
.asString();
assertResponseStatus(302, response);
// location header takes you to accounts page for that user
String redirectUrl = response.getHeaders().getFirst("location");
String urlPath = new URL(redirectUrl).getPath();
assertTrue(urlPath.startsWith(fullServletPath(AccountsServlet.class)));
String viewUsersUrl = url(UsersServlet.class);
response = Unirest.get(viewUsersUrl).asString();
Document doc = Jsoup.parse(response.getBody());
Elements links = doc.getElementsByClass("userLink");
assertThat(links.size(), is(equalTo(1)));
Element link = links.get(0);
userDetailPath = link.attr("href");
assertTrue(userDetailPath.startsWith(fullServletPath(AccountsServlet.class) + "?"));
}
@Test
@RunAsClient
@InSequence(500)
public void viewAccounts() throws Exception {
response = connect(userDetailPath);
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
boolean accountManagerLinkExists = findLink(fullServletPath(AccountManagerServlet.class), doc);
assertEquals("A link from the accounts page to the account manager page must exist.", accountManagerLinkExists, true);
}
/**
* Add the deployment context path to a servlet's path to create an absolute path.
*
* For example, given:
* deploymentUrl: "http://127.0.0.1:8080/a1dgfdw"
* servlet path: "/accounts/manage"
*
* Return: "/a1dgfdw/accounts/manage"
*/
private String fullServletPath(Class<? extends HttpServlet> servlet) {
StringBuilder servletUrl = new StringBuilder();
final String deploymentPath = deploymentUrl.getPath();
servletUrl.append(deploymentPath.substring(0, deploymentPath.length()-1));
servletUrl.append(servletPath(servlet));
return servletUrl.toString();
}
/**
* A helper method to connect to a specific servlet on the test deployment.
*/
private HttpResponse<String> connect(Class<? extends HttpServlet> servlet) {
try {
return Unirest.get(url(servlet)).asString();
} catch (UnirestException e) {
e.printStackTrace();
return null;
}
}
private HttpResponse<String> connect(String absolutePath) {
try {
return Unirest.get(url(absolutePath)).asString();
} catch (UnirestException | MalformedURLException e) {
e.printStackTrace();
return null;
}
}
/**
* Build the deployment url given the request path on the server.
*/
private String url(String requestPath) throws MalformedURLException {
StringBuilder url = new StringBuilder();
url.append("http://")
.append(deploymentUrl.getHost())
.append(":")
.append(deploymentUrl.getPort());
if(requestPath.startsWith(deploymentUrl.getPath())) {
url.append(requestPath);
} else {
url.append(deploymentUrl.getPath());
if(requestPath.startsWith("/")) {
url.append(requestPath.substring(1));
}
url.append(requestPath);
}
return url.toString();
}
/**
* Create the url for a servlet on the test deployment.
*/
private String url(Class<? extends HttpServlet> servlet) {
return "http://" +
deploymentUrl.getHost() +
":" +
deploymentUrl.getPort() +
fullServletPath(servlet);
}
/**
* Find a link to the given path.
* @return true if the path was found as one of the links' href, false if none was found
*/
private static boolean findLink(String path, Document doc) {
Elements links = doc.getElementsByTag("a");
if(path == null || links == null) {
return false;
}
boolean linkFound = false;
for(Element link : links) {
String currentLinkPath = link.attr("href");
if(currentLinkPath.equals(path)) {
linkFound = true;
}
}
if(!linkFound) {
try {
File tempFile = File.createTempFile("integrationTest", ".html");
FileWriter writer = new FileWriter(tempFile);
writer.write(doc.toString());
writer.close();
System.out.println("Saved response page to: file://" + tempFile.getAbsolutePath());
} catch(Exception ex) {
ex.printStackTrace();
}
}
return linkFound;
}
/**
* Save response output to a file if the response status assertion fails.
*/
private static void assertResponseStatus(int expected, HttpResponse<String> response) throws IOException {
if(response.getStatus() != expected) {
File tempFile = File.createTempFile("integrationTest", ".html");
FileWriter writer = new FileWriter(tempFile);
writer.write(response.getBody());
writer.close();
System.out.println("Saved response page to: file://" + tempFile.getAbsolutePath());
}
assertEquals(expected, response.getStatus());
}
}
| src/test/java/com/github/cstroe/spendhawk/web/BasicFeaturesIT.java | package com.github.cstroe.spendhawk.web;
import com.github.cstroe.spendhawk.web.user.UserManagerServlet;
import com.github.cstroe.spendhawk.web.user.UsersServlet;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@RunWith(Arquillian.class)
public class BasicFeaturesIT {
@ArquillianResource
URL deploymentUrl;
private static String userDetailUrl;
@Test
@RunAsClient
@InSequence(100)
public void connectToWelcomeServlet() throws Exception {
String url = deploymentUrl + WelcomeServlet.PATH.substring(1);
HttpResponse<String> response = Unirest.get(url).asString();
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
Elements links = doc.getElementsByTag("a");
String usersUrl = servletPath(deploymentUrl, UsersServlet.class);
assertEquals("A link from the welcome page to the users page must exist. Url: " + usersUrl,
findLink(usersUrl, links), true);
}
@Test
@RunAsClient
@InSequence(200)
public void connectToUsersServlet() throws Exception {
String url = deploymentUrl + UsersServlet.PATH.substring(1);
HttpResponse<String> response = Unirest.get(url).asString();
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
Elements links = doc.getElementsByClass("userLink");
assertThat(links.size(), is(equalTo(0)));
}
@Test
@RunAsClient
@InSequence(300)
public void connectToUserManagerServlet() throws Exception {
String url = deploymentUrl + UserManagerServlet.PATH.substring(1);
HttpResponse<String> response = Unirest.get(url).asString();
assertResponseStatus(200, response);
}
@Test
@RunAsClient
@InSequence(400)
public void createUser() throws Exception {
String url = deploymentUrl + UserManagerServlet.PATH.substring(1);
HttpResponse<String> response = Unirest.post(url)
.field("user.name", "testuser")
.field("action", "Add User")
.asString();
assertResponseStatus(302, response);
url = deploymentUrl + UsersServlet.PATH.substring(1);
response = Unirest.get(url).asString();
assertResponseStatus(200, response);
Document doc = Jsoup.parse(response.getBody());
Elements links = doc.getElementsByClass("userLink");
assertThat(links.size(), is(equalTo(1)));
Element link = links.get(0);
userDetailUrl = link.attr("href");
assertTrue(userDetailUrl.contains(AccountsServlet.PATH + "?"));
}
@Test
@RunAsClient
@InSequence(500)
public void viewAccounts() throws Exception {
String url = deploymentUrl + userDetailUrl;
HttpResponse<String> response = Unirest.get(url).asString();
assertResponseStatus(200, response);
}
/**
* Build the path of a given servlet, to be used when verifying that links
* exist.
*/
private static String servletPath(URL deploymentUrl, Class<? extends HttpServlet> servlet) {
StringBuilder servletUrl = new StringBuilder();
try {
Field path = servlet.getDeclaredField("PATH");
String servletPath = (String) path.get(servlet);
String deploymentPath = deploymentUrl.getPath();
servletUrl.append(deploymentPath.substring(0, deploymentPath.length()-1))
.append(servletPath);
return servletUrl.toString();
} catch(IllegalAccessException | NoSuchFieldException ex) {
return null;
}
}
/**
* Find a link to the given path.
* @param links A list of links.
* @return true if the path was found as one of the links' href, false if none was found
*/
private static boolean findLink(String path, Elements links) {
if(path == null || links == null) {
return false;
}
boolean linkFound = false;
for(Element link : links) {
String currentLinkPath = link.attr("href");
if(currentLinkPath.equals(path)) {
linkFound = true;
}
}
return linkFound;
}
/**
* Save response output to a file if the response status assertion fails.
*/
private static void assertResponseStatus(int expected, HttpResponse<String> response) throws IOException {
if(response.getStatus() != expected) {
File tempFile = File.createTempFile("integrationTest", ".html");
FileWriter writer = new FileWriter(tempFile);
writer.write(response.getBody());
writer.close();
System.out.println("Saved error output to: file://" + tempFile.getAbsolutePath());
}
assertEquals(expected, response.getStatus());
}
}
| Cleaner and more thorough tests.
| src/test/java/com/github/cstroe/spendhawk/web/BasicFeaturesIT.java | Cleaner and more thorough tests. |
|
Java | lgpl-2.1 | a106106389d53c611df27dcfd9b06997315414dd | 0 | ebollens/ccnmp,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,ebollens/ccnmp,cawka/ndnx,svartika/ccnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx | /*
* Part of the CCNx Java Library.
*
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library 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
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.versioning;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.TreeSet;
/**
* Add some missing features from the JDK 5 TreeSet. If
* running on JDK 6, use them as they will be way more efficient.
* This class is to provide JDK compatibility for the versioning
* package and only implements the needed functionality.
*
* The user should call the *Compatible methods (floorCompatible, etc.)
* instead of the Java 6 methods (e.g. floor).
*
* When used in a JDK 5 environment, the implementations of the
* provided algorithms is going to be O(N), not O(log N). There is no
* fast-fail detection for concurrent modifications. The descendingIterator
* works fine for iteration and calling remove(), but if you mix in
* other calls, like to add() while iterating, you will not see those
* values.
*/
public class TreeSet6<E> extends TreeSet<E> {
public TreeSet6() {
initialize();
}
public TreeSet6(Comparator<? super E> c) {
super(c);
initialize();
}
/**
* Returns the greatest element in this set less than or equal to the
* given element, or null if there is no such element.
*
* Use this method, not floor().
*/
@SuppressWarnings("unchecked")
public E floorCompatible(E key) {
if( null != floor )
try {
return (E) floor.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalFloor(key);
}
/**
* Returns the least element in this set greater than or equal to the
* given element, or null if there is no such element.
*
* Use this method, not ceiling().
*/
@SuppressWarnings("unchecked")
public E ceilingCompatible(E key) {
if( null != ceiling )
try {
return (E) ceiling.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalCeiling(key);
}
/**
* Returns the greatest element in this set strictly less than the
* given element, or null if there is no such element.
*
* Use this method, not lower().
*/
@SuppressWarnings("unchecked")
public E lowerCompatible(E key) {
if( null != lower )
try {
return (E) lower.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalLower(key);
}
/**
* Returns the least element in this set strictly greater than the
* given element, or null if there is no such element.
*
* Use this method, not higher().
*/
@SuppressWarnings("unchecked")
public E higherCompatible(E key) {
if( null != higher )
try {
return (E) higher.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalHigher(key);
}
/**
* Returns an iterator over the elements in this set in descending order.
* @return
*/
@SuppressWarnings("unchecked")
public Iterator<E> descendingIteratorCompatible() {
if( null != higher )
try {
return (Iterator<E>) descendingIterator.invoke(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalDescendingIterator();
}
// =============================================
private static final long serialVersionUID = 7840825335033077895L;
// These are transient because they should not be considered part of the TreeSet's
// serializable state
private transient Method floor = null;
private transient Method ceiling = null;
private transient Method lower = null;
private transient Method higher = null;
private transient Method descendingIterator = null;
/**
* Our own wrapper for getMethod that returns null if the method is not found.
* @param c class to search for method
* @param name method name
* @param parameterTypes
* @return the method or null if not found
*/
protected Method getMethod(Class<?> c, String name, Class<?>... parameterTypes) {
Method m = null;
try {
m = c.getMethod(name, parameterTypes);
} catch (NoSuchMethodException nsme) {
// ignore this, we'll just return null
}
return m;
}
private Iterator<E> internalDescendingIterator() {
return new DescendingIterator<E>();
}
private void initialize() {
try {
Class<?>[] parameterTypes = new Class[] { Object.class };
Class<?> c = this.getClass();
Class<?> cc = c.getSuperclass();
try {
floor = cc.getMethod("floor", parameterTypes);
} catch(NoSuchMethodException nsme) {}
try {
ceiling = cc.getMethod("ceiling", parameterTypes);
} catch(NoSuchMethodException nsme) {}
try {
lower = cc.getMethod("lower", parameterTypes);
} catch(NoSuchMethodException nsme) {}
try {
higher = cc.getMethod("higher", parameterTypes);
} catch(NoSuchMethodException nsme) {}
try {
descendingIterator = cc.getMethod("descendingIterator");
} catch(NoSuchMethodException nsme) {}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the greatest element in this set less than or equal to the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalFloor(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the test value
if( mycompare(comparator, comparable, key, test) == 0 )
return test;
// key is before test, so we have run past the place
// where the floor could be. Return our best result so far.
if( mycompare(comparator, comparable, key, test) < 0 )
return rtn;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the least element in this set greater than or equal to the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalCeiling(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the test value
if( mycompare(comparator, comparable, key, test) == 0 )
return test;
// key is before test, so we have come to the
// first element in the set greater than key
// without equality, so return this.
if( mycompare(comparator, comparable, key, test) < 0 )
return test;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the least element in this set strictly greater than the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalHigher(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// key is before test, so we have come to the
// first element in the set greater than key
// without equality, so return this.
if( mycompare(comparator, comparable, key, test) < 0 )
return test;
// else test <= key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the greatest element in this set strictly less than the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalLower(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the last test value visited
if( mycompare(comparator, comparable, key, test) == 0 )
return rtn;
// key is before test, so we have run past the place
// where the floor could be. Return our best result so far.
if( mycompare(comparator, comparable, key, test) < 0 )
return rtn;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* if comp not null, use comp, else use comparable if not null, else
* throw a ClassCast exception
* @param comparator the Comparator to use
* @param comparable the casting to (Comparable) from a
* @param a
* @param b
* @return -1 if a<b, 0 a==0, +1 a>b
*/
protected int mycompare(Comparator<? super E> comparator, Comparable<? super E> comparable, E a, E b) throws ClassCastException {
if( null != comparator )
return(comparator.compare(a,b));
if( null != comparable )
return(comparable.compareTo(b));
throw new ClassCastException("not comparable");
}
// ================================================
protected class DescendingIterator<T> implements Iterator<T> {
private final LinkedList<T> _list;
private ListIterator<T> _listIterator;
private T _lastReturnedValue = null;
@SuppressWarnings("unchecked")
public DescendingIterator() {
_list = new LinkedList<T>((Collection<? extends T>) TreeSet6.this);
_listIterator = _list.listIterator();
// now move the iterator to the end
while(_listIterator.hasNext())
_listIterator.next();
}
public boolean hasNext() {
return _listIterator.hasPrevious();
}
public T next() {
_lastReturnedValue = _listIterator.previous();
return _lastReturnedValue;
}
public void remove() {
if( null == _lastReturnedValue )
throw new IllegalStateException("Remove has already been called or no value has been returned");
_listIterator.remove();
TreeSet6.this.remove(_lastReturnedValue);
_lastReturnedValue = null;
}
}
}
| javasrc/src/org/ccnx/ccn/profiles/versioning/TreeSet6.java | /*
* Part of the CCNx Java Library.
*
* Copyright (C) 2011 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library 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
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.versioning;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.TreeSet;
/**
* Add some missing features from the JDK 5 TreeSet. If
* running on JDK 6, use them as they will be way more efficient.
* This class is to provide JDK compatibility for the versioning
* package and only implements the needed functionality.
*
* The user should call the *Compatible methods (floorCompatible, etc.)
* instead of the Java 6 methods (e.g. floor).
*
* When used in a JDK 5 environment, the implementations of the
* provided algorithms is going to be O(N), not O(log N). There is no
* fast-fail detection for concurrent modifications. The descendingIterator
* works fine for iteration and calling remove(), but if you mix in
* other calls, like to add() while iterating, you will not see those
* values.
*/
public class TreeSet6<E> extends TreeSet<E> {
public TreeSet6() {
initialize();
}
public TreeSet6(Comparator<? super E> c) {
super(c);
initialize();
}
/**
* Returns the greatest element in this set less than or equal to the
* given element, or null if there is no such element.
*
* Use this method, not floor().
*/
@SuppressWarnings("unchecked")
public E floorCompatible(E key) {
if( null != floor )
try {
return (E) floor.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalFloor(key);
}
/**
* Returns the least element in this set greater than or equal to the
* given element, or null if there is no such element.
*
* Use this method, not ceiling().
*/
@SuppressWarnings("unchecked")
public E ceilingCompatible(E key) {
if( null != ceiling )
try {
return (E) ceiling.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalCeiling(key);
}
/**
* Returns the greatest element in this set strictly less than the
* given element, or null if there is no such element.
*
* Use this method, not lower().
*/
@SuppressWarnings("unchecked")
public E lowerCompatible(E key) {
if( null != lower )
try {
return (E) lower.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalLower(key);
}
/**
* Returns the least element in this set strictly greater than the
* given element, or null if there is no such element.
*
* Use this method, not higher().
*/
@SuppressWarnings("unchecked")
public E higherCompatible(E key) {
if( null != higher )
try {
return (E) higher.invoke(this, (Object) key);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalHigher(key);
}
/**
* Returns an iterator over the elements in this set in descending order.
* @return
*/
@SuppressWarnings("unchecked")
public Iterator<E> descendingIteratorCompatible() {
if( null != higher )
try {
return (Iterator<E>) descendingIterator.invoke(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
return internalDescendingIterator();
}
// =============================================
private static final long serialVersionUID = 7840825335033077895L;
// These are transient because they should not be considered part of the TreeSet's
// serializable state
private transient Method floor = null;
private transient Method ceiling = null;
private transient Method lower = null;
private transient Method higher = null;
private transient Method descendingIterator = null;
/**
* Our own wrapper for getMethod that returns null if the method is not found.
* @param c class to search for method
* @param name method name
* @param parameterTypes
* @return the method or null if not found
*/
protected Method getMethod(Class<?> c, String name, Class<?>... parameterTypes) {
Method m = null;
try {
m = c.getMethod(name, parameterTypes);
} catch (NoSuchMethodException nsme) {
// ignore this, we'll just return null
}
return m;
}
private Iterator<E> internalDescendingIterator() {
return new DescendingIterator<E>();
}
private void initialize() {
try {
Class<?>[] parameterTypes = new Class[] { Object.class };
Class<?> c = this.getClass();
Class<?> cc = c.getSuperclass();
floor = cc.getMethod("floor", parameterTypes);
ceiling = cc.getMethod("ceiling", parameterTypes);
lower = cc.getMethod("lower", parameterTypes);
higher = cc.getMethod("higher", parameterTypes);
descendingIterator = cc.getMethod("descendingIterator");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the greatest element in this set less than or equal to the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalFloor(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the test value
if( mycompare(comparator, comparable, key, test) == 0 )
return test;
// key is before test, so we have run past the place
// where the floor could be. Return our best result so far.
if( mycompare(comparator, comparable, key, test) < 0 )
return rtn;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the least element in this set greater than or equal to the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalCeiling(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the test value
if( mycompare(comparator, comparable, key, test) == 0 )
return test;
// key is before test, so we have come to the
// first element in the set greater than key
// without equality, so return this.
if( mycompare(comparator, comparable, key, test) < 0 )
return test;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the least element in this set strictly greater than the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalHigher(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// key is before test, so we have come to the
// first element in the set greater than key
// without equality, so return this.
if( mycompare(comparator, comparable, key, test) < 0 )
return test;
// else test <= key, so keep looking
rtn = test;
}
return rtn;
}
/**
* Returns the greatest element in this set strictly less than the
* given element, or null if there is no such element.
*/
@SuppressWarnings("unchecked")
protected E internalLower(E key) {
Comparator<? super E> comparator = this.comparator();
Comparable<? super E> comparable = null;
if( key instanceof Comparable<?>) {
comparable = (Comparable<? super E>) key;
}
E rtn = null;
Iterator<E> iter = iterator();
while( iter.hasNext() ) {
E test = iter.next();
// An exact match, return the last test value visited
if( mycompare(comparator, comparable, key, test) == 0 )
return rtn;
// key is before test, so we have run past the place
// where the floor could be. Return our best result so far.
if( mycompare(comparator, comparable, key, test) < 0 )
return rtn;
// else test < key, so keep looking
rtn = test;
}
return rtn;
}
/**
* if comp not null, use comp, else use comparable if not null, else
* throw a ClassCast exception
* @param comparator the Comparator to use
* @param comparable the casting to (Comparable) from a
* @param a
* @param b
* @return -1 if a<b, 0 a==0, +1 a>b
*/
protected int mycompare(Comparator<? super E> comparator, Comparable<? super E> comparable, E a, E b) throws ClassCastException {
if( null != comparator )
return(comparator.compare(a,b));
if( null != comparable )
return(comparable.compareTo(b));
throw new ClassCastException("not comparable");
}
// ================================================
protected class DescendingIterator<T> implements Iterator<T> {
private final LinkedList<T> _list;
private ListIterator<T> _listIterator;
private T _lastReturnedValue = null;
@SuppressWarnings("unchecked")
public DescendingIterator() {
_list = new LinkedList<T>((Collection<? extends T>) TreeSet6.this);
_listIterator = _list.listIterator();
// now move the iterator to the end
while(_listIterator.hasNext())
_listIterator.next();
}
public boolean hasNext() {
return _listIterator.hasPrevious();
}
public T next() {
_lastReturnedValue = _listIterator.previous();
return _lastReturnedValue;
}
public void remove() {
if( null == _lastReturnedValue )
throw new IllegalStateException("Remove has already been called or no value has been returned");
_listIterator.remove();
TreeSet6.this.remove(_lastReturnedValue);
_lastReturnedValue = null;
}
}
}
| Refs #100320-365-merge. Somehow lost the catches for NoSuchMethodException, so add them back to initialize().
| javasrc/src/org/ccnx/ccn/profiles/versioning/TreeSet6.java | Refs #100320-365-merge. Somehow lost the catches for NoSuchMethodException, so add them back to initialize(). |
|
Java | lgpl-2.1 | b032efa917bb0b3977b5575b82f004c1ce3fe022 | 0 | zebrafishmine/intermine,tomck/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,joshkh/intermine,tomck/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,zebrafishmine/intermine,zebrafishmine/intermine,kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,drhee/toxoMine,drhee/toxoMine,JoeCarlson/intermine,elsiklab/intermine,justincc/intermine,tomck/intermine,zebrafishmine/intermine,JoeCarlson/intermine,zebrafishmine/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,tomck/intermine,tomck/intermine,tomck/intermine,kimrutherford/intermine,zebrafishmine/intermine,elsiklab/intermine,justincc/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,drhee/toxoMine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,JoeCarlson/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,elsiklab/intermine,drhee/toxoMine,drhee/toxoMine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,drhee/toxoMine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,drhee/toxoMine,JoeCarlson/intermine,JoeCarlson/intermine,joshkh/intermine | package org.intermine.webservice.server.template.result;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.search.Scope;
import org.intermine.api.template.SwitchOffAbility;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplatePopulator;
import org.intermine.api.template.TemplatePopulatorException;
import org.intermine.api.template.TemplateQuery;
import org.intermine.api.template.TemplateValue;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathConstraintBag;
import org.intermine.pathquery.PathConstraintLookup;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.TemplateAction;
import org.intermine.web.util.URLGenerator;
import org.intermine.webservice.server.WebService;
import org.intermine.webservice.server.exceptions.BadRequestException;
import org.intermine.webservice.server.exceptions.ResourceNotFoundException;
import org.intermine.webservice.server.query.result.PathQueryBuilderForJSONObj;
import org.intermine.webservice.server.query.result.QueryResultService;
/**
* Web service that returns results of public template constrained with values in request.
* All constraints operations and values that are in template must be specified in request.
* @author Jakub Kulaviak
*/
public class TemplateResultService extends QueryResultService
{
/** Name of type parameter **/
public static final String TYPE_PARAMETER = "type";
/** Name of name parameter **/
public static final String NAME_PARAMETER = "name";
private static final Logger LOG = Logger.getLogger(TemplateResultService.class);
/**
* Construct with an InterMineAPI.
* @param im the InterMine API
*/
public TemplateResultService(InterMineAPI im) {
super(im);
}
/**
* {@inheritDoc}}
*/
@Override
protected void execute(HttpServletRequest request,
HttpServletResponse response) {
TemplateManager templateManager = this.im.getTemplateManager();
TemplateResultInput input = getInput();
TemplateQuery template;
if (isAuthenticated()) {
Profile profile = SessionMethods.getProfile(request.getSession());
template = templateManager.getUserOrGlobalTemplate(profile, input.getName());
} else {
template = templateManager.getGlobalTemplate(input.getName());
}
if (template == null) {
throw new ResourceNotFoundException("public template with name '" + input.getName()
+ "' doesn't exist.");
}
Map<String, List<TemplateValue>> templateValues = getValuesFromInput(template, input);
TemplateQuery populatedTemplate;
try {
populatedTemplate =
TemplatePopulator.getPopulatedTemplate(template, templateValues);
} catch (TemplatePopulatorException e) {
e.printStackTrace();
LOG.error("Error populating template: " + template.getName() + ". " + e);
throw new BadRequestException("Error in applying constraint values to template: "
+ template.getName(), e);
}
if (getFormat() == WebService.JSON_OBJ_FORMAT) {
List<String> newView = PathQueryBuilderForJSONObj.getAlteredViews(populatedTemplate);
populatedTemplate.clearView();
populatedTemplate.addViews(newView);
}
setHeaderAttributes(populatedTemplate, input.getStart(), input.getMaxCount(),
populatedTemplate.getTitle());
if (populatedTemplate.isValid()) {
runPathQuery(populatedTemplate, input.getStart(), input.getMaxCount(),
populatedTemplate.getTitle(), populatedTemplate.getDescription(), input,
getMineLinkURL(request, populatedTemplate, input), input.getLayout());
} else {
String msg = "Required data source (template) is outdated and is in conflict "
+ "with model: " + populatedTemplate.verifyQuery();
throw new BadRequestException(msg);
}
}
private Map<String, List<TemplateValue>> getValuesFromInput(TemplateQuery template,
TemplateResultInput input) {
Map<String, List<TemplateValue>> values = new HashMap<String, List<TemplateValue>>();
for (String path : template.getEditablePaths()) {
List<PathConstraint> constraintsForPath = template.getEditableConstraints(path);
List<ConstraintInput> inputsForPath = new ArrayList<ConstraintInput>();
if (input.getConstraints().get(path) != null) {
inputsForPath.addAll(input.getConstraints().get(path));
}
// too many inputs for path
if (constraintsForPath.size() < inputsForPath.size()) {
throw new BadRequestException("There were more constraints specified "
+ " in the request than there are editable constraints for path "
+ path + ".");
}
if (constraintsForPath.size() == 1) {
// one constraint and at most one input
PathConstraint con = constraintsForPath.get(0);
ConstraintInput conInput = null;
if (!inputsForPath.isEmpty()) {
conInput = inputsForPath.get(0);
}
checkAndAddValue(values, template, con, conInput, null);
} else {
// more than one constraint so we need to look at codes
for (PathConstraint con : constraintsForPath) {
ConstraintInput foundConInput = null;
String code = template.getConstraints().get(con);
for (ConstraintInput conInput : inputsForPath) {
if (StringUtils.isBlank(conInput.getCode())) {
throw new BadRequestException("There are multiple editable constraints"
+ "for path " + path + " but codes weren't set. If there is"
+ " more than one constraint on a path you need to specify the"
+ " corresponding constraint codes.");
}
if (conInput.getCode().equals(code)) {
if (foundConInput != null) {
throw new BadRequestException("There was more than one constraint"
+ " specified with code: " + conInput.getCode()
+ " in the request for path: " + path + " You should only"
+ " provide one value per code.");
}
foundConInput = conInput;
}
}
// foundConInput may be null but that's ok if the constraint is optional
checkAndAddValue(values, template, con, foundConInput, code);
}
}
}
return values;
}
private void checkAndAddValue(Map<String, List<TemplateValue>> values, TemplateQuery template,
PathConstraint con, ConstraintInput conInput, String code) {
if (conInput != null) {
if (template.isRequired(con)) {
addToValuesMap(values, createTemplateValue(con, conInput, SwitchOffAbility.LOCKED));
} else {
addToValuesMap(values, createTemplateValue(con, conInput, SwitchOffAbility.ON));
}
} else if (template.isRequired(con)) {
throw new BadRequestException("There isn't a specified constraint value "
+ "and operation for path " + con.getPath()
+ ((code != null) ? " and code " + code : "")
+ " in the request; this constraint is required.");
} else {
// no value was provided but the constraint was optional so we can do nothing
}
}
private void addToValuesMap(Map<String, List<TemplateValue>> valMap, TemplateValue newValue) {
String path = newValue.getConstraint().getPath();
List<TemplateValue> values = valMap.get(path);
if (values == null) {
values = new ArrayList<TemplateValue>();
valMap.put(path, values);
}
values.add(newValue);
}
private TemplateValue createTemplateValue(PathConstraint con, ConstraintInput input,
SwitchOffAbility switchOffAbility) {
TemplateValue value;
if (con instanceof PathConstraintLookup) {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.SIMPLE_VALUE, input.getExtraValue(), switchOffAbility);
} else if (con instanceof PathConstraintBag) {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.BAG_VALUE, switchOffAbility);
} else {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.SIMPLE_VALUE, switchOffAbility);
}
return value;
}
// private TemplateValue createDummyTemplateValue(PathConstraint con) {
// TemplateValue value;
// value = new TemplateValue(con, con.getOp(), "dummy",
// TemplateValue.ValueType.SIMPLE_VALUE, SwitchOffAbility.OFF);
// return value;
// }
private TemplateResultInput getInput() {
return new TemplateResultRequestParser(request).getInput();
}
private String getMineLinkURL(HttpServletRequest request, TemplateQuery template,
TemplateResultInput input) {
String ret = new URLGenerator(request).getBaseURL();
ret += "/" + TemplateAction.TEMPLATE_ACTION_PATH;
ret += "?" + getQueryString(request, template, input);
ret += "&" + TemplateAction.SKIP_BUILDER_PARAMETER + "&"
+ TemplateResultService.TYPE_PARAMETER + "=" + Scope.ALL;
return ret;
}
private String getQueryString(HttpServletRequest request,
TemplateQuery template, TemplateResultInput input) {
String ret = "";
ret += TemplateResultService.NAME_PARAMETER + "=" + encode(input.getName()) + "&";
int i = 1;
for (PathConstraint con : template.getEditableConstraints()) {
ret += constraintToString(getCorrespondingInput(template, con, input), i);
i++;
}
return ret;
}
@Override
protected String getLinkPath(PathQuery pq, String format) {
if (!(pq instanceof TemplateQuery)) {
throw new IllegalArgumentException(
"The template results service only handles "
+ "TemplateQuerys, I got: " + pq.getClass());
}
TemplateQuery template = (TemplateQuery) pq;
TemplateResultLinkGenerator linkGen = new TemplateResultLinkGenerator();
return linkGen.getLinkPath(template, format);
}
private ConstraintInput getCorrespondingInput(TemplateQuery template, PathConstraint con,
TemplateResultInput input) {
List<ConstraintInput> conInputs = input.getConstraints().get(con.getPath());
String code = template.getConstraints().get(con);
if (conInputs != null) {
if (conInputs.size() == 1) {
return conInputs.get(0);
} else {
for (ConstraintInput conInput : conInputs) {
if (conInput.getCode().equals(code)) {
return conInput;
}
}
}
}
return null;
}
private String constraintToString(ConstraintInput input, int index) {
String ret = "";
if (input != null) {
ret += encode("attributeOps(" + index + ")") + "=";
ret += encode(input.getConstraintOp().getIndex().toString()) + "&";
ret += encode("attributeValues(" + index + ")") + "=";
ret += encode(input.getValue()) + "&";
if (input.getExtraValue() != null) {
ret += encode("extraValues(" + index + ")") + "="
+ encode(input.getExtraValue()) + "&";
}
}
return ret;
}
}
| intermine/web/main/src/org/intermine/webservice/server/template/result/TemplateResultService.java | package org.intermine.webservice.server.template.result;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.search.Scope;
import org.intermine.api.template.SwitchOffAbility;
import org.intermine.api.template.TemplateManager;
import org.intermine.api.template.TemplatePopulator;
import org.intermine.api.template.TemplatePopulatorException;
import org.intermine.api.template.TemplateQuery;
import org.intermine.api.template.TemplateValue;
import org.intermine.pathquery.PathConstraint;
import org.intermine.pathquery.PathConstraintBag;
import org.intermine.pathquery.PathConstraintLookup;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.PortalHelper;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.TemplateAction;
import org.intermine.web.util.URLGenerator;
import org.intermine.webservice.server.WebService;
import org.intermine.webservice.server.exceptions.BadRequestException;
import org.intermine.webservice.server.exceptions.ResourceNotFoundException;
import org.intermine.webservice.server.query.result.PathQueryBuilderForJSONObj;
import org.intermine.webservice.server.query.result.QueryResultService;
/**
* Web service that returns results of public template constrained with values in request.
* All constraints operations and values that are in template must be specified in request.
* @author Jakub Kulaviak
*/
public class TemplateResultService extends QueryResultService
{
/** Name of type parameter **/
public static final String TYPE_PARAMETER = "type";
/** Name of name parameter **/
public static final String NAME_PARAMETER = "name";
private static final Logger LOG = Logger.getLogger(TemplateResultService.class);
/**
* Construct with an InterMineAPI.
* @param im the InterMine API
*/
public TemplateResultService(InterMineAPI im) {
super(im);
}
/**
* {@inheritDoc}}
*/
@Override
protected void execute(HttpServletRequest request,
HttpServletResponse response) {
TemplateManager templateManager = this.im.getTemplateManager();
TemplateResultInput input = getInput();
TemplateQuery template;
if (isAuthenticated()) {
Profile profile = SessionMethods.getProfile(request.getSession());
template = templateManager.getUserOrGlobalTemplate(profile, input.getName());
} else {
template = templateManager.getGlobalTemplate(input.getName());
}
if (template == null) {
throw new ResourceNotFoundException("public template with name '" + input.getName()
+ "' doesn't exist.");
}
Map<String, List<TemplateValue>> templateValues = getValuesFromInput(template, input);
TemplateQuery populatedTemplate;
try {
populatedTemplate =
TemplatePopulator.getPopulatedTemplate(template, templateValues);
} catch (TemplatePopulatorException e) {
e.printStackTrace();
LOG.error("Error populating template: " + template.getName() + ". " + e);
throw new BadRequestException("Error in applying constraint values to template: "
+ template.getName(), e);
}
if (getFormat() == WebService.JSON_OBJ_FORMAT) {
List<String> newView = PathQueryBuilderForJSONObj.getAlteredViews(populatedTemplate);
populatedTemplate.clearView();
populatedTemplate.addViews(newView);
}
setHeaderAttributes(populatedTemplate, input.getStart(), input.getMaxCount(),
input.getName());
if (populatedTemplate.isValid()) {
runPathQuery(populatedTemplate, input.getStart(), input.getMaxCount(),
populatedTemplate.getTitle(), populatedTemplate.getDescription(), input,
getMineLinkURL(request, populatedTemplate, input), input.getLayout());
} else {
String msg = "Required data source (template) is outdated and is in conflict "
+ "with model: " + populatedTemplate.verifyQuery();
throw new BadRequestException(msg);
}
}
private Map<String, List<TemplateValue>> getValuesFromInput(TemplateQuery template,
TemplateResultInput input) {
Map<String, List<TemplateValue>> values = new HashMap<String, List<TemplateValue>>();
for (String path : template.getEditablePaths()) {
List<PathConstraint> constraintsForPath = template.getEditableConstraints(path);
List<ConstraintInput> inputsForPath = new ArrayList<ConstraintInput>();
if (input.getConstraints().get(path) != null) {
inputsForPath.addAll(input.getConstraints().get(path));
}
// too many inputs for path
if (constraintsForPath.size() < inputsForPath.size()) {
throw new BadRequestException("There were more constraints specified "
+ " in the request than there are editable constraints for path "
+ path + ".");
}
if (constraintsForPath.size() == 1) {
// one constraint and at most one input
PathConstraint con = constraintsForPath.get(0);
ConstraintInput conInput = null;
if (!inputsForPath.isEmpty()) {
conInput = inputsForPath.get(0);
}
checkAndAddValue(values, template, con, conInput, null);
} else {
// more than one constraint so we need to look at codes
for (PathConstraint con : constraintsForPath) {
ConstraintInput foundConInput = null;
String code = template.getConstraints().get(con);
for (ConstraintInput conInput : inputsForPath) {
if (StringUtils.isBlank(conInput.getCode())) {
throw new BadRequestException("There are multiple editable constraints"
+ "for path " + path + " but codes weren't set. If there is"
+ " more than one constraint on a path you need to specify the"
+ " corresponding constraint codes.");
}
if (conInput.getCode().equals(code)) {
if (foundConInput != null) {
throw new BadRequestException("There was more than one constraint"
+ " specified with code: " + conInput.getCode()
+ " in the request for path: " + path + " You should only"
+ " provide one value per code.");
}
foundConInput = conInput;
}
}
// foundConInput may be null but that's ok if the constraint is optional
checkAndAddValue(values, template, con, foundConInput, code);
}
}
}
return values;
}
private void checkAndAddValue(Map<String, List<TemplateValue>> values, TemplateQuery template,
PathConstraint con, ConstraintInput conInput, String code) {
if (conInput != null) {
if (template.isRequired(con)) {
addToValuesMap(values, createTemplateValue(con, conInput, SwitchOffAbility.LOCKED));
} else {
addToValuesMap(values, createTemplateValue(con, conInput, SwitchOffAbility.ON));
}
} else if (template.isRequired(con)) {
throw new BadRequestException("There isn't a specified constraint value "
+ "and operation for path " + con.getPath()
+ ((code != null) ? " and code " + code : "")
+ " in the request; this constraint is required.");
} else {
// no value was provided but the constraint was optional so we can do nothing
}
}
private void addToValuesMap(Map<String, List<TemplateValue>> valMap, TemplateValue newValue) {
String path = newValue.getConstraint().getPath();
List<TemplateValue> values = valMap.get(path);
if (values == null) {
values = new ArrayList<TemplateValue>();
valMap.put(path, values);
}
values.add(newValue);
}
private TemplateValue createTemplateValue(PathConstraint con, ConstraintInput input,
SwitchOffAbility switchOffAbility) {
TemplateValue value;
if (con instanceof PathConstraintLookup) {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.SIMPLE_VALUE, input.getExtraValue(), switchOffAbility);
} else if (con instanceof PathConstraintBag) {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.BAG_VALUE, switchOffAbility);
} else {
value = new TemplateValue(con, input.getConstraintOp(), input.getValue(),
TemplateValue.ValueType.SIMPLE_VALUE, switchOffAbility);
}
return value;
}
// private TemplateValue createDummyTemplateValue(PathConstraint con) {
// TemplateValue value;
// value = new TemplateValue(con, con.getOp(), "dummy",
// TemplateValue.ValueType.SIMPLE_VALUE, SwitchOffAbility.OFF);
// return value;
// }
private TemplateResultInput getInput() {
return new TemplateResultRequestParser(request).getInput();
}
private String getMineLinkURL(HttpServletRequest request, TemplateQuery template,
TemplateResultInput input) {
String ret = new URLGenerator(request).getBaseURL();
ret += "/" + TemplateAction.TEMPLATE_ACTION_PATH;
ret += "?" + getQueryString(request, template, input);
ret += "&" + TemplateAction.SKIP_BUILDER_PARAMETER + "&"
+ TemplateResultService.TYPE_PARAMETER + "=" + Scope.ALL;
return ret;
}
private String getQueryString(HttpServletRequest request,
TemplateQuery template, TemplateResultInput input) {
String ret = "";
ret += TemplateResultService.NAME_PARAMETER + "=" + encode(input.getName()) + "&";
int i = 1;
for (PathConstraint con : template.getEditableConstraints()) {
ret += constraintToString(getCorrespondingInput(template, con, input), i);
i++;
}
return ret;
}
@Override
protected String getExportLink(PathQuery pq, String format) {
if (!(pq instanceof TemplateQuery)) {
throw new IllegalArgumentException(
"The template results service only handles "
+ "TemplateQuerys, I got: " + pq.getClass());
}
TemplateQuery template = (TemplateQuery) pq;
String baseUrl = PortalHelper.getBaseUrl(request);
TemplateResultLinkGenerator linkGen = new TemplateResultLinkGenerator();
String xml = pq.toXml(PathQuery.USERPROFILE_VERSION);
return linkGen.getTabLink(baseUrl, template);
}
private ConstraintInput getCorrespondingInput(TemplateQuery template, PathConstraint con,
TemplateResultInput input) {
List<ConstraintInput> conInputs = input.getConstraints().get(con.getPath());
String code = template.getConstraints().get(con);
if (conInputs != null) {
if (conInputs.size() == 1) {
return conInputs.get(0);
} else {
for (ConstraintInput conInput : conInputs) {
if (conInput.getCode().equals(code)) {
return conInput;
}
}
}
}
return null;
}
private String constraintToString(ConstraintInput input, int index) {
String ret = "";
if (input != null) {
ret += encode("attributeOps(" + index + ")") + "=";
ret += encode(input.getConstraintOp().getIndex().toString()) + "&";
ret += encode("attributeValues(" + index + ")") + "=";
ret += encode(input.getValue()) + "&";
if (input.getExtraValue() != null) {
ret += encode("extraValues(" + index + ")") + "="
+ encode(input.getExtraValue()) + "&";
}
}
return ret;
}
}
| Provide the template title in JSON output, and only provide paths rather than full urls
| intermine/web/main/src/org/intermine/webservice/server/template/result/TemplateResultService.java | Provide the template title in JSON output, and only provide paths rather than full urls |
|
Java | lgpl-2.1 | c29d37bbb2fd792f038828f6d93d3469916e2812 | 0 | levants/lightmare | package org.lightmare.utils;
import java.util.Arrays;
import org.junit.Test;
public class CollectionUtilsTest {
@Test
public void arrayCastTest() {
try {
boolean[] bools = new boolean[2];
bools[0] = false;
bools[1] = true;
boolean[] casted = ObjectUtils.cast(bools, boolean[].class);
System.out.println(Arrays.toString(casted));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| src/test/java/org/lightmare/utils/CollectionUtilsTest.java | package org.lightmare.utils;
import java.util.Arrays;
import org.junit.Test;
public class CollectionUtilsTest {
@Test
public void arrayCastTest() {
try {
boolean[] bools = new boolean[2];
bools[0] = false;
bools[1] = true;
boolean[] casted = ObjectUtils.cast(bools, boolean[].class);
System.out.println(Arrays.toString(casted));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| improved CollectioUtils test cases | src/test/java/org/lightmare/utils/CollectionUtilsTest.java | improved CollectioUtils test cases |
|
Java | lgpl-2.1 | c76d23cb7a32245e570438fb605c185915e2cb32 | 0 | hal/core,hal/core,hal/core,hal/core,hal/core | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.shared.deployment;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanUtils;
import org.jboss.as.console.client.shared.deployment.model.DeployedEjb;
import org.jboss.as.console.client.shared.deployment.model.DeployedEndpoint;
import org.jboss.as.console.client.shared.deployment.model.DeployedPersistenceUnit;
import org.jboss.as.console.client.shared.deployment.model.DeployedServlet;
import org.jboss.as.console.client.shared.deployment.model.DeploymentData;
import org.jboss.as.console.client.shared.deployment.model.DeploymentEjbSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentJpaSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentRecord;
import org.jboss.as.console.client.shared.deployment.model.DeploymentWebSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentWebserviceSubsystem;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.widgets.browser.DefaultCellBrowser;
import org.jboss.ballroom.client.widgets.forms.CheckBoxItem;
import org.jboss.ballroom.client.widgets.forms.Form;
import org.jboss.ballroom.client.widgets.forms.FormItem;
import org.jboss.ballroom.client.widgets.forms.ListItem;
import org.jboss.ballroom.client.widgets.forms.TextAreaItem;
import org.jboss.ballroom.client.widgets.forms.TextBoxItem;
import org.jboss.dmr.client.ModelNode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Harald Pehl
* @date 12/04/2012
*/
public class DeploymentBrowser
{
private final DeploymentTreeModel deploymentTreeModel;
private final SingleSelectionModel<DeploymentRecord> selectionModel;
private final DefaultCellBrowser cellBrowser;
private final DeploymentBreadcrumb breadcrumb;
private final DeckPanel contextPanel;
private final Map<String, Form<DeploymentData>> forms;
private final Map<String, Integer> indexes;
private DeploymentBrowser.HelpCallback helpCallback;
public DeploymentBrowser(final DeploymentStore deploymentStore,
final SingleSelectionModel<DeploymentRecord> selectionModel)
{
forms = new HashMap<String, Form<DeploymentData>>();
indexes = new HashMap<String, Integer>();
this.selectionModel = selectionModel;
deploymentTreeModel = new DeploymentTreeModel(this, deploymentStore, this.selectionModel);
cellBrowser = new DefaultCellBrowser.Builder(deploymentTreeModel, null).build();
breadcrumb = new DeploymentBreadcrumb();
breadcrumb.getElement().setAttribute("style", "margin-top:30px;");
int index = 0;
this.contextPanel = new DeckPanel();
this.helpCallback = new HelpCallback();
Label noInfo = new Label("No deployments available.");
noInfo.getElement().addClassName("console-DeploymentBreadcrumb-noinfo");
noInfo.getElement().addClassName("console-DeploymentBreadcrumb-context");
this.contextPanel.add(noInfo);
index++;
addContext(DeploymentRecord.class, index++,
new TextAreaItem("name", "Name"),
new TextAreaItem("runtimeName", "Runtime Name")
);
addContext(DeploymentEjbSubsystem.class, index++);
addContext(DeploymentJpaSubsystem.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("defaultDataSource", "Default Datasource"),
new TextBoxItem("defaultInheritance", "Default Inheritance"));
addContext(DeploymentWebSubsystem.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("contextRoot", "Context Root"),
new TextBoxItem("virtualHost", "Virtual Host"));
addContext(DeploymentWebserviceSubsystem.class, index++);
addContext(DeployedEjb.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("componentClassname", "Component Classname"),
new ListItem("declaredRoles", "Declared Roles"),
new TextBoxItem("runAsRole", "Run As Role"),
new TextBoxItem("securityDomain", "Security Domain"));
addContext(DeployedPersistenceUnit.class, index++,
new TextAreaItem("name", "Name"),
new CheckBoxItem("enabled", "Statistics Enabled"),
new ListItem("entities", "Entities"));
addContext(DeployedServlet.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("servletClass", "Servlet Class"));
addContext(DeployedEndpoint.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("classname", "Classname"),
new TextBoxItem("context", "Context"),
new TextBoxItem("endpointType", "Type"),
new TextBoxItem("wsdl", "WSDL"));
}
@SuppressWarnings("unchecked")
private <T extends DeploymentData> void addContext(Class<T> clazz, int index, FormItem... formItems)
{
Widget widget;
String classname = clazz.getName();
if (formItems != null && formItems.length > 0)
{
Form<T> form = new Form<T>(clazz);
form.setNumColumns(1);
form.setEnabled(false);
form.setFields(formItems);
FormHelpPanel helpPanel = new FormHelpPanel(helpCallback, form);
forms.put(classname, (Form<DeploymentData>) form);
VerticalPanel wrapper = new VerticalPanel();
wrapper.setStyleName("fill-layout-width");
wrapper.add(helpPanel.asWidget());
wrapper.add(form.asWidget());
widget = wrapper;
}
else
{
widget = new Label("No information available.");
widget.getElement().addClassName("console-DeploymentBreadcrumb-noinfo");
}
widget.getElement().addClassName("console-DeploymentBreadcrumb-context");
indexes.put(classname, index);
contextPanel.add(widget);
}
/**
* Updates the list of deployments, selects the first deployment in the browser and shows the relevant context view.
* If the list is empty a special context view is displayed.
*
* @param deployments the deployments - can be empty, must not be null
*/
public void updateDeployments(List<DeploymentRecord> deployments)
{
deploymentTreeModel.updateDeployments(deployments);
if (deployments.isEmpty())
{
breadcrumb.empty();
contextPanel.showWidget(0);
}
else
{
DeploymentRecord firstDeployment = deployments.get(0);
selectionModel.setSelected(firstDeployment, true);
updateContext(firstDeployment);
}
}
@SuppressWarnings("unchecked")
public <T extends DeploymentData> void updateContext(final T selectedContext)
{
breadcrumb.setDeploymentData(selectedContext);
AutoBean<T> autoBean = AutoBeanUtils.getAutoBean(selectedContext);
String classname = autoBean.getType().getName();
Integer index = indexes.get(classname);
if (index != null && index > 0 && index < contextPanel.getWidgetCount())
{
Form<DeploymentData> form = forms.get(classname);
if (form != null)
{
helpCallback.setSelection(selectedContext);
form.edit(selectedContext);
}
contextPanel.showWidget(index);
}
}
public DefaultCellBrowser getCellBrowser()
{
return cellBrowser;
}
public DeploymentBreadcrumb getBreadcrumb()
{
return breadcrumb;
}
public DeckPanel getContextPanel()
{
return contextPanel;
}
class HelpCallback<T extends DeploymentData> implements FormHelpPanel.AddressCallback
{
private T selection;
@Override
public ModelNode getAddress()
{
ModelNode address = new ModelNode();
address.setEmptyList();
if (selection != null)
{
address = selection.getAddress();
}
return address;
}
public void setSelection(final T selection)
{
this.selection = selection;
}
}
}
| gui/src/main/java/org/jboss/as/console/client/shared/deployment/DeploymentBrowser.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.shared.deployment;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanUtils;
import org.jboss.as.console.client.shared.deployment.model.DeployedEjb;
import org.jboss.as.console.client.shared.deployment.model.DeployedEndpoint;
import org.jboss.as.console.client.shared.deployment.model.DeployedPersistenceUnit;
import org.jboss.as.console.client.shared.deployment.model.DeployedServlet;
import org.jboss.as.console.client.shared.deployment.model.DeploymentData;
import org.jboss.as.console.client.shared.deployment.model.DeploymentEjbSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentJpaSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentRecord;
import org.jboss.as.console.client.shared.deployment.model.DeploymentWebSubsystem;
import org.jboss.as.console.client.shared.deployment.model.DeploymentWebserviceSubsystem;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.widgets.browser.DefaultCellBrowser;
import org.jboss.ballroom.client.widgets.forms.CheckBoxItem;
import org.jboss.ballroom.client.widgets.forms.Form;
import org.jboss.ballroom.client.widgets.forms.FormItem;
import org.jboss.ballroom.client.widgets.forms.ListItem;
import org.jboss.ballroom.client.widgets.forms.TextAreaItem;
import org.jboss.ballroom.client.widgets.forms.TextBoxItem;
import org.jboss.dmr.client.ModelNode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Harald Pehl
* @date 12/04/2012
*/
public class DeploymentBrowser
{
private final DeploymentTreeModel deploymentTreeModel;
private final SingleSelectionModel<DeploymentRecord> selectionModel;
private final DefaultCellBrowser cellBrowser;
private final DeploymentBreadcrumb breadcrumb;
private final DeckPanel contextPanel;
private final Map<String, Form<DeploymentData>> forms;
private final Map<String, Integer> indexes;
private DeploymentBrowser.HelpCallback helpCallback;
public DeploymentBrowser(final DeploymentStore deploymentStore,
final SingleSelectionModel<DeploymentRecord> selectionModel)
{
forms = new HashMap<String, Form<DeploymentData>>();
indexes = new HashMap<String, Integer>();
this.selectionModel = selectionModel;
deploymentTreeModel = new DeploymentTreeModel(this, deploymentStore, this.selectionModel);
cellBrowser = new DefaultCellBrowser.Builder(deploymentTreeModel, null).build();
breadcrumb = new DeploymentBreadcrumb();
breadcrumb.getElement().setAttribute("style", "margin-top:30px;");
int index = 0;
this.contextPanel = new DeckPanel();
this.helpCallback = new HelpCallback();
Label noInfo = new Label("No deployments available.");
noInfo.getElement().addClassName("console-DeploymentBreadcrumb-noinfo");
noInfo.getElement().addClassName("console-DeploymentBreadcrumb-context");
this.contextPanel.add(noInfo);
index++;
addContext(DeploymentRecord.class, index++,
new TextAreaItem("name", "Name"),
new TextAreaItem("runtimeName", "Runtime Name"),
new TextAreaItem("path", "Path"),
new TextBoxItem("relativeTo", "Relative To"));
addContext(DeploymentEjbSubsystem.class, index++);
addContext(DeploymentJpaSubsystem.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("defaultDataSource", "Default Datasource"),
new TextBoxItem("defaultInheritance", "Default Inheritance"));
addContext(DeploymentWebSubsystem.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("contextRoot", "Context Root"),
new TextBoxItem("virtualHost", "Virtual Host"));
addContext(DeploymentWebserviceSubsystem.class, index++);
addContext(DeployedEjb.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("componentClassname", "Component Classname"),
new ListItem("declaredRoles", "Declared Roles"),
new TextBoxItem("runAsRole", "Run As Role"),
new TextBoxItem("securityDomain", "Security Domain"));
addContext(DeployedPersistenceUnit.class, index++,
new TextAreaItem("name", "Name"),
new CheckBoxItem("enabled", "Statistics Enabled"),
new ListItem("entities", "Entities"));
addContext(DeployedServlet.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("servletClass", "Servlet Class"));
addContext(DeployedEndpoint.class, index++,
new TextAreaItem("name", "Name"),
new TextBoxItem("classname", "Classname"),
new TextBoxItem("context", "Context"),
new TextBoxItem("endpointType", "Type"),
new TextBoxItem("wsdl", "WSDL"));
}
@SuppressWarnings("unchecked")
private <T extends DeploymentData> void addContext(Class<T> clazz, int index, FormItem... formItems)
{
Widget widget;
String classname = clazz.getName();
if (formItems != null && formItems.length > 0)
{
Form<T> form = new Form<T>(clazz);
form.setNumColumns(1);
form.setEnabled(false);
form.setFields(formItems);
FormHelpPanel helpPanel = new FormHelpPanel(helpCallback, form);
forms.put(classname, (Form<DeploymentData>) form);
VerticalPanel wrapper = new VerticalPanel();
wrapper.setStyleName("fill-layout-width");
wrapper.add(helpPanel.asWidget());
wrapper.add(form.asWidget());
widget = wrapper;
}
else
{
widget = new Label("No information available.");
widget.getElement().addClassName("console-DeploymentBreadcrumb-noinfo");
}
widget.getElement().addClassName("console-DeploymentBreadcrumb-context");
indexes.put(classname, index);
contextPanel.add(widget);
}
/**
* Updates the list of deployments, selects the first deployment in the browser and shows the relevant context view.
* If the list is empty a special context view is displayed.
*
* @param deployments the deployments - can be empty, must not be null
*/
public void updateDeployments(List<DeploymentRecord> deployments)
{
deploymentTreeModel.updateDeployments(deployments);
if (deployments.isEmpty())
{
breadcrumb.empty();
contextPanel.showWidget(0);
}
else
{
DeploymentRecord firstDeployment = deployments.get(0);
selectionModel.setSelected(firstDeployment, true);
updateContext(firstDeployment);
}
}
@SuppressWarnings("unchecked")
public <T extends DeploymentData> void updateContext(final T selectedContext)
{
breadcrumb.setDeploymentData(selectedContext);
AutoBean<T> autoBean = AutoBeanUtils.getAutoBean(selectedContext);
String classname = autoBean.getType().getName();
Integer index = indexes.get(classname);
if (index != null && index > 0 && index < contextPanel.getWidgetCount())
{
Form<DeploymentData> form = forms.get(classname);
if (form != null)
{
helpCallback.setSelection(selectedContext);
form.edit(selectedContext);
}
contextPanel.showWidget(index);
}
}
public DefaultCellBrowser getCellBrowser()
{
return cellBrowser;
}
public DeploymentBreadcrumb getBreadcrumb()
{
return breadcrumb;
}
public DeckPanel getContextPanel()
{
return contextPanel;
}
class HelpCallback<T extends DeploymentData> implements FormHelpPanel.AddressCallback
{
private T selection;
@Override
public ModelNode getAddress()
{
ModelNode address = new ModelNode();
address.setEmptyList();
if (selection != null)
{
address = selection.getAddress();
}
return address;
}
public void setSelection(final T selection)
{
this.selection = selection;
}
}
}
| browser doesn't need to show path attributes | gui/src/main/java/org/jboss/as/console/client/shared/deployment/DeploymentBrowser.java | browser doesn't need to show path attributes |
|
Java | lgpl-2.1 | a44536bd19d72f324ed8c8b56e2a10878acad0a0 | 0 | geotools/geotools,geotools/geotools,geotools/geotools,geotools/geotools | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-2014, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library 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
* Lesser General Public License for more details.
*/
package org.geotools.data.wfs.internal.v1_x;
import static org.geotools.data.wfs.internal.GetFeatureRequest.ResultType.RESULTS;
import static org.geotools.data.wfs.internal.HttpMethod.GET;
import static org.geotools.data.wfs.internal.HttpMethod.POST;
import static org.geotools.data.wfs.internal.Loggers.debug;
import static org.geotools.data.wfs.internal.Loggers.info;
import static org.geotools.data.wfs.internal.Loggers.requestInfo;
import static org.geotools.data.wfs.internal.Loggers.trace;
import static org.geotools.data.wfs.internal.WFSOperationType.GET_CAPABILITIES;
import static org.geotools.data.wfs.internal.WFSOperationType.GET_FEATURE;
import static org.geotools.data.wfs.internal.WFSOperationType.TRANSACTION;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.xml.namespace.QName;
import net.opengis.ows10.DCPType;
import net.opengis.ows10.DomainType;
import net.opengis.ows10.OperationType;
import net.opengis.ows10.OperationsMetadataType;
import net.opengis.ows10.RequestMethodType;
import net.opengis.wfs.DeleteElementType;
import net.opengis.wfs.DescribeFeatureTypeType;
import net.opengis.wfs.FeatureTypeListType;
import net.opengis.wfs.FeatureTypeType;
import net.opengis.wfs.GetFeatureType;
import net.opengis.wfs.InsertElementType;
import net.opengis.wfs.OperationsType;
import net.opengis.wfs.PropertyType;
import net.opengis.wfs.QueryType;
import net.opengis.wfs.ResultTypeType;
import net.opengis.wfs.TransactionType;
import net.opengis.wfs.UpdateElementType;
import net.opengis.wfs.WFSCapabilitiesType;
import net.opengis.wfs.WfsFactory;
import org.eclipse.emf.ecore.EObject;
import org.geotools.data.wfs.WFSServiceInfo;
import org.geotools.data.wfs.internal.AbstractWFSStrategy;
import org.geotools.data.wfs.internal.DescribeFeatureTypeRequest;
import org.geotools.data.wfs.internal.FeatureTypeInfo;
import org.geotools.data.wfs.internal.GetFeatureRequest;
import org.geotools.data.wfs.internal.GetFeatureRequest.ResultType;
import org.geotools.data.wfs.internal.HttpMethod;
import org.geotools.data.wfs.internal.Loggers;
import org.geotools.data.wfs.internal.TransactionRequest;
import org.geotools.data.wfs.internal.TransactionRequest.Delete;
import org.geotools.data.wfs.internal.TransactionRequest.Insert;
import org.geotools.data.wfs.internal.TransactionRequest.TransactionElement;
import org.geotools.data.wfs.internal.TransactionRequest.Update;
import org.geotools.data.wfs.internal.DescribeStoredQueriesRequest;
import org.geotools.data.wfs.internal.ListStoredQueriesRequest;
import org.geotools.data.wfs.internal.Versions;
import org.geotools.data.wfs.internal.WFSExtensions;
import org.geotools.data.wfs.internal.WFSGetCapabilities;
import org.geotools.data.wfs.internal.WFSOperationType;
import org.geotools.data.wfs.internal.WFSResponseFactory;
import org.geotools.data.wfs.internal.WFSStrategy;
import org.geotools.util.Version;
import org.geotools.wfs.v1_0.WFS;
import org.geotools.xml.Configuration;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.capability.FilterCapabilities;
import org.opengis.filter.sort.SortBy;
/**
*
*/
public class StrictWFS_1_x_Strategy extends AbstractWFSStrategy {
private static final List<String> PREFFERRED_GETFEATURE_FORMATS = Collections
.unmodifiableList(Arrays.asList("text/xml; subtype=gml/3.1.1",
"text/xml; subtype=gml/3.1.1/profiles/gmlsf/0", "GML3"));
private static final List<String> PREFFERRED_GETFEATURE_FORMATS_10 = Collections
.unmodifiableList(Arrays.asList("GML2"));
/**
* The WFS GetCapabilities document. Final by now, as we're not handling updatesequence, so will
* not ask the server for an updated capabilities during the life-time of this datastore.
*/
protected net.opengis.wfs.WFSCapabilitiesType capabilities;
private final Map<QName, FeatureTypeType> typeInfos;
private Version serviceVersion;
public StrictWFS_1_x_Strategy() {
// default to 1.0, override at setCapabilities if needed
this(Versions.v1_0_0);
}
public StrictWFS_1_x_Strategy(Version defaultVersion) {
super();
typeInfos = new HashMap<QName, FeatureTypeType>();
serviceVersion = defaultVersion;
}
/*---------------------------------------------------------------------
* AbstractWFSStrategy methods
* ---------------------------------------------------------------------*/
@Override
protected QName getOperationName(WFSOperationType operation) {
return new QName(WFS.NAMESPACE, operation.getName());
}
/**
* @see org.geotools.data.wfs.internal.AbstractWFSStrategy#createGetFeatureRequestPost(org.geotools.data.wfs.internal.GetFeatureRequest)
*/
@SuppressWarnings("unchecked")
@Override
protected GetFeatureType createGetFeatureRequestPost(GetFeatureRequest query)
throws IOException {
final QName typeName = query.getTypeName();
final FeatureTypeInfo featureTypeInfo = getFeatureTypeInfo(typeName);
final WfsFactory factory = WfsFactory.eINSTANCE;
GetFeatureType getFeature = factory.createGetFeatureType();
getFeature.setService("WFS");
getFeature.setVersion(getVersion());
String outputFormat = query.getOutputFormat();
getFeature.setOutputFormat(outputFormat);
getFeature.setHandle(query.getHandle());
Integer maxFeatures = query.getMaxFeatures();
if (maxFeatures != null) {
getFeature.setMaxFeatures(BigInteger.valueOf(maxFeatures.intValue()));
}
ResultType resultType = query.getResultType();
getFeature.setResultType(RESULTS == resultType ? ResultTypeType.RESULTS_LITERAL
: ResultTypeType.HITS_LITERAL);
QueryType wfsQuery = factory.createQueryType();
wfsQuery.setTypeName(Collections.singletonList(typeName));
final Filter supportedFilter;
final Filter unsupportedFilter;
{
final Filter filter = query.getFilter();
Filter[] splitFilters = splitFilters(typeName, filter);
supportedFilter = splitFilters[0];
unsupportedFilter = splitFilters[1];
}
query.setUnsupportedFilter(unsupportedFilter);
if (!Filter.INCLUDE.equals(supportedFilter)) {
wfsQuery.setFilter(supportedFilter);
}
String srsName = query.getSrsName();
if (null == srsName) {
srsName = featureTypeInfo.getDefaultSRS();
}
try {
wfsQuery.setSrsName(new URI(srsName));
} catch (URISyntaxException e) {
throw new RuntimeException("Can't create a URI from the query CRS: " + srsName, e);
}
String[] propertyNames = query.getPropertyNames();
boolean retrieveAllProperties = propertyNames == null;
if (!retrieveAllProperties) {
List<String> propertyName = wfsQuery.getPropertyName();
for (String propName : propertyNames) {
propertyName.add(propName);
}
}
SortBy[] sortByList = query.getSortBy();
if (sortByList != null) {
for (SortBy sortBy : sortByList) {
wfsQuery.getSortBy().add(sortBy);
}
}
getFeature.getQuery().add(wfsQuery);
return getFeature;
}
@Override
protected DescribeFeatureTypeType createDescribeFeatureTypeRequestPost(
DescribeFeatureTypeRequest request) {
final WfsFactory factory = WfsFactory.eINSTANCE;
DescribeFeatureTypeType dft = factory.createDescribeFeatureTypeType();
Version version = getServiceVersion();
dft.setService("WFS");
dft.setVersion(version.toString());
dft.setHandle(request.getHandle());
if (Versions.v1_0_0.equals(version)) {
dft.setOutputFormat(null);
}
QName typeName = request.getTypeName();
@SuppressWarnings("unchecked")
List<QName> typeNames = dft.getTypeName();
typeNames.add(typeName);
return dft;
}
@Override
protected EObject createListStoredQueriesRequestPost(
ListStoredQueriesRequest request) throws IOException {
// Not implemented in 1.0.0 or 1.1.0, this method should never be entered
throw new UnsupportedOperationException("WFS 1.0.0 / 1.1.0 does not support Stored Queries!");
}
@Override
protected EObject createDescribeStoredQueriesRequestPost(
DescribeStoredQueriesRequest request) throws IOException {
// Not implemented in 1.0.0 or 1.1.0, this method should never be entered
throw new UnsupportedOperationException("WFS 1.0.0 / 1.1.0 does not support Stored Queries!");
}
@Override
protected EObject createTransactionRequest(TransactionRequest request) throws IOException {
final WfsFactory factory = WfsFactory.eINSTANCE;
TransactionType tx = factory.createTransactionType();
tx.setService("WFS");
tx.setHandle(request.getHandle());
tx.setVersion(getVersion());
List<TransactionElement> transactionElements = request.getTransactionElements();
if (transactionElements.isEmpty()) {
requestInfo("Asked to perform transaction with no transaction elements");
return tx;
}
@SuppressWarnings("unchecked")
List<InsertElementType> inserts = tx.getInsert();
@SuppressWarnings("unchecked")
List<UpdateElementType> updates = tx.getUpdate();
@SuppressWarnings("unchecked")
List<DeleteElementType> deletes = tx.getDelete();
try {
for (TransactionElement elem : transactionElements) {
if (elem instanceof TransactionRequest.Insert) {
InsertElementType insert = createInsert(factory, (Insert) elem);
inserts.add(insert);
} else if (elem instanceof TransactionRequest.Update) {
UpdateElementType update = createUpdate(factory, (Update) elem);
updates.add(update);
} else if (elem instanceof TransactionRequest.Delete) {
DeleteElementType delete = createDelete(factory, (Delete) elem);
deletes.add(delete);
}
}
} catch (IOException e) {
throw e;
} catch (RuntimeException re) {
throw re;
} catch (Exception other) {
throw new RuntimeException(other);
}
return tx;
}
protected InsertElementType createInsert(WfsFactory factory, Insert elem) throws Exception {
InsertElementType insert = factory.createInsertElementType();
String srsName = getFeatureTypeInfo(elem.getTypeName()).getDefaultSRS();
insert.setSrsName(new URI(srsName));
List<SimpleFeature> features = elem.getFeatures();
insert.getFeature().addAll(features);
return insert;
}
protected UpdateElementType createUpdate(WfsFactory factory, Update elem) throws Exception {
List<QName> propertyNames = elem.getPropertyNames();
List<Object> newValues = elem.getNewValues();
if (propertyNames.size() != newValues.size()) {
throw new IllegalArgumentException("Got " + propertyNames.size()
+ " property names and " + newValues.size() + " values");
}
UpdateElementType update = factory.createUpdateElementType();
QName typeName = elem.getTypeName();
update.setTypeName(typeName);
String srsName = getFeatureTypeInfo(typeName).getDefaultSRS();
update.setSrsName(new URI(srsName));
Filter filter = elem.getFilter();
update.setFilter(filter);
@SuppressWarnings("unchecked")
List<PropertyType> properties = update.getProperty();
for (int i = 0; i < propertyNames.size(); i++) {
QName propName = propertyNames.get(i);
Object value = newValues.get(i);
PropertyType property = factory.createPropertyType();
property.setName(propName);
property.setValue(value);
properties.add(property);
}
return update;
}
protected DeleteElementType createDelete(WfsFactory factory, Delete elem) throws Exception {
DeleteElementType delete = factory.createDeleteElementType();
QName typeName = elem.getTypeName();
delete.setTypeName(typeName);
Filter filter = elem.getFilter();
delete.setFilter(filter);
return delete;
}
/*---------------------------------------------------------------------
* WFSStrategy methods
* ---------------------------------------------------------------------*/
@Override
public boolean supportsTransaction(QName typeName) {
try {
getFeatureTypeInfo(typeName);
} catch (IllegalArgumentException e) {
throw e;
}
if (!supportsOperation(TRANSACTION, POST)) {
return false;
}
OperationsType operations = this.capabilities.getFeatureTypeList().getOperations();
if (operations == null) {
return false;
}
@SuppressWarnings("unchecked")
List<net.opengis.wfs.OperationType> operation = operations.getOperation();
for (net.opengis.wfs.OperationType required : Arrays.asList(
net.opengis.wfs.OperationType.INSERT_LITERAL,
net.opengis.wfs.OperationType.UPDATE_LITERAL,
net.opengis.wfs.OperationType.DELETE_LITERAL)) {
if (!operation.contains(required)) {
info("Transactions not supported since WFS didn't declare support for "
+ required.getName());
return false;
}
}
return true;
}
@Override
public Configuration getFilterConfiguration() {
return Versions.v1_0_0.equals(getServiceVersion()) ? FILTER_1_0_CONFIGURATION
: FILTER_1_1_CONFIGURATION;
}
@Override
public Configuration getWfsConfiguration() {
return Versions.v1_0_0.equals(getServiceVersion()) ? WFS_1_0_CONFIGURATION
: WFS_1_1_CONFIGURATION;
}
@Override
public void setCapabilities(WFSGetCapabilities capabilities) {
WFSCapabilitiesType caps = (WFSCapabilitiesType) capabilities.getParsedCapabilities();
this.capabilities = caps;
String version = caps.getVersion();
try {
this.serviceVersion = Versions.find(version);
} catch (IllegalArgumentException e) {
LOGGER.warning("Capabilities document didn't advertise a supported version (" + version
+ "). Defaulting to " + this.serviceVersion);
}
typeInfos.clear();
FeatureTypeListType featureTypeList = this.capabilities.getFeatureTypeList();
if (featureTypeList == null || featureTypeList.getFeatureType().isEmpty()) {
Loggers.MODULE.info("WFS Server contains no FeatureTypes: "
+ getOperationURI(GET_CAPABILITIES, GET));
return;
}
@SuppressWarnings("unchecked")
List<FeatureTypeType> featureTypes = featureTypeList.getFeatureType();
for (FeatureTypeType typeInfo : featureTypes) {
FeatureTypeType transTypeInfo = translateTypeInfo(typeInfo);
QName name = transTypeInfo.getName();
typeInfos.put(name, transTypeInfo);
}
}
/**
* Any server specific translation of type information
* such as setting correct namespace
*
* @param typeInfo type info
* @return translated type info
*/
protected FeatureTypeType translateTypeInfo(FeatureTypeType typeInfo){
return typeInfo;
}
@Override
public WFSServiceInfo getServiceInfo() {
final String schemaLocation;
if (Versions.v1_1_0.equals(getServiceVersion())) {
schemaLocation = "http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd";
} else {
schemaLocation = "http://schemas.opengis.net/wfs/1.1.0/wfs.xsd";
}
URL getCapsUrl = getOperationURL(GET_CAPABILITIES, GET);
return new CapabilitiesServiceInfo(schemaLocation, getCapsUrl, capabilities);
}
@Override
public boolean supports(ResultType resultType) {
switch (resultType) {
case RESULTS:
return true;
case HITS:
return Versions.v1_0_0.equals(getServiceVersion()) ? false : true;
default:
return false;
}
}
@Override
public Version getServiceVersion() {
return this.serviceVersion;
}
/**
* @see WFSStrategy#getFeatureTypeNames()
*/
@Override
public Set<QName> getFeatureTypeNames() {
return new HashSet<QName>(typeInfos.keySet());
}
/**
* @see org.geotools.data.wfs.internal.WFSStrategy#getFeatureTypeInfo(javax.xml.namespace.QName)
*/
@Override
public FeatureTypeInfo getFeatureTypeInfo(QName typeName) {
FeatureTypeType eType = typeInfos.get(typeName);
if (null == eType) {
throw new IllegalArgumentException("Type name not found: " + typeName);
}
return new FeatureTypeInfoImpl(eType);
}
/**
* @see WFSStrategy#getFilterCapabilities()
*/
@Override
public FilterCapabilities getFilterCapabilities() {
FilterCapabilities wfsFilterCapabilities;
wfsFilterCapabilities = capabilities.getFilterCapabilities();
return wfsFilterCapabilities;
}
@SuppressWarnings("unchecked")
@Override
protected String getOperationURI(WFSOperationType operation, HttpMethod method) {
trace("Looking operation URI for ", operation, "/", method);
List<OperationType> operations = capabilities.getOperationsMetadata().getOperation();
for (OperationType op : operations) {
if (!operation.getName().equals(op.getName())) {
continue;
}
List<DCPType> dcpTypes = op.getDCP();
if (null == dcpTypes) {
continue;
}
for (DCPType d : dcpTypes) {
List<RequestMethodType> methods;
if (HttpMethod.GET.equals(method)) {
methods = d.getHTTP().getGet();
} else {
methods = d.getHTTP().getPost();
}
if (null == methods || methods.isEmpty()) {
continue;
}
String href = methods.get(0).getHref();
debug("Returning operation URI for ", operation, "/", method, ": ", href);
return href;
}
}
debug("No operation URI found for ", operation, "/", method);
return null;
}
/**
* @see WFSStrategy#getServerSupportedOutputFormats(QName, WFSOperationType)
*/
@Override
public Set<String> getServerSupportedOutputFormats(QName typeName, WFSOperationType operation) {
Set<String> ftypeFormats = new HashSet<String>();
final Set<String> serviceOutputFormats = getServerSupportedOutputFormats(operation);
ftypeFormats.addAll(serviceOutputFormats);
if (GET_FEATURE.equals(operation)) {
final FeatureTypeInfo typeInfo = getFeatureTypeInfo(typeName);
final Set<String> typeAdvertisedFormats = typeInfo.getOutputFormats();
ftypeFormats.addAll(typeAdvertisedFormats);
}
return ftypeFormats;
}
/**
* @see #getDefaultOutputFormat
*/
@Override
public Set<String> getServerSupportedOutputFormats(WFSOperationType operation) {
String parameterName;
final Version serviceVersion = getServiceVersion();
final boolean wfs1_0 = Versions.v1_0_0.equals(serviceVersion);
switch (operation) {
case GET_FEATURE:
parameterName = wfs1_0 ? "ResultFormat" : "outputFormat";
break;
case DESCRIBE_FEATURETYPE:
parameterName = wfs1_0 ? "SchemaDescriptionLanguage" : "outputFormat";
break;
case GET_FEATURE_WITH_LOCK:
parameterName = wfs1_0 ? "ResultFormat" : "outputFormat";
break;
case TRANSACTION:
if (wfs1_0) {
//TODO: not sure what to do here.
//this is a hack, there appears to be no format info in the 1.0 capabilities for transaction
operation = GET_FEATURE;
parameterName = "ResultFormat";
} else {
parameterName = "inputFormat";
}
break;
default:
throw new UnsupportedOperationException("not yet implemented for " + operation);
}
final OperationType operationMetadata = getOperationMetadata(operation);
Set<String> serverSupportedFormats;
serverSupportedFormats = findParameters(operationMetadata, parameterName);
return serverSupportedFormats;
}
/**
* @see WFSStrategy#getSupportedCRSIdentifiers
*/
@Override
public Set<String> getSupportedCRSIdentifiers(QName typeName) {
FeatureTypeInfo featureTypeInfo = getFeatureTypeInfo(typeName);
String defaultSRS = featureTypeInfo.getDefaultSRS();
List<String> otherSRS = featureTypeInfo.getOtherSRS();
Set<String> ftypeCrss = new HashSet<String>();
ftypeCrss.add(defaultSRS);
if (!config.isUseDefaultSrs()) {
ftypeCrss.addAll(otherSRS);
}
final boolean wfs1_1 = Versions.v1_1_0.equals(getServiceVersion());
if (wfs1_1) {
OperationType operationMetadata = getOperationMetadata(GET_FEATURE);
final String operationParameter = "SrsName";
Set<String> globalSrsNames = findParameters(operationMetadata, operationParameter);
ftypeCrss.addAll(globalSrsNames);
}
return ftypeCrss;
}
@SuppressWarnings("unchecked")
protected Set<String> findParameters(final OperationType operationMetadata,
final String parameterName) {
Set<String> outputFormats = new HashSet<String>();
List<DomainType> parameters = operationMetadata.getParameter();
for (DomainType param : parameters) {
String paramName = param.getName();
if (parameterName.equals(paramName)) {
List<String> value = param.getValue();
outputFormats.addAll(value);
}
}
return outputFormats;
}
@Override
public List<String> getClientSupportedOutputFormats(WFSOperationType operation) {
List<WFSResponseFactory> operationResponseFactories;
operationResponseFactories = WFSExtensions.findResponseFactories(operation);
List<String> outputFormats = new LinkedList<String>();
for (WFSResponseFactory factory : operationResponseFactories) {
List<String> factoryFormats = factory.getSupportedOutputFormats();
outputFormats.addAll(factoryFormats);
}
final boolean wfs1_0 = Versions.v1_0_0.equals(serviceVersion);
if (GET_FEATURE.equals(operation)) {
for (String preferred : wfs1_0? PREFFERRED_GETFEATURE_FORMATS_10 : PREFFERRED_GETFEATURE_FORMATS) {
boolean hasFormat = outputFormats.remove(preferred);
if (hasFormat) {
outputFormats.add(0, preferred);
break;
}
}
}
return outputFormats;
}
/**
* @return the operation metadata advertised in the capabilities for the given operation
* @see #getServerSupportedOutputFormats(WFSOperationType)
*/
protected OperationType getOperationMetadata(final WFSOperationType operation) {
final OperationsMetadataType operationsMetadata = capabilities.getOperationsMetadata();
@SuppressWarnings("unchecked")
final List<OperationType> operations = operationsMetadata.getOperation();
final String expectedOperationName = operation.getName();
for (OperationType operationType : operations) {
String operationName = operationType.getName();
if (expectedOperationName.equalsIgnoreCase(operationName)) {
return operationType;
}
}
throw new NoSuchElementException("Operation metadata not found for "
+ expectedOperationName + " in the capabilities document");
}
}
| modules/unsupported/wfs-ng/src/main/java/org/geotools/data/wfs/internal/v1_x/StrictWFS_1_x_Strategy.java | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2004-2014, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library 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
* Lesser General Public License for more details.
*/
package org.geotools.data.wfs.internal.v1_x;
import static org.geotools.data.wfs.internal.GetFeatureRequest.ResultType.RESULTS;
import static org.geotools.data.wfs.internal.HttpMethod.GET;
import static org.geotools.data.wfs.internal.HttpMethod.POST;
import static org.geotools.data.wfs.internal.Loggers.debug;
import static org.geotools.data.wfs.internal.Loggers.info;
import static org.geotools.data.wfs.internal.Loggers.requestInfo;
import static org.geotools.data.wfs.internal.Loggers.trace;
import static org.geotools.data.wfs.internal.WFSOperationType.GET_CAPABILITIES;
import static org.geotools.data.wfs.internal.WFSOperationType.GET_FEATURE;
import static org.geotools.data.wfs.internal.WFSOperationType.TRANSACTION;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.xml.namespace.QName;
import net.opengis.ows10.DCPType;
import net.opengis.ows10.DomainType;
import net.opengis.ows10.OperationType;
import net.opengis.ows10.OperationsMetadataType;
import net.opengis.ows10.RequestMethodType;
import net.opengis.wfs.DeleteElementType;
import net.opengis.wfs.DescribeFeatureTypeType;
import net.opengis.wfs.FeatureTypeListType;
import net.opengis.wfs.FeatureTypeType;
import net.opengis.wfs.GetFeatureType;
import net.opengis.wfs.InsertElementType;
import net.opengis.wfs.OperationsType;
import net.opengis.wfs.PropertyType;
import net.opengis.wfs.QueryType;
import net.opengis.wfs.ResultTypeType;
import net.opengis.wfs.TransactionType;
import net.opengis.wfs.UpdateElementType;
import net.opengis.wfs.WFSCapabilitiesType;
import net.opengis.wfs.WfsFactory;
import org.eclipse.emf.ecore.EObject;
import org.geotools.data.wfs.WFSServiceInfo;
import org.geotools.data.wfs.internal.AbstractWFSStrategy;
import org.geotools.data.wfs.internal.DescribeFeatureTypeRequest;
import org.geotools.data.wfs.internal.FeatureTypeInfo;
import org.geotools.data.wfs.internal.GetFeatureRequest;
import org.geotools.data.wfs.internal.GetFeatureRequest.ResultType;
import org.geotools.data.wfs.internal.HttpMethod;
import org.geotools.data.wfs.internal.Loggers;
import org.geotools.data.wfs.internal.TransactionRequest;
import org.geotools.data.wfs.internal.TransactionRequest.Delete;
import org.geotools.data.wfs.internal.TransactionRequest.Insert;
import org.geotools.data.wfs.internal.TransactionRequest.TransactionElement;
import org.geotools.data.wfs.internal.TransactionRequest.Update;
import org.geotools.data.wfs.internal.DescribeStoredQueriesRequest;
import org.geotools.data.wfs.internal.ListStoredQueriesRequest;
import org.geotools.data.wfs.internal.Versions;
import org.geotools.data.wfs.internal.WFSExtensions;
import org.geotools.data.wfs.internal.WFSGetCapabilities;
import org.geotools.data.wfs.internal.WFSOperationType;
import org.geotools.data.wfs.internal.WFSResponseFactory;
import org.geotools.data.wfs.internal.WFSStrategy;
import org.geotools.util.Version;
import org.geotools.wfs.v1_0.WFS;
import org.geotools.xml.Configuration;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import org.opengis.filter.capability.FilterCapabilities;
import org.opengis.filter.sort.SortBy;
/**
*
*/
public class StrictWFS_1_x_Strategy extends AbstractWFSStrategy {
private static final List<String> PREFFERRED_GETFEATURE_FORMATS = Collections
.unmodifiableList(Arrays.asList("text/xml; subtype=gml/3.1.1",
"text/xml; subtype=gml/3.1.1/profiles/gmlsf/0", "GML3"));
private static final List<String> PREFFERRED_GETFEATURE_FORMATS_10 = Collections
.unmodifiableList(Arrays.asList("GML2"));
/**
* The WFS GetCapabilities document. Final by now, as we're not handling updatesequence, so will
* not ask the server for an updated capabilities during the life-time of this datastore.
*/
protected net.opengis.wfs.WFSCapabilitiesType capabilities;
private final Map<QName, FeatureTypeType> typeInfos;
private Version serviceVersion;
public StrictWFS_1_x_Strategy() {
// default to 1.0, override at setCapabilities if needed
this(Versions.v1_0_0);
}
public StrictWFS_1_x_Strategy(Version defaultVersion) {
super();
typeInfos = new HashMap<QName, FeatureTypeType>();
serviceVersion = defaultVersion;
}
/*---------------------------------------------------------------------
* AbstractWFSStrategy methods
* ---------------------------------------------------------------------*/
@Override
protected QName getOperationName(WFSOperationType operation) {
return new QName(WFS.NAMESPACE, operation.getName());
}
/**
* @see org.geotools.data.wfs.internal.AbstractWFSStrategy#createGetFeatureRequestPost(org.geotools.data.wfs.internal.GetFeatureRequest)
*/
@SuppressWarnings("unchecked")
@Override
protected GetFeatureType createGetFeatureRequestPost(GetFeatureRequest query)
throws IOException {
final QName typeName = query.getTypeName();
final FeatureTypeInfo featureTypeInfo = getFeatureTypeInfo(typeName);
final WfsFactory factory = WfsFactory.eINSTANCE;
GetFeatureType getFeature = factory.createGetFeatureType();
getFeature.setService("WFS");
getFeature.setVersion(getVersion());
String outputFormat = query.getOutputFormat();
getFeature.setOutputFormat(outputFormat);
getFeature.setHandle(query.getHandle());
Integer maxFeatures = query.getMaxFeatures();
if (maxFeatures != null) {
getFeature.setMaxFeatures(BigInteger.valueOf(maxFeatures.intValue()));
}
ResultType resultType = query.getResultType();
getFeature.setResultType(RESULTS == resultType ? ResultTypeType.RESULTS_LITERAL
: ResultTypeType.HITS_LITERAL);
QueryType wfsQuery = factory.createQueryType();
wfsQuery.setTypeName(Collections.singletonList(typeName));
final Filter supportedFilter;
final Filter unsupportedFilter;
{
final Filter filter = query.getFilter();
Filter[] splitFilters = splitFilters(typeName, filter);
supportedFilter = splitFilters[0];
unsupportedFilter = splitFilters[1];
}
query.setUnsupportedFilter(unsupportedFilter);
if (!Filter.INCLUDE.equals(supportedFilter)) {
wfsQuery.setFilter(supportedFilter);
}
String srsName = query.getSrsName();
if (null == srsName) {
srsName = featureTypeInfo.getDefaultSRS();
}
try {
wfsQuery.setSrsName(new URI(srsName));
} catch (URISyntaxException e) {
throw new RuntimeException("Can't create a URI from the query CRS: " + srsName, e);
}
String[] propertyNames = query.getPropertyNames();
boolean retrieveAllProperties = propertyNames == null;
if (!retrieveAllProperties) {
List<String> propertyName = wfsQuery.getPropertyName();
for (String propName : propertyNames) {
propertyName.add(propName);
}
}
SortBy[] sortByList = query.getSortBy();
if (sortByList != null) {
for (SortBy sortBy : sortByList) {
wfsQuery.getSortBy().add(sortBy);
}
}
getFeature.getQuery().add(wfsQuery);
return getFeature;
}
@Override
protected DescribeFeatureTypeType createDescribeFeatureTypeRequestPost(
DescribeFeatureTypeRequest request) {
final WfsFactory factory = WfsFactory.eINSTANCE;
DescribeFeatureTypeType dft = factory.createDescribeFeatureTypeType();
Version version = getServiceVersion();
dft.setService("WFS");
dft.setVersion(version.toString());
dft.setHandle(request.getHandle());
if (Versions.v1_0_0.equals(version)) {
dft.setOutputFormat(null);
}
QName typeName = request.getTypeName();
@SuppressWarnings("unchecked")
List<QName> typeNames = dft.getTypeName();
typeNames.add(typeName);
return dft;
}
@Override
protected EObject createListStoredQueriesRequestPost(
ListStoredQueriesRequest request) throws IOException {
// Not implemented in 1.0.0 or 1.1.0, this method should never be entered
throw new UnsupportedOperationException("WFS 1.0.0 / 1.1.0 does not support Stored Queries!");
}
@Override
protected EObject createDescribeStoredQueriesRequestPost(
DescribeStoredQueriesRequest request) throws IOException {
// Not implemented in 1.0.0 or 1.1.0, this method should never be entered
throw new UnsupportedOperationException("WFS 1.0.0 / 1.1.0 does not support Stored Queries!");
}
@Override
protected EObject createTransactionRequest(TransactionRequest request) throws IOException {
final WfsFactory factory = WfsFactory.eINSTANCE;
TransactionType tx = factory.createTransactionType();
tx.setService("WFS");
tx.setHandle(request.getHandle());
tx.setVersion(getVersion());
List<TransactionElement> transactionElements = request.getTransactionElements();
if (transactionElements.isEmpty()) {
requestInfo("Asked to perform transaction with no transaction elements");
return tx;
}
@SuppressWarnings("unchecked")
List<InsertElementType> inserts = tx.getInsert();
@SuppressWarnings("unchecked")
List<UpdateElementType> updates = tx.getUpdate();
@SuppressWarnings("unchecked")
List<DeleteElementType> deletes = tx.getDelete();
try {
for (TransactionElement elem : transactionElements) {
if (elem instanceof TransactionRequest.Insert) {
InsertElementType insert = createInsert(factory, (Insert) elem);
inserts.add(insert);
} else if (elem instanceof TransactionRequest.Update) {
UpdateElementType update = createUpdate(factory, (Update) elem);
updates.add(update);
} else if (elem instanceof TransactionRequest.Delete) {
DeleteElementType delete = createDelete(factory, (Delete) elem);
deletes.add(delete);
}
}
} catch (IOException e) {
throw e;
} catch (RuntimeException re) {
throw re;
} catch (Exception other) {
throw new RuntimeException(other);
}
return tx;
}
protected InsertElementType createInsert(WfsFactory factory, Insert elem) throws Exception {
InsertElementType insert = factory.createInsertElementType();
String srsName = getFeatureTypeInfo(elem.getTypeName()).getDefaultSRS();
insert.setSrsName(new URI(srsName));
List<SimpleFeature> features = elem.getFeatures();
insert.getFeature().addAll(features);
return insert;
}
protected UpdateElementType createUpdate(WfsFactory factory, Update elem) throws Exception {
List<QName> propertyNames = elem.getPropertyNames();
List<Object> newValues = elem.getNewValues();
if (propertyNames.size() != newValues.size()) {
throw new IllegalArgumentException("Got " + propertyNames.size()
+ " property names and " + newValues.size() + " values");
}
UpdateElementType update = factory.createUpdateElementType();
QName typeName = elem.getTypeName();
update.setTypeName(typeName);
String srsName = getFeatureTypeInfo(typeName).getDefaultSRS();
update.setSrsName(new URI(srsName));
Filter filter = elem.getFilter();
update.setFilter(filter);
@SuppressWarnings("unchecked")
List<PropertyType> properties = update.getProperty();
for (int i = 0; i < propertyNames.size(); i++) {
QName propName = propertyNames.get(i);
Object value = newValues.get(i);
PropertyType property = factory.createPropertyType();
property.setName(propName);
property.setValue(value);
properties.add(property);
}
return update;
}
protected DeleteElementType createDelete(WfsFactory factory, Delete elem) throws Exception {
DeleteElementType delete = factory.createDeleteElementType();
QName typeName = elem.getTypeName();
delete.setTypeName(typeName);
Filter filter = elem.getFilter();
delete.setFilter(filter);
return delete;
}
/*---------------------------------------------------------------------
* WFSStrategy methods
* ---------------------------------------------------------------------*/
@Override
public boolean supportsTransaction(QName typeName) {
try {
getFeatureTypeInfo(typeName);
} catch (IllegalArgumentException e) {
throw e;
}
if (!supportsOperation(TRANSACTION, POST)) {
return false;
}
OperationsType operations = this.capabilities.getFeatureTypeList().getOperations();
if (operations == null) {
return false;
}
@SuppressWarnings("unchecked")
List<net.opengis.wfs.OperationType> operation = operations.getOperation();
for (net.opengis.wfs.OperationType required : Arrays.asList(
net.opengis.wfs.OperationType.INSERT_LITERAL,
net.opengis.wfs.OperationType.UPDATE_LITERAL,
net.opengis.wfs.OperationType.DELETE_LITERAL)) {
if (!operation.contains(required)) {
info("Transactions not supported since WFS didn't declare support for "
+ required.getName());
return false;
}
}
return true;
}
@Override
public Configuration getFilterConfiguration() {
return Versions.v1_0_0.equals(getServiceVersion()) ? FILTER_1_0_CONFIGURATION
: FILTER_1_1_CONFIGURATION;
}
@Override
public Configuration getWfsConfiguration() {
return Versions.v1_0_0.equals(getServiceVersion()) ? WFS_1_0_CONFIGURATION
: WFS_1_1_CONFIGURATION;
}
@Override
public void setCapabilities(WFSGetCapabilities capabilities) {
WFSCapabilitiesType caps = (WFSCapabilitiesType) capabilities.getParsedCapabilities();
this.capabilities = caps;
String version = caps.getVersion();
try {
this.serviceVersion = Versions.find(version);
} catch (IllegalArgumentException e) {
LOGGER.warning("Capabilities document didn't advertise a supported version (" + version
+ "). Defaulting to " + this.serviceVersion);
}
typeInfos.clear();
FeatureTypeListType featureTypeList = this.capabilities.getFeatureTypeList();
if (featureTypeList == null || featureTypeList.getFeatureType().isEmpty()) {
Loggers.MODULE.info("WFS Server contains no FeatureTypes: "
+ getOperationURI(GET_CAPABILITIES, GET));
return;
}
@SuppressWarnings("unchecked")
List<FeatureTypeType> featureTypes = featureTypeList.getFeatureType();
for (FeatureTypeType typeInfo : featureTypes) {
FeatureTypeType transTypeInfo = translateTypeInfo(typeInfo);
QName name = transTypeInfo.getName();
typeInfos.put(name, transTypeInfo);
}
}
/**
* Any server specific translation of type information
* such as setting correct namespace
*
* @param typeInfo type info
* @return translated type info
*/
protected FeatureTypeType translateTypeInfo(FeatureTypeType typeInfo){
return typeInfo;
}
@Override
public WFSServiceInfo getServiceInfo() {
final String schemaLocation;
if (Versions.v1_1_0.equals(getServiceVersion())) {
schemaLocation = "http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd";
} else {
schemaLocation = "http://schemas.opengis.net/wfs/1.1.0/wfs.xsd";
}
URL getCapsUrl = getOperationURL(GET_CAPABILITIES, GET);
return new CapabilitiesServiceInfo(schemaLocation, getCapsUrl, capabilities);
}
@Override
public boolean supports(ResultType resultType) {
switch (resultType) {
case RESULTS:
return true;
case HITS:
return Versions.v1_0_0.equals(getServiceVersion()) ? false : true;
default:
return false;
}
}
@Override
public Version getServiceVersion() {
return this.serviceVersion;
}
/**
* @see WFSStrategy#getFeatureTypeNames()
*/
@Override
public Set<QName> getFeatureTypeNames() {
return new HashSet<QName>(typeInfos.keySet());
}
/**
* @see org.geotools.data.wfs.internal.WFSStrategy#getFeatureTypeInfo(javax.xml.namespace.QName)
*/
@Override
public FeatureTypeInfo getFeatureTypeInfo(QName typeName) {
FeatureTypeType eType = typeInfos.get(typeName);
if (null == eType) {
throw new IllegalArgumentException("Type name not found: " + typeName);
}
return new FeatureTypeInfoImpl(eType);
}
/**
* @see WFSStrategy#getFilterCapabilities()
*/
@Override
public FilterCapabilities getFilterCapabilities() {
FilterCapabilities wfsFilterCapabilities;
wfsFilterCapabilities = capabilities.getFilterCapabilities();
return wfsFilterCapabilities;
}
@SuppressWarnings("unchecked")
@Override
protected String getOperationURI(WFSOperationType operation, HttpMethod method) {
trace("Looking operation URI for ", operation, "/", method);
List<OperationType> operations = capabilities.getOperationsMetadata().getOperation();
for (OperationType op : operations) {
if (!operation.getName().equals(op.getName())) {
continue;
}
List<DCPType> dcpTypes = op.getDCP();
if (null == dcpTypes) {
continue;
}
for (DCPType d : dcpTypes) {
List<RequestMethodType> methods;
if (HttpMethod.GET.equals(method)) {
methods = d.getHTTP().getGet();
} else {
methods = d.getHTTP().getPost();
}
if (null == methods || methods.isEmpty()) {
continue;
}
String href = methods.get(0).getHref();
debug("Returning operation URI for ", operation, "/", method, ": ", href);
return href;
}
}
debug("No operation URI found for ", operation, "/", method);
return null;
}
/**
* @see WFSStrategy#getServerSupportedOutputFormats(QName, WFSOperationType)
*/
@Override
public Set<String> getServerSupportedOutputFormats(QName typeName, WFSOperationType operation) {
Set<String> ftypeFormats = new HashSet<String>();
final Set<String> serviceOutputFormats = getServerSupportedOutputFormats(operation);
ftypeFormats.addAll(serviceOutputFormats);
if (GET_FEATURE.equals(operation)) {
final FeatureTypeInfo typeInfo = getFeatureTypeInfo(typeName);
final Set<String> typeAdvertisedFormats = typeInfo.getOutputFormats();
ftypeFormats.addAll(typeAdvertisedFormats);
}
return ftypeFormats;
}
/**
* @see #getDefaultOutputFormat
*/
@Override
public Set<String> getServerSupportedOutputFormats(WFSOperationType operation) {
String parameterName;
final Version serviceVersion = getServiceVersion();
final boolean wfs1_0 = Versions.v1_0_0.equals(serviceVersion);
switch (operation) {
case GET_FEATURE:
parameterName = wfs1_0 ? "ResultFormat" : "outputFormat";
break;
case DESCRIBE_FEATURETYPE:
parameterName = wfs1_0 ? "SchemaDescriptionLanguage" : "outputFormat";
break;
case GET_FEATURE_WITH_LOCK:
parameterName = wfs1_0 ? "ResultFormat" : "outputFormat";
break;
case TRANSACTION:
if (wfs1_0) {
//TODO: not sure what to do here.
//this is a hack, there appears to be no format info in the 1.0 capabilities for transaction
operation = GET_FEATURE;
parameterName = "ResultFormat";
} else {
parameterName = "inputFormat";
}
break;
default:
throw new UnsupportedOperationException("not yet implemented for " + operation);
}
final OperationType operationMetadata = getOperationMetadata(operation);
Set<String> serverSupportedFormats;
serverSupportedFormats = findParameters(operationMetadata, parameterName);
return serverSupportedFormats;
}
/**
* @see WFSStrategy#getSupportedCRSIdentifiers
*/
@Override
public Set<String> getSupportedCRSIdentifiers(QName typeName) {
FeatureTypeInfo featureTypeInfo = getFeatureTypeInfo(typeName);
String defaultSRS = featureTypeInfo.getDefaultSRS();
List<String> otherSRS = featureTypeInfo.getOtherSRS();
Set<String> ftypeCrss = new HashSet<String>();
ftypeCrss.add(defaultSRS);
if (!config.isUseDefaultSrs()) {
ftypeCrss.addAll(otherSRS);
}
final boolean wfs1_1 = Versions.v1_1_0.equals(getServiceVersion());
if (wfs1_1) {
OperationType operationMetadata = getOperationMetadata(GET_FEATURE);
final String operationParameter = "SrsName";
Set<String> globalSrsNames = findParameters(operationMetadata, operationParameter);
ftypeCrss.addAll(globalSrsNames);
}
return ftypeCrss;
}
@SuppressWarnings("unchecked")
protected Set<String> findParameters(final OperationType operationMetadata,
final String parameterName) {
Set<String> outputFormats = new HashSet<String>();
List<DomainType> parameters = operationMetadata.getParameter();
for (DomainType param : parameters) {
String paramName = param.getName();
if (parameterName.equals(paramName)) {
List<String> value = param.getValue();
outputFormats.addAll(value);
}
}
return outputFormats;
}
@Override
public List<String> getClientSupportedOutputFormats(WFSOperationType operation) {
List<WFSResponseFactory> operationResponseFactories;
operationResponseFactories = WFSExtensions.findResponseFactories(operation);
List<String> outputFormats = new LinkedList<String>();
for (WFSResponseFactory factory : operationResponseFactories) {
List<String> factoryFormats = factory.getSupportedOutputFormats();
outputFormats.addAll(factoryFormats);
}
final boolean wfs1_0 = Versions.v1_0_0.equals(serviceVersion);
if (GET_FEATURE.equals(operation)) {
for (String preferred : wfs1_0? PREFFERRED_GETFEATURE_FORMATS_10 : PREFFERRED_GETFEATURE_FORMATS) {
boolean hasFormat = outputFormats.remove(preferred);
if (hasFormat) {
outputFormats.add(0, preferred);
break;
}
}
}
return outputFormats;
}
/**
* @return the operation metadata advertised in the capabilities for the given operation
* @see #getServerSupportedOutputFormats(WFSOperationType)
*/
protected OperationType getOperationMetadata(final WFSOperationType operation) {
final OperationsMetadataType operationsMetadata = capabilities.getOperationsMetadata();
@SuppressWarnings("unchecked")
final List<OperationType> operations = operationsMetadata.getOperation();
final String expectedOperationName = operation.getName();
for (OperationType operationType : operations) {
String operationName = operationType.getName();
if (expectedOperationName.equalsIgnoreCase(operationName)) {
return operationType;
}
}
throw new NoSuchElementException("Operation metadata not found for "
+ expectedOperationName + " in the capabilities document");
}
}
| spaces | modules/unsupported/wfs-ng/src/main/java/org/geotools/data/wfs/internal/v1_x/StrictWFS_1_x_Strategy.java | spaces |
|
Java | apache-2.0 | 015f45e2fdd2e0281e0bb8ca6a17a828f6c4d15f | 0 | Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.util;
import java.io.File;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import org.apache.commons.math.exception.MathInternalError;
/**
* Utility class for saving and loading tabulated data used by
* {@link FastMath}.
*
* @version $Id$
*/
class FastMathResources {
/**
* Resource directory. Assuming that this class and the resource files
* are located in the same package as "FastMath".
*/
private static final String RES_DIR = "data/" +
FastMath.class.getPackage().getName().replace('.', '/') + "/";
/** File resource prefix. */
private static final String RES_PREFIX = RES_DIR + "FastMath__";
/** Resource basename for "EXP_INT_TABLE_A" and "EXP_INT_TABLE_B". */
private static final String EXP_INT = "exp_int";
/** Resource basename for "EXP_FRAC_TABLE_A" and "EXP_FRAC_TABLE_B". */
private static final String EXP_FRAC = "exp_frac";
/** Resource basename for "LN_MANT". */
private static final String LN_MANT = "ln_mant";
/** Number of bytes in a "double". */
private static final int BYTES_IN_DOUBLE = Double.SIZE / Byte.SIZE;
/**
* Class contains only static methods.
*/
private FastMathResources() {}
/**
* Compute and save all the resources.
*/
static void createAll() {
// Create resource directory.
final File resDir = new File(RES_DIR);
if (resDir.exists()) {
if (!resDir.isDirectory()) {
throw new MathInternalError();
}
} else {
try {
resDir.mkdirs();
} catch (SecurityException e) {
throw new MathInternalError(e);
}
}
// "EXP_INT" tables.
final double[] expIntA = new double[FastMath.EXP_INT_TABLE_LEN];
final double[] expIntB = new double[FastMath.EXP_INT_TABLE_LEN];
final double tmp[] = new double[2];
final double recip[] = new double[2];
for (int i = 0; i < FastMath.EXP_INT_TABLE_MAX_INDEX; i++) {
FastMathCalc.expint(i, tmp);
expIntA[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0];
expIntB[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1];
if (i != 0) {
// Negative integer powers.
FastMathCalc.splitReciprocal(tmp, recip);
expIntA[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
expIntB[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
}
}
saveTable2d(EXP_INT, new double[][] { expIntA, expIntB });
// "EXP_FRAC" tables.
final double[] expFracA = new double[FastMath.EXP_FRAC_TABLE_LEN];
final double[] expFracB = new double[FastMath.EXP_FRAC_TABLE_LEN];
for (int i = 0; i < FastMath.EXP_FRAC_TABLE_LEN; i++) {
FastMathCalc.slowexp(i / 1024d, tmp); // TWO_POWER_10
expFracA[i] = tmp[0];
expFracB[i] = tmp[1];
}
saveTable2d(EXP_FRAC, new double[][] { expFracA, expFracB });
// "LN_MANT" table.
final double[][] lnMant = new double[FastMath.LN_MANT_LEN][];
for (int i = 0; i < FastMath.LN_MANT_LEN; i++) {
final double d = Double.longBitsToDouble((((long) i) << 42) |
0x3ff0000000000000L);
lnMant[i] = FastMathCalc.slowLog(d);
}
saveTable2d(LN_MANT, transpose(lnMant));
}
/**
* Load "EXP_INT" tables.
* "EXP_INT_TABLE_A" is at index 0.
* "EXP_INT_TABLE_B" is at index 1.
*
* @return the retrieved data.
*/
static double[][] loadExpInt() {
return loadTable2d(EXP_INT, 2, FastMath.EXP_INT_TABLE_LEN);
}
/**
* Load "EXP_FRAC" tables.
* "EXP_FRAC_TABLE_A" is at index 0.
* "EXP_FRAC_TABLE_B" is at index 1.
*
* @return the retrieved data.
*/
static double[][] loadExpFrac() {
return loadTable2d(EXP_FRAC, 2, FastMath.EXP_FRAC_TABLE_LEN);
}
/**
* Load "LN_MANT".
*
* @return the retrieved data.
*/
static double[][] loadLnMant() {
return transpose(loadTable2d(LN_MANT, 2, FastMath.LN_MANT_LEN));
}
/**
* @param name Basename of the resource.
* @return an output stream.
* @throws FileNotFoundException if the file cannot be opened.
*/
private static DataOutputStream out(String name)
throws FileNotFoundException {
final String fullName = RES_PREFIX + name;
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fullName)));
}
/**
* @param name Basename of the resource.
* @param data Data to be stored.
*/
private static void saveTable1d(String name,
double[] data) {
final int len = data.length;
try {
final DataOutputStream out = out(name);
for (int i = 0; i < len; i++) {
out.writeDouble(data[i]);
}
out.close();
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @param data Data to be stored.
*/
private static void saveTable2d(String name,
double[][] data) {
final int len = data.length;
final int rowLen = data[0].length;
try {
final DataOutputStream out = out(name);
for (int i = 0; i < len; i++) {
for (int j = 0; j < rowLen; j++) {
out.writeDouble(data[i][j]);
}
}
out.close();
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @return an input stream.
* @throws FileNotFoundException if the resource cannot be accessed.
*/
private static DataInputStream in(String name)
throws FileNotFoundException {
final String fullName = "/" + RES_PREFIX + name;
final InputStream in = FastMathResources.class.getResourceAsStream(fullName);
return new DataInputStream(new BufferedInputStream(in));
}
/**
* @param name Basename of the resource.
* @param len Size of the data.
* @return the retrieved data.
*/
private static double[] loadTable1d(String name,
int len) {
try {
final DataInputStream in = in(name);
final double[] data = new double[len];
for (int i = 0; i < len; i++) {
data[i] = in.readDouble();
}
in.close();
return data;
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @param len Size of the table.
* @param rowLen Size of each row of the table.
* @return the retrieved data.
*/
private static double[][] loadTable2d(String name,
int len,
int rowLen) {
try {
final DataInputStream in = in(name);
final byte[] b = new byte[BYTES_IN_DOUBLE * rowLen];
final double[][] data = new double[len][rowLen];
final ByteBuffer bBuf = ByteBuffer.wrap(b);
for (int i = 0; i < len; i++) {
in.readFully(b);
final DoubleBuffer dBuf = bBuf.asDoubleBuffer();
for (int j = 0; j < rowLen; j++) {
data[i][j] = dBuf.get();
}
}
in.close();
return data;
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* Transposes a two-dimensional array: The number of rows becomes the
* number of columns and vice-versa.
* The array must be rectangular (same number of colums in each row).
*
* @param data Array to be transposed.
* @return the transposed array.
*/
private static double[][] transpose(double[][] data) {
final int rowLen = data.length;
final int len = data[0].length;
final double[][] tData = new double[len][rowLen];
for (int i = 0; i < len; i++) {
for (int j = 0; j < rowLen; j++) {
tData[i][j] = data[j][i];
}
}
return tData;
}
}
| src/main/java/org/apache/commons/math/util/FastMathResources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.util;
import java.io.File;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import org.apache.commons.math.exception.MathInternalError;
/**
* Utility class for saving and loading tabulated data used by
* {@link FastMath}.
*
* @version $Id$
*/
class FastMathResources {
/**
* Resource directory. Assuming that this class and the resource files
* are located in the same package as "FastMath".
*/
private static final String RES_DIR = "data/" +
FastMath.class.getPackage().getName().replace('.', '/') + "/";
/** File resource prefix. */
private static final String RES_PREFIX = RES_DIR + "FastMath__";
/** Resource basename for "EXP_INT_TABLE_A" and "EXP_INT_TABLE_B". */
private static final String EXP_INT = "exp_int";
/** Resource basename for "EXP_FRAC_TABLE_A" and "EXP_FRAC_TABLE_B". */
private static final String EXP_FRAC = "exp_frac";
/** Resource basename for "LN_MANT". */
private static final String LN_MANT = "ln_mant";
/** Number of bytes in a "double". */
private static final int BYTES_IN_DOUBLE = Double.SIZE / Byte.SIZE;
/**
* Class contains only static methods.
*/
private FastMathResources() {}
/**
* Compute and save all the resources.
*/
static void createAll() {
// Create resource directory.
final File resDir = new File(RES_DIR);
if (resDir.exists()) {
if (!resDir.isDirectory()) {
throw new MathInternalError();
}
} else {
try {
resDir.mkdirs();
} catch (SecurityException e) {
throw new MathInternalError(e);
}
}
// "EXP_INT" tables.
final double[] expIntA = new double[FastMath.EXP_INT_TABLE_LEN];
final double[] expIntB = new double[FastMath.EXP_INT_TABLE_LEN];
final double tmp[] = new double[2];
final double recip[] = new double[2];
for (int i = 0; i < FastMath.EXP_INT_TABLE_MAX_INDEX; i++) {
FastMathCalc.expint(i, tmp);
expIntA[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[0];
expIntB[i + FastMath.EXP_INT_TABLE_MAX_INDEX] = tmp[1];
if (i != 0) {
// Negative integer powers.
FastMathCalc.splitReciprocal(tmp, recip);
expIntA[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[0];
expIntB[FastMath.EXP_INT_TABLE_MAX_INDEX - i] = recip[1];
}
}
saveTable2d(EXP_INT, new double[][] { expIntA, expIntB });
// "EXP_FRAC" tables.
final double[] expFracA = new double[FastMath.EXP_FRAC_TABLE_LEN];
final double[] expFracB = new double[FastMath.EXP_FRAC_TABLE_LEN];
for (int i = 0; i < FastMath.EXP_FRAC_TABLE_LEN; i++) {
FastMathCalc.slowexp(i / 1024d, tmp); // TWO_POWER_10
expFracA[i] = tmp[0];
expFracB[i] = tmp[1];
}
saveTable2d(EXP_FRAC, new double[][] { expFracA, expFracB });
// "LN_MANT" table.
final double[][] lnMant = new double[FastMath.LN_MANT_LEN][];
for (int i = 0; i < FastMath.LN_MANT_LEN; i++) {
final double d = Double.longBitsToDouble((((long) i) << 42) |
0x3ff0000000000000L);
lnMant[i] = FastMathCalc.slowLog(d);
}
saveTable2d(LN_MANT, transpose(lnMant));
}
/**
* Load "EXP_INT" tables.
* "EXP_INT_TABLE_A" is at index 0.
* "EXP_INT_TABLE_B" is at index 1.
*
* @return the retrieved data.
*/
public static double[][] loadExpInt() {
return loadTable2d(EXP_INT, 2, FastMath.EXP_INT_TABLE_LEN);
}
/**
* Load "EXP_FRAC" tables.
* "EXP_FRAC_TABLE_A" is at index 0.
* "EXP_FRAC_TABLE_B" is at index 1.
*
* @return the retrieved data.
*/
public static double[][] loadExpFrac() {
return loadTable2d(EXP_FRAC, 2, FastMath.EXP_FRAC_TABLE_LEN);
}
/**
* Load "LN_MANT".
*
* @return the retrieved data.
*/
public static double[][] loadLnMant() {
return transpose(loadTable2d(LN_MANT, 2, FastMath.LN_MANT_LEN));
}
/**
* @param name Basename of the resource.
* @return an output stream.
* @throws FileNotFoundException if the file cannot be opened.
*/
private static DataOutputStream out(String name)
throws FileNotFoundException {
final String fullName = RES_PREFIX + name;
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fullName)));
}
/**
* @param name Basename of the resource.
* @param data Data to be stored.
*/
private static void saveTable1d(String name,
double[] data) {
final int len = data.length;
try {
final DataOutputStream out = out(name);
for (int i = 0; i < len; i++) {
out.writeDouble(data[i]);
}
out.close();
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @param data Data to be stored.
*/
private static void saveTable2d(String name,
double[][] data) {
final int len = data.length;
final int rowLen = data[0].length;
try {
final DataOutputStream out = out(name);
for (int i = 0; i < len; i++) {
for (int j = 0; j < rowLen; j++) {
out.writeDouble(data[i][j]);
}
}
out.close();
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @return an input stream.
* @throws FileNotFoundException if the resource cannot be accessed.
*/
private static DataInputStream in(String name)
throws FileNotFoundException {
final String fullName = "/" + RES_PREFIX + name;
final InputStream in = FastMathResources.class.getResourceAsStream(fullName);
return new DataInputStream(new BufferedInputStream(in));
}
/**
* @param name Basename of the resource.
* @param len Size of the data.
* @return the retrieved data.
*/
private static double[] loadTable1d(String name,
int len) {
try {
final DataInputStream in = in(name);
final double[] data = new double[len];
for (int i = 0; i < len; i++) {
data[i] = in.readDouble();
}
in.close();
return data;
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* @param name Basename of the resource.
* @param len Size of the table.
* @param rowLen Size of each row of the table.
* @return the retrieved data.
*/
private static double[][] loadTable2d(String name,
int len,
int rowLen) {
try {
final DataInputStream in = in(name);
final byte[] b = new byte[BYTES_IN_DOUBLE * rowLen];
final double[][] data = new double[len][rowLen];
final ByteBuffer bBuf = ByteBuffer.wrap(b);
for (int i = 0; i < len; i++) {
in.readFully(b);
final DoubleBuffer dBuf = bBuf.asDoubleBuffer();
for (int j = 0; j < rowLen; j++) {
data[i][j] = dBuf.get();
}
}
in.close();
return data;
} catch (IOException e) {
throw new MathInternalError(e);
}
}
/**
* Transposes a two-dimensional array: The number of rows becomes the
* number of columns and vice-versa.
* The array must be rectangular (same number of colums in each row).
*
* @param data Array to be transposed.
* @return the transposed array.
*/
private static double[][] transpose(double[][] data) {
final int rowLen = data.length;
final int len = data[0].length;
final double[][] tData = new double[len][rowLen];
for (int i = 0; i < len; i++) {
for (int j = 0; j < rowLen; j++) {
tData[i][j] = data[j][i];
}
}
return tData;
}
}
| Lowered access level.
git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@1181245 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/math/util/FastMathResources.java | Lowered access level. |
|
Java | apache-2.0 | 66219513d6795cf62519c6a4e3fc1a1735c68b02 | 0 | OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine | package org.ovirt.engine.core.dao.network;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.BaseDAOTestCase;
import org.ovirt.engine.core.dao.FixturesTool;
public class NetworkDaoTest extends BaseDAOTestCase {
private NetworkDao dao;
private Guid cluster;
private Guid datacenter;
private Network new_net;
private static final String EXISTING_NETWORK_NAME = "engine";
private static final int NUM_OF_NETWORKS = 5;
@Override
public void setUp() throws Exception {
super.setUp();
dao = dbFacade.getNetworkDao();
cluster = new Guid("b399944a-81ab-4ec5-8266-e19ba7c3c9d1");
datacenter = new Guid("6d849ebf-755f-4552-ad09-9a090cda105d");
new_net = new Network();
new_net.setName("newnet1");
new_net.setDescription("New network");
new_net.setDataCenterId(datacenter);
}
/**
* Ensures that a null network is returned.
*/
@Test
public void testGetByNameWithInvalidName() {
Network result = dao.getByName("farkle");
assertNull(result);
}
/**
* Ensures that retrieving a network by name works as expected.
*/
@Test
public void testGetByName() {
Network result = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that retrieving a network by name and data center works as expected.
*/
@Test
public void testGetByNameAndDataCenter() {
Network result = dao.getByNameAndDataCenter(EXISTING_NETWORK_NAME, datacenter);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that retrieving a network by name and cluster works as expected.
*/
@Test
public void testGetByNameAndCluster() {
Network result = dao.getByNameAndCluster(EXISTING_NETWORK_NAME, cluster);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that all networks are returned.
*/
@Test
public void testGetAll() {
List<Network> result = dao.getAll();
assertNotNull(result);
assertEquals(NUM_OF_NETWORKS, result.size());
}
/**
* Ensures that all networks are returned for a specific user when filter is on.
*/
@Test
public void testFilteredGetAll() {
List<Network> result = dao.getAll(PRIVILEGED_USER_ID, true);
assertNotNull(result);
assertFalse(result.isEmpty());
}
/**
* Ensures that no networks is returned for a specific user when filter is on.
*/
@Test
public void testFilteredGetAllWithNoPermissions() {
List<Network> result = dao.getAll(UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that all networks are returned for a unprivileged user when filter is off.
*/
@Test
public void testUnfilteredGetAllWithNoPermissions() {
List<Network> result = dao.getAll(UNPRIVILEGED_USER_ID, false);
assertNotNull(result);
assertFalse(result.isEmpty());
}
/**
* Ensures that an empty collection is returned when the specified cluster has no networks.
*/
@Test
public void testGetAllForClusterWithInvalidCluster() {
List<Network> result = dao.getAllForCluster(Guid.newGuid());
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures the right set of networks are returned for the given cluster.
*/
@Test
public void testGetAllForCluster() {
List<Network> result = dao.getAllForCluster(cluster);
assertGetAllForClusterResult(result);
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a privileged user
*/
@Test
public void testGetAllForClusterFilteredWithPermissions() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, PRIVILEGED_USER_ID, true);
assertGetAllForClusterResult(result);
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a unprivileged user and with filtering enabled
*/
@Test
public void testGetAllForClusterFilteredWithPermissionsNoPermissions() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a unprivileged user, but with no filtering
*/
@Test
public void testGetAllForClusterFilteredWithPermissionsNoPermissionsAndNoFilter() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, UNPRIVILEGED_USER_ID, false);
assertGetAllForClusterResult(result);
}
/**
* Asserts the result of {@link NetworkDao#getAllForCluster(Guid)} contains all the required networks
* @param result
*/
private static void assertGetAllForClusterResult(List<Network> result) {
assertNotNull(result);
assertFalse(result.isEmpty());
assertIsSorted(result);
}
private static void assertIsSorted(List<Network> result) {
Network previous = null;
for (Network network : result) {
if (previous != null && network.getName().compareTo(previous.getName()) < 0) {
fail(String.format("List of networks is not ordered by network name, %s came before %s.",
previous.getName(),
network.getName()));
}
previous = network;
}
}
/**
* Ensures that an empty collection is returned when the data center has no networks.
*/
@Test
public void testGetAllForDataCenterWithInvalidDataCenter() {
List<Network> result = dao.getAllForDataCenter(Guid.newGuid());
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that the right set of networks are returned for the given data center.
*/
@Test
public void testGetAllForDataCenter() {
List<Network> result = dao.getAllForDataCenter(datacenter);
verifyDataCenterNetworks(result);
}
/**
* Ensures that the right set of networks are returned for the given data center for a specific user according to
* the filter.
*/
@Test
public void testFilteredGetAllForDataCenter() {
List<Network> result = dao.getAllForDataCenter(datacenter, PRIVILEGED_USER_ID, true);
verifyDataCenterNetworks(result);
}
/**
* Ensures that the no network is returned for the given data center for a user with no permissions on network
* entities
*/
@Test
public void testFilteredGetAllForDataCenterWithNoPermissions() {
List<Network> result = dao.getAllForDataCenter(datacenter, UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that the all networks are returned for the given data center for a specific user when the filter is off.
*/
@Test
public void testUnFilteredGetAllForDataCenterWithNoPermissions() {
List<Network> result = dao.getAllForDataCenter(datacenter, PRIVILEGED_USER_ID, false);
verifyDataCenterNetworks(result);
}
private void verifyDataCenterNetworks(List<Network> result) {
assertNotNull(result);
assertFalse(result.isEmpty());
for (Network net : result) {
assertEquals(datacenter, net.getDataCenterId());
}
}
/**
* Ensures the right set of networks are returned for the given provider.
*/
@Test
public void testGetAllForProvider() {
List<Network> result = dao.getAllForProvider(FixturesTool.PROVIDER_ID);
assertNotNull(result);
assertFalse(result.isEmpty());
for (Network network : result) {
assertEquals(FixturesTool.PROVIDER_ID, network.getProvidedBy().getProviderId());
}
}
/**
* Ensures that saving a network works as expected.
*/
@Test
public void testSave() {
List<NetworkCluster> clustersFromDB = dbFacade.getNetworkClusterDao().getAllForCluster(cluster);
NetworkCluster clusterFromDB = clustersFromDB.get(0);
assertNotNull(clusterFromDB);
new_net.setCluster(clusterFromDB);
new_net.setId(Guid.newGuid());
dao.save(new_net);
Network result = dao.getByName(new_net.getName());
assertNotNull(result);
assertEquals(new_net, result);
}
/**
* Ensures updating a network works as expected.
*/
@Test
public void testUpdate() {
Network before = dao.getByName(EXISTING_NETWORK_NAME);
before.setDescription("This is a completely changed description");
dao.update(before);
Network after = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(after);
assertEquals(before, after);
}
/**
* Ensures that removing a network works as expected.
*/
@Test
public void testRemove() {
Network result = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(result);
dao.remove(result.getId());
result = dao.getByName(EXISTING_NETWORK_NAME);
assertNull(result);
}
}
| backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/network/NetworkDaoTest.java | package org.ovirt.engine.core.dao.network;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.NetworkCluster;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.BaseDAOTestCase;
import org.ovirt.engine.core.dao.FixturesTool;
public class NetworkDaoTest extends BaseDAOTestCase {
private NetworkDao dao;
private Guid cluster;
private Guid datacenter;
private Network new_net;
private static final String EXISTING_NETWORK_NAME = "engine";
private static final int NUM_OF_NETWORKS = 5;
@Override
public void setUp() throws Exception {
super.setUp();
dao = dbFacade.getNetworkDao();
cluster = new Guid("b399944a-81ab-4ec5-8266-e19ba7c3c9d1");
datacenter = new Guid("6d849ebf-755f-4552-ad09-9a090cda105d");
new_net = new Network();
new_net.setName("newnet1");
new_net.setDescription("New network");
new_net.setDataCenterId(datacenter);
}
/**
* Ensures that a null network is returned.
*/
@Test
public void testGetByNameWithInvalidName() {
Network result = dao.getByName("farkle");
assertNull(result);
}
/**
* Ensures that retrieving a network by name works as expected.
*/
@Test
public void testGetByName() {
Network result = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that retrieving a network by name and data center works as expected.
*/
@Test
public void testGetByNameAndDataCenter() {
Network result = dao.getByNameAndDataCenter(EXISTING_NETWORK_NAME, datacenter);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that retrieving a network by name and cluster works as expected.
*/
@Test
public void testGetByNameAndCluster() {
Network result = dao.getByNameAndCluster(EXISTING_NETWORK_NAME, cluster);
assertNotNull(result);
assertEquals(EXISTING_NETWORK_NAME, result.getName());
}
/**
* Ensures that all networks are returned.
*/
@Test
public void testGetAll() {
List<Network> result = dao.getAll();
assertNotNull(result);
assertEquals(NUM_OF_NETWORKS, result.size());
}
/**
* Ensures that all networks are returned for a specific user when filter is on.
*/
@Test
public void testFilteredGetAll() {
List<Network> result = dao.getAll(PRIVILEGED_USER_ID, true);
assertNotNull(result);
assertFalse(result.isEmpty());
}
/**
* Ensures that no networks is returned for a specific user when filter is on.
*/
@Test
public void testFilteredGetAllWithNoPermissions() {
List<Network> result = dao.getAll(UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that all networks are returned for a unprivileged user when filter is off.
*/
@Test
public void testUnfilteredGetAllWithNoPermissions() {
List<Network> result = dao.getAll(UNPRIVILEGED_USER_ID, false);
assertNotNull(result);
assertFalse(result.isEmpty());
}
/**
* Ensures that an empty collection is returned when the specified cluster has no networks.
*/
@Test
public void testGetAllForClusterWithInvalidCluster() {
List<Network> result = dao.getAllForCluster(Guid.newGuid());
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures the right set of networks are returned for the given cluster.
*/
@Test
public void testGetAllForCluster() {
List<Network> result = dao.getAllForCluster(cluster);
assertGetAllForClusterResult(result);
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a privileged user
*/
@Test
public void testGetAllForClusterFilteredWithPermissions() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, PRIVILEGED_USER_ID, true);
assertGetAllForClusterResult(result);
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a unprivileged user and with filtering enabled
*/
@Test
public void testGetAllForClusterFilteredWithPermissionsNoPermissions() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures the right set of networks are returned for the given cluster,
* with a unprivileged user, but with no filtering
*/
@Test
public void testGetAllForClusterFilteredWithPermissionsNoPermissionsAndNoFilter() {
// A use with permissions
List<Network> result = dao.getAllForCluster(cluster, UNPRIVILEGED_USER_ID, false);
assertGetAllForClusterResult(result);
}
/**
* Asserts the result of {@link NetworkDao#getAllForCluster(Guid)} contains all the required networks
* @param result
*/
private static void assertGetAllForClusterResult(List<Network> result) {
assertNotNull(result);
assertFalse(result.isEmpty());
assertIsSorted(result);
}
private static void assertIsSorted(List<Network> result) {
Network previous = null;
for (Network network : result) {
if (previous != null && network.getName().compareTo(previous.getName()) < 0) {
fail(String.format("List of networks is not ordered by network name, %s came before %s.",
previous.getName(),
network.getName()));
}
previous = network;
}
}
/**
* Ensures that an empty collection is returned when the data center has no networks.
*/
@Test
public void testGetAllForDataCenterWithInvalidDataCenter() {
List<Network> result = dao.getAllForDataCenter(Guid.newGuid());
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that the right set of networks are returned for the given data center.
*/
@Test
public void testGetAllForDataCenter() {
List<Network> result = dao.getAllForDataCenter(datacenter);
verifyDataCenterNetworks(result);
}
/**
* Ensures that the right set of networks are returned for the given data center for a specific user according to
* the filter.
*/
@Test
public void testFilteredGetAllForDataCenter() {
List<Network> result = dao.getAllForDataCenter(datacenter, PRIVILEGED_USER_ID, true);
verifyDataCenterNetworks(result);
}
/**
* Ensures that the no network is returned for the given data center for a user with no permissions on network
* entities
*/
@Test
public void testFilteredGetAllForDataCenterWithNoPermissions() {
List<Network> result = dao.getAllForDataCenter(datacenter, UNPRIVILEGED_USER_ID, true);
assertNotNull(result);
assertTrue(result.isEmpty());
}
/**
* Ensures that the all networks are returned for the given data center for a specific user when the filter is off.
*/
@Test
public void testUnFilteredGetAllForDataCenterWithNoPermissions() {
List<Network> result = dao.getAllForDataCenter(datacenter, PRIVILEGED_USER_ID, false);
verifyDataCenterNetworks(result);
}
private void verifyDataCenterNetworks(List<Network> result) {
assertGetAllForClusterResult(result);
for (Network net : result) {
assertEquals(datacenter, net.getDataCenterId());
}
}
/**
* Ensures the right set of networks are returned for the given provider.
*/
@Test
public void testGetAllForProvider() {
List<Network> result = dao.getAllForProvider(FixturesTool.PROVIDER_ID);
assertNotNull(result);
assertFalse(result.isEmpty());
for (Network network : result) {
assertEquals(FixturesTool.PROVIDER_ID, network.getProvidedBy().getProviderId());
}
}
/**
* Ensures that saving a network works as expected.
*/
@Test
public void testSave() {
List<NetworkCluster> clustersFromDB = dbFacade.getNetworkClusterDao().getAllForCluster(cluster);
NetworkCluster clusterFromDB = clustersFromDB.get(0);
assertNotNull(clusterFromDB);
new_net.setCluster(clusterFromDB);
new_net.setId(Guid.newGuid());
dao.save(new_net);
Network result = dao.getByName(new_net.getName());
assertNotNull(result);
assertEquals(new_net, result);
}
/**
* Ensures updating a network works as expected.
*/
@Test
public void testUpdate() {
Network before = dao.getByName(EXISTING_NETWORK_NAME);
before.setDescription("This is a completely changed description");
dao.update(before);
Network after = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(after);
assertEquals(before, after);
}
/**
* Ensures that removing a network works as expected.
*/
@Test
public void testRemove() {
Network result = dao.getByName(EXISTING_NETWORK_NAME);
assertNotNull(result);
dao.remove(result.getId());
result = dao.getByName(EXISTING_NETWORK_NAME);
assertNull(result);
}
}
| engine: Removed sorted assertion from DC networks test
This would occasionally fail the test, when the assertion was
originally meant only for cluster queries.
Change-Id: I8252ba734f1455eb15ed5e1478930d8bb2e23368
Signed-off-by: Lior Vernia <[email protected]>
| backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/network/NetworkDaoTest.java | engine: Removed sorted assertion from DC networks test |
|
Java | apache-2.0 | 9298c4dc95f6d620db4a77c32525b7e64cd907fc | 0 | bitstorm/wicket,mafulafunk/wicket,AlienQueen/wicket,martin-g/wicket-osgi,astrapi69/wicket,apache/wicket,selckin/wicket,mosoft521/wicket,topicusonderwijs/wicket,zwsong/wicket,dashorst/wicket,aldaris/wicket,klopfdreh/wicket,freiheit-com/wicket,klopfdreh/wicket,freiheit-com/wicket,zwsong/wicket,aldaris/wicket,Servoy/wicket,astrapi69/wicket,topicusonderwijs/wicket,aldaris/wicket,zwsong/wicket,bitstorm/wicket,mafulafunk/wicket,aldaris/wicket,mosoft521/wicket,Servoy/wicket,topicusonderwijs/wicket,Servoy/wicket,Servoy/wicket,topicusonderwijs/wicket,mosoft521/wicket,klopfdreh/wicket,selckin/wicket,freiheit-com/wicket,dashorst/wicket,dashorst/wicket,klopfdreh/wicket,martin-g/wicket-osgi,astrapi69/wicket,mosoft521/wicket,freiheit-com/wicket,apache/wicket,selckin/wicket,aldaris/wicket,astrapi69/wicket,Servoy/wicket,apache/wicket,topicusonderwijs/wicket,mafulafunk/wicket,freiheit-com/wicket,klopfdreh/wicket,martin-g/wicket-osgi,selckin/wicket,AlienQueen/wicket,bitstorm/wicket,apache/wicket,bitstorm/wicket,AlienQueen/wicket,bitstorm/wicket,zwsong/wicket,AlienQueen/wicket,dashorst/wicket,mosoft521/wicket,dashorst/wicket,AlienQueen/wicket,apache/wicket,selckin/wicket | /*
* $Id$
* $Revision$ $Date$
*
* ==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package wicket;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.markup.ComponentTag;
import wicket.markup.ComponentWicketTag;
import wicket.markup.IComponentResolver;
import wicket.markup.Markup;
import wicket.markup.MarkupElement;
import wicket.markup.MarkupException;
import wicket.markup.MarkupStream;
import wicket.model.IModel;
import wicket.util.collections.MicroMap;
import wicket.util.collections.MiniMap;
import wicket.util.listener.IChangeListener;
import wicket.util.resource.IResource;
import wicket.util.resource.ResourceNotFoundException;
import wicket.util.string.Strings;
import wicket.util.watch.ModificationWatcher;
/**
* A markup container holds a map of child components. Children can be added by
* calling the add() method and they can be looked up using a dotted path. For
* example, if a container called "a" held a nested container "b" which held a
* nested component "c", then a.get("b.c") would return the component named "c".
* <p>
* The number of children in a container can be determined by calling size().
* And the whole hierarchy of children held by a container can be traversed by
* calling visitChildren(), passing in an implementation of Component.IVisitor.
* <p>
* A container also holds markup information which is used to render the
* container. As the markup stream for a container is rendered, component
* references in the markup are resolved by using the container to look up
* components by name. Each component referenced by the markup stream is given
* an opportunity to render itself using the markup stream.
* <p>
* Components may alter the referring tag, replace the tag's body or insert
* markup after the tag. But components cannot remove tags from the markup
* stream. This is an important guarantee because graphic designers may be
* setting attributes on component tags that affect visual presentation.
* <p>
* The type of markup held in a given container subclass can be determined by
* calling getMarkupType(). Markup is accessed via a MarkupStream object which
* allows a component to traverse ComponentTag and RawMarkup MarkupElements
* while rendering a response. Markup in the stream may be HTML or some other
* kind of markup, such as VXML, as determined by the specific container
* subclass.
* <p>
* A markup stream may be directly associated with a container via
* setMarkupStream. However, a container which does not have a markup stream
* (its getMarkupStream() returns null) may inherit a markup stream from a
* container above it in the component hierarchy. The findMarkupStream() method
* will locate the first container at or above this container which has a markup
* stream.
* <p>
* All Page containers set a markup stream before rendering by calling the
* method getAssociatedMarkupStream() to load the markup associated with the
* page. Since Page is at the top of the container hierarchy, it is guaranteed
* that findMarkupStream will always return a valid markup stream.
*
* @see MarkupStream
* @author Jonathan Locke
*/
public abstract class MarkupContainer extends Component
{
/** Log for reporting. */
private static final Log log = LogFactory.getLog(MarkupContainer.class);
/** Map of markup tags by class. */
private static final Map markupCache = new HashMap();
/** Size of MiniMaps. */
private static final int MINIMAP_MAX_ENTRIES = 8;
/** Whether to optimize maps of children with MicroMap and MiniMap. */
private static final boolean optimizeChildMapsForSpace = false;
/** Map of children by name. */
private Map childForName = Collections.EMPTY_MAP;
/** The markup stream for this container. */
private transient MarkupStream markupStream;
/**
* @see wicket.Component#Component(String)
*/
public MarkupContainer(final String id)
{
super(id);
optimize();
}
/**
* @see wicket.Component#Component(String, IModel)
*/
public MarkupContainer(final String id, IModel model)
{
super(id, model);
optimize();
}
/**
* Adds a child component to this container.
*
* @param child
* The child
* @throws IllegalArgumentException
* Thrown if a child with the same name is replaced by the add
* operation.
* @return This
*/
public MarkupContainer add(final Component child)
{
// Check for degenerate case
if (child == this)
{
throw new IllegalArgumentException("Component can't be added to itself");
}
// Get child name
final String childName = child.getId();
if (log.isDebugEnabled())
{
log.debug("Add " + childName + " to " + this);
}
// Set child's parent
child.setParent(this);
// Are we using MicroMap optimization?
if (optimizeChildMapsForSpace)
{
if (childForName.size() == MicroMap.MAX_ENTRIES)
{
// Reallocate MicroMap as MiniMap
childForName = new MiniMap(childForName, MINIMAP_MAX_ENTRIES);
}
else if (childForName.size() == MINIMAP_MAX_ENTRIES)
{
// Reallocate MiniMap as full HashMap
childForName = new HashMap(childForName);
}
}
// Add to map
final Object replaced = childForName.put(childName, child);
// Look up to make sure it's not already in the map
if (replaced != null)
{
throw new IllegalArgumentException(exceptionMessage("A child component with the name '"
+ childName + "' already exists"));
}
// Tell the page a component was added
final Page page = findPage();
if (page != null)
{
page.componentAdded(child);
}
return this;
}
/**
* Get a child component by looking it up with the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
public final Component get(final String path)
{
// Reference to this container
if (path == null || path.trim().equals(""))
{
return this;
}
// Get child's name, if any
final String childName = Strings.firstPathComponent(path, '.');
// Get child by name
final Component child = (Component)childForName.get(childName);
// Found child?
if (child != null)
{
// Recurse on latter part of path
return child.get(Strings.afterFirstPathComponent(path, '.'));
}
// No child by that name
return null;
}
/**
* Get the Iterator that iterates through children in an undefined order.
*
* @return Iterator that iterates through children in an undefined order
*/
public final Iterator iterator()
{
if (childForName == null)
{
childForName = Collections.EMPTY_MAP;
}
return new ComponentIterator(childForName.values().iterator());
}
/**
* @param component
* The component to check
* @param recurse
* True if all descendents should be considered
* @return True if the component is contained in this container
*/
public final boolean contains(final Component component, final boolean recurse)
{
if (recurse)
{
// Start at component and continue while we're not out of parents
for (Component current = component; current != null;)
{
// Get parent
final MarkupContainer parent = current.getParent();
// If this container is the parent, then the component is
// recursively contained by this container
if (parent == this)
{
// Found it!
return true;
}
// Move up the chain to the next parent
current = parent;
}
// Failed to find this container in component's ancestry
return false;
}
else
{
// Is the component contained in this container?
return component.getParent() == this;
}
}
/**
* Removes the named component
*
* @param id
* The id of the component to remove
*/
public void remove(final String id)
{
final Component component = get(id);
if (component != null)
{
// Remove from map
childForName.remove(id);
// Notify Page
final Page page = findPage();
if (page != null)
{
page.componentRemoved(component);
}
}
else
{
throw new WicketRuntimeException("Unable to find a component with id '" + id
+ "' to remove");
}
}
/**
* Removes all children from this container.
*/
public void removeAll()
{
// MarkupContainer.java
// Undoable undoable = new RemoveAllUndoable(childForName);
//
// getPage().addUndoable(undoable);
//
// childForName.clear();
// Get page for efficiency
final Page page = findPage();
// Loop through child components
for (final Iterator iterator = childForName.values().iterator(); iterator.hasNext();)
{
// Get next child
final Component component = (Component)iterator.next();
// Remove child
iterator.remove();
// Tell the page we removed the component
if (page != null)
{
page.componentRemoved(component);
}
}
}
/**
* Replaces a child component of this container with another
*
* @param child
* The child
* @throws IllegalArgumentException
* Thrown if there was no child with the same name.
* @return This
*/
public MarkupContainer replace(final Component child)
{
// Get child name
final String childName = child.getId();
if (log.isDebugEnabled())
{
log.debug("Add " + childName + " to " + this);
}
if (child.getParent() != this)
{
// First reset the childs parent (can't set them at once with
// another)
child.setParent(null);
// Set child's parent
child.setParent(this);
// Are we using MicroMap optimization?
if (optimizeChildMapsForSpace)
{
if (childForName.size() == MicroMap.MAX_ENTRIES)
{
// Reallocate MicroMap as MiniMap
childForName = new MiniMap(childForName, MINIMAP_MAX_ENTRIES);
}
else if (childForName.size() == MINIMAP_MAX_ENTRIES)
{
// Reallocate MiniMap as full HashMap
childForName = new HashMap(childForName);
}
}
// Add to map
final Component replaced = (Component)childForName.put(childName, child);
// Look up to make sure it was already in the map
if (replaced == null)
{
throw new IllegalArgumentException(
exceptionMessage("A child component with the name '" + childName
+ "' didn't exist"));
}
replaced.setParent(null);
// Notify the page that the replace happened
final Page page = findPage();
if (page != null)
{
page.componentRemoved(replaced);
page.componentAdded(child);
}
}
return this;
}
/**
* Get the number of children in this container.
*
* @return Number of children in this container
*/
public final int size()
{
return childForName.size();
}
/**
* Get the string representation of this container.
*
* @return String representation of this container
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(super.toString());
if (markupStream != null)
{
buffer.append(", markupStream = " + markupStream);
}
if (childForName != null && childForName.size() != 0)
{
buffer.append(", children = " + childForName.values());
}
buffer.append(']');
return buffer.toString();
}
/**
* Traverses all child components of the given class in this container,
* calling the visitor's visit method at each one.
*
* @param c
* The class of child to visit, or null to visit all children
* @param visitor
* The visitor to call back to
* @return The return value from a visitor which halted the traversal, or
* null if the entire traversal occurred
*/
public final Object visitChildren(final Class c, final IVisitor visitor)
{
// Iterate through children on this container
for (Iterator iterator = iterator(); iterator.hasNext();)
{
// Get next child component
final Component child = (Component)iterator.next();
// Is the child of the correct class (or was no class specified)?
if ((c == null) || c.isInstance(child))
{
// Call visitor
final Object value = visitor.component(child);
// If visitor returns a non-null value, it halts the traversal
if (value != IVisitor.CONTINUE_TRAVERSAL)
{
return value;
}
}
// If child is a container
if (child instanceof MarkupContainer)
{
// visit the children in the container
final Object value = ((MarkupContainer)child).visitChildren(c, visitor);
// If visitor returns a non-null value, it halts the traversal
if (value != IVisitor.CONTINUE_TRAVERSAL)
{
return value;
}
}
}
return null;
}
/**
* Traverses all child components in this container, calling the visitor's
* visit method at each one.
*
* @param visitor
* The visitor to call back to
* @return The return value from a visitor which halted the traversal, or
* null if the entire traversal occurred
*/
public final Object visitChildren(final IVisitor visitor)
{
return visitChildren(null, visitor);
}
/**
* Get the markup stream for this component.
*
* @return The markup stream for this component, or if it doesn't have one,
* the markup stream for the nearest parent which does have one
*/
protected final MarkupStream findMarkupStream()
{
// Start here
MarkupContainer c = this;
// Walk up hierarchy until markup found
while (c.markupStream == null)
{
// Check parent
c = c.getParent();
// Are we at the top of the hierarchy?
if (c == null)
{
// Failed to find markup stream
throw new WicketRuntimeException(exceptionMessage("No markup found"));
}
}
return c.markupStream;
}
/**
* Get the markup stream set on this container.
*
* @return Returns the markup stream set on this container.
*/
protected final MarkupStream getMarkupStream()
{
return markupStream;
}
/**
* Get the type of associated markup for this component.
*
* @return The type of associated markup for this component (for example,
* "html", "wml" or "vxml"). The markup type for a component is
* independent of whether or not the component actually has an
* associated markup resource file (which is determined at runtime).
* If there is no markup type for a component, null may be returned,
* but this means that no markup can be loaded for the class.
*/
protected String getMarkupType()
{
throw new IllegalStateException(
exceptionMessage("You cannot directly subclass Page or MarkupContainer. Instead, subclass a markup-specific class, such as WebPage or WebMarkupContainer"));
}
/**
* Handle the container's body. If your override of this method does not
* advance the markup stream to the close tag for the openTag, a runtime
* exception will be thrown by the framework.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
renderComponentTagBody(markupStream, openTag);
}
/**
* Renders this component.
*/
protected void onRender()
{
renderAll(findMarkupStream());
}
/**
* Renders the entire associated markup stream for a container such as a
* Border or Panel. Any leading or trailing raw markup in the associated
* markup is skipped.
*
* @param openTagName
* the tag to render the associated markup for
* @param exceptionMessage
* message that will be used for exceptions
*/
protected final void renderAssociatedMarkup(final String openTagName,
final String exceptionMessage)
{
// Get markup associated with Border or Panel component
final MarkupStream originalMarkupStream = getMarkupStream();
final MarkupStream associatedMarkupStream = getAssociatedMarkupStream();
associatedMarkupStream.skipRawMarkup();
setMarkupStream(associatedMarkupStream);
// Get open tag in associated markup of border component
final ComponentTag associatedMarkupOpenTag = associatedMarkupStream.getTag();
// Check for required open tag name
if (!(associatedMarkupStream.atOpenTag(openTagName) && (associatedMarkupOpenTag instanceof ComponentWicketTag)))
{
associatedMarkupStream.throwMarkupException(exceptionMessage);
}
renderComponentTag(associatedMarkupOpenTag);
associatedMarkupStream.next();
renderComponentTagBody(associatedMarkupStream, associatedMarkupOpenTag);
renderClosingComponentTag(associatedMarkupStream, associatedMarkupOpenTag);
setMarkupStream(originalMarkupStream);
}
/**
* Renders markup for the body of a ComponentTag from the current position
* in the given markup stream. If the open tag passed in does not require a
* close tag, nothing happens. Markup is rendered until the closing tag for
* openTag is reached.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag
*/
protected final void renderComponentTagBody(final MarkupStream markupStream,
final ComponentTag openTag)
{
// If the open tag requires a close tag
if (openTag.requiresCloseTag())
{
// Loop through the markup in this container
while (markupStream.hasMore() && !markupStream.get().closes(openTag))
{
// Render markup element. Doing so must advance the markup
// stream
final int index = markupStream.getCurrentIndex();
renderNext(markupStream);
if (index == markupStream.getCurrentIndex())
{
markupStream.throwMarkupException("Markup element at index " + index
+ " failed to advance the markup stream");
}
}
}
}
/**
* The MarkupContainer was not able to resolve the component name.
* Subclasses may augment the default strategy by subclassing
* resolveComponent().
*
* @see wicket.markup.html.border.Border for an example.
* <p>
* Note: resolveComponent must also render the components created
*
* @param markupStream
* The current markup stream
* @param tag
* The current component tag
* @return true, if MarkupContainer was able to resolve the component name
* and to render the component
*/
protected boolean resolveComponent(final MarkupStream markupStream, final ComponentTag tag)
{
return false;
}
/**
* Set markup stream for this container.
*
* @param markupStream
* The markup stream
*/
protected final void setMarkupStream(final MarkupStream markupStream)
{
this.markupStream = markupStream;
}
/**
* Gets any (immutable) markup resource for this class.
*
* @return Markup resource
*/
final Markup getAssociatedMarkup()
{
synchronized (markupCache)
{
// Look up markup tag list by class, locale, style and markup type
final String key = markupKey();
Markup markup = (Markup)markupCache.get(key);
// If no markup in map
if (markup == null)
{
// Locate markup resource, searching up class hierarchy
IResource markupResource = null;
Class containerClass = getClass();
while ((markupResource == null) && (containerClass != MarkupContainer.class))
{
// Look for markup resource for containerClass
markupResource = getApplication().getResourceLocator().locate(containerClass,
getStyle(), getLocale(), getMarkupType());
containerClass = containerClass.getSuperclass();
}
// Found markup?
if (markupResource != null)
{
// load the markup and watch for changes
markup = loadMarkupAndWatchForChanges(key, markupResource);
}
else
{
// flag markup as non-existent (as opposed to null, which
// might mean that it's simply not loaded into the cache)
markup = Markup.NO_MARKUP;
}
// Save any markup list (or absence of one) for next time
markupCache.put(key, markup);
}
return markup;
}
}
/**
* Gets a fresh markup stream that contains the (immutable) markup resource
* for this class.
*
* @return A stream of MarkupElement elements
*/
final MarkupStream getAssociatedMarkupStream()
{
// Look for associated markup
final Markup markup = getAssociatedMarkup();
// If we found markup for this container
if (markup != Markup.NO_MARKUP)
{
// return a MarkupStream for the markup
return new MarkupStream(markup);
}
else
{
// throw exception since there is no associated markup
throw new WicketRuntimeException(
exceptionMessage("Markup of type '"
+ getMarkupType()
+ "' for component '"
+ getClass().getName()
+ "' not found."
+ " Enable debug messages for wicket.util.resource.Resource to get a list of all filenames tried."));
}
}
/**
* @return True if this markup container has associated markup
*/
final boolean hasAssociatedMarkup()
{
return getAssociatedMarkup() != Markup.NO_MARKUP;
}
/**
* Renders this component and all sub-components using the given markup
* stream.
*
* @param markupStream
* The markup stream
*/
final void renderAll(final MarkupStream markupStream)
{
// Loop through the markup in this container
while (markupStream.hasMore())
{
// Element rendering is responsible for advancing markup stream!
final int index = markupStream.getCurrentIndex();
renderNext(markupStream);
if (index == markupStream.getCurrentIndex())
{
markupStream.throwMarkupException("Component at markup stream index " + index
+ " failed to advance the markup stream");
}
}
}
/**
* Loads markup.
*
* @param application
* Application
* @param key
* Key under which markup should be cached
* @param markupResource
* The markup resource to load
* @return The markup
* @throws ParseException
* @throws IOException
* @throws ResourceNotFoundException
*/
private Markup loadMarkup(final Application application, final String key,
final IResource markupResource) throws ParseException, IOException,
ResourceNotFoundException
{
final Markup markup = application.getMarkupParser().readAndParse(markupResource);
markupCache.put(key, markup);
return markup;
}
/**
* Load markup and add a {@link ModificationWatcher}to the markup resource.
*
* @param key
* The key for the resource
* @param markupResource
* The markup file to load and begin to watch
* @return The markup in the file
*/
private Markup loadMarkupAndWatchForChanges(final String key, final IResource markupResource)
{
final Application application = getApplication();
try
{
// Watch file in the future
final ModificationWatcher watcher = application.getResourceWatcher();
if (watcher != null)
{
watcher.add(markupResource, new IChangeListener()
{
public void onChange()
{
synchronized (markupCache)
{
try
{
log.info("Reloading markup from " + markupResource);
loadMarkup(application, key, markupResource);
}
catch (ParseException e)
{
log.error("Unable to parse markup from " + markupResource, e);
}
catch (ResourceNotFoundException e)
{
log.error("Unable to find markup from " + markupResource, e);
}
catch (IOException e)
{
log.error("Unable to read markup from " + markupResource, e);
}
}
}
});
}
log.info("Loading markup from " + markupResource);
return loadMarkup(application, key, markupResource);
}
catch (ParseException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to parse markup from " + markupResource), e);
}
catch (MarkupException e)
{
throw new MarkupException(markupResource, exceptionMessage(e.getMessage()));
}
catch (ResourceNotFoundException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to find markup from " + markupResource), e);
}
catch (IOException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to read markup from " + markupResource), e);
}
}
/**
* @return Key that uniquely identifies any markup that might be associated
* with this markup container.
*/
private String markupKey()
{
return getClass().getName() + getLocale() + getStyle() + getMarkupType();
}
/**
* Optimize child name mapping.
*/
private void optimize()
{
if (optimizeChildMapsForSpace)
{
childForName = new MicroMap();
}
else
{
childForName = new HashMap();
}
}
/**
* Renders the next element of markup in the given markup stream.
*
* @param markupStream
* The markup stream
*/
private void renderNext(final MarkupStream markupStream)
{
// Get the current markup element
final MarkupElement element = markupStream.get();
// If it a tag like <wicket..> or <span wicket:id="..." >
if (element instanceof ComponentTag && !markupStream.atCloseTag())
{
// Get element as tag
final ComponentTag tag = (ComponentTag)element;
// Get component name
final String componentId = tag.getId();
// Get the component for the component name from the given container
final Component component = get(componentId);
// Failed to find it?
if (component != null)
{
component.render();
}
else
{
// 2nd try: all static name resolvers
final List componentResolvers = this.getApplication().getComponentResolvers();
final Iterator iter = componentResolvers.iterator();
while (iter.hasNext())
{
final IComponentResolver resolver = (IComponentResolver)iter.next();
if (resolver.resolve(this, markupStream, tag))
{
return;
}
}
// 3rd try: a subclass replacing resolveComponent()
MarkupContainer container = this;
while (container != null)
{
if (container.resolveComponent(markupStream, tag))
{
return;
}
container = container.findParent(MarkupContainer.class);
}
// No one was able to handle the component name
markupStream.throwMarkupException("Unable to find component named '"
+ componentId + "' in " + this);
}
}
else
{
// Render as raw markup
log.debug("Rendering raw markup");
getResponse().write(element.toString());
markupStream.next();
}
}
private class ComponentIterator implements Iterator
{
private Iterator iterator;
private Component component;
/**
* @param iterator
*
*/
public ComponentIterator(Iterator iterator)
{
this.iterator = iterator;
}
/**
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext()
{
return iterator.hasNext();
}
/**
* @see java.util.Iterator#next()
*/
public Object next()
{
component = (Component)iterator.next();
return component;
}
/**
* @see java.util.Iterator#remove()
*/
public void remove()
{
iterator.remove();
// Notify Page
final Page page = findPage();
if (page != null)
{
page.componentRemoved(component);
}
}
}
} | wicket/src/java/wicket/MarkupContainer.java | /*
* $Id$
* $Revision$ $Date$
*
* ==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package wicket;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.markup.ComponentTag;
import wicket.markup.ComponentWicketTag;
import wicket.markup.IComponentResolver;
import wicket.markup.Markup;
import wicket.markup.MarkupElement;
import wicket.markup.MarkupException;
import wicket.markup.MarkupStream;
import wicket.model.IModel;
import wicket.util.collections.MicroMap;
import wicket.util.collections.MiniMap;
import wicket.util.listener.IChangeListener;
import wicket.util.resource.IResource;
import wicket.util.resource.ResourceNotFoundException;
import wicket.util.string.Strings;
import wicket.util.watch.ModificationWatcher;
/**
* A markup container holds a map of child components. Children can be added by
* calling the add() method and they can be looked up using a dotted path. For
* example, if a container called "a" held a nested container "b" which held a
* nested component "c", then a.get("b.c") would return the component named "c".
* <p>
* The number of children in a container can be determined by calling size().
* And the whole hierarchy of children held by a container can be traversed by
* calling visitChildren(), passing in an implementation of Component.IVisitor.
* <p>
* A container also holds markup information which is used to render the
* container. As the markup stream for a container is rendered, component
* references in the markup are resolved by using the container to look up
* components by name. Each component referenced by the markup stream is given
* an opportunity to render itself using the markup stream.
* <p>
* Components may alter the referring tag, replace the tag's body or insert
* markup after the tag. But components cannot remove tags from the markup
* stream. This is an important guarantee because graphic designers may be
* setting attributes on component tags that affect visual presentation.
* <p>
* The type of markup held in a given container subclass can be determined by
* calling getMarkupType(). Markup is accessed via a MarkupStream object which
* allows a component to traverse ComponentTag and RawMarkup MarkupElements
* while rendering a response. Markup in the stream may be HTML or some other
* kind of markup, such as VXML, as determined by the specific container
* subclass.
* <p>
* A markup stream may be directly associated with a container via
* setMarkupStream. However, a container which does not have a markup stream
* (its getMarkupStream() returns null) may inherit a markup stream from a
* container above it in the component hierarchy. The findMarkupStream() method
* will locate the first container at or above this container which has a markup
* stream.
* <p>
* All Page containers set a markup stream before rendering by calling the
* method getAssociatedMarkupStream() to load the markup associated with the
* page. Since Page is at the top of the container hierarchy, it is guaranteed
* that findMarkupStream will always return a valid markup stream.
*
* @see MarkupStream
* @author Jonathan Locke
*/
public abstract class MarkupContainer extends Component
{
/** Log for reporting. */
private static final Log log = LogFactory.getLog(MarkupContainer.class);
/** Map of markup tags by class. */
private static final Map markupCache = new HashMap();
/** Size of MiniMaps. */
private static final int MINIMAP_MAX_ENTRIES = 8;
/** Whether to optimize maps of children with MicroMap and MiniMap. */
private static final boolean optimizeChildMapsForSpace = false;
/** Map of children by name. */
private Map childForName = Collections.EMPTY_MAP;
/** The markup stream for this container. */
private transient MarkupStream markupStream;
/**
* @see wicket.Component#Component(String)
*/
public MarkupContainer(final String id)
{
super(id);
optimize();
}
/**
* @see wicket.Component#Component(String, IModel)
*/
public MarkupContainer(final String id, IModel model)
{
super(id, model);
optimize();
}
/**
* Adds a child component to this container.
*
* @param child
* The child
* @throws IllegalArgumentException
* Thrown if a child with the same name is replaced by the add
* operation.
* @return This
*/
public MarkupContainer add(final Component child)
{
// Check for degenerate case
if (child == this)
{
throw new IllegalArgumentException("Component can't be added to itself");
}
// Get child name
final String childName = child.getId();
if (log.isDebugEnabled())
{
log.debug("Add " + childName + " to " + this);
}
// Set child's parent
child.setParent(this);
// Are we using MicroMap optimization?
if (optimizeChildMapsForSpace)
{
if (childForName.size() == MicroMap.MAX_ENTRIES)
{
// Reallocate MicroMap as MiniMap
childForName = new MiniMap(childForName, MINIMAP_MAX_ENTRIES);
}
else if (childForName.size() == MINIMAP_MAX_ENTRIES)
{
// Reallocate MiniMap as full HashMap
childForName = new HashMap(childForName);
}
}
// Add to map
final Object replaced = childForName.put(childName, child);
// Look up to make sure it's not already in the map
if (replaced != null)
{
throw new IllegalArgumentException(exceptionMessage("A child component with the name '"
+ childName + "' already exists"));
}
// Tell the page a component was added
final Page page = findPage();
if (page != null)
{
page.componentAdded(child);
}
return this;
}
/**
* Get a child component by looking it up with the given path.
*
* @param path
* Path to component
* @return The component at the path
*/
public final Component get(final String path)
{
// Reference to this container
if (path == null || path.trim().equals(""))
{
return this;
}
// Get child's name, if any
final String childName = Strings.firstPathComponent(path, '.');
// Get child by name
final Component child = (Component)childForName.get(childName);
// Found child?
if (child != null)
{
// Recurse on latter part of path
return child.get(Strings.afterFirstPathComponent(path, '.'));
}
// No child by that name
return null;
}
/**
* Get the Iterator that iterates through children in an undefined order.
*
* @return Iterator that iterates through children in an undefined order
*/
public final Iterator iterator()
{
if (childForName == null)
{
childForName = Collections.EMPTY_MAP;
}
return childForName.values().iterator();
}
/**
* @param component
* The component to check
* @param recurse
* True if all descendents should be considered
* @return True if the component is contained in this container
*/
public final boolean contains(final Component component, final boolean recurse)
{
if (recurse)
{
// Start at component and continue while we're not out of parents
for (Component current = component; current != null;)
{
// Get parent
final MarkupContainer parent = current.getParent();
// If this container is the parent, then the component is
// recursively contained by this container
if (parent == this)
{
// Found it!
return true;
}
// Move up the chain to the next parent
current = parent;
}
// Failed to find this container in component's ancestry
return false;
}
else
{
// Is the component contained in this container?
return component.getParent() == this;
}
}
/**
* Removes the named component
*
* @param id
* The id of the component to remove
*/
public void remove(final String id)
{
final Component component = get(id);
if (component != null)
{
// Remove from map
childForName.remove(id);
// Notify Page
final Page page = findPage();
if (page != null)
{
page.componentRemoved(component);
}
}
else
{
throw new WicketRuntimeException("Unable to find a component with id '" + id
+ "' to remove");
}
}
/**
* Removes all children from this container.
*/
public void removeAll()
{
// Get page for efficiency
final Page page = findPage();
// Loop through child components
for (final Iterator iterator = childForName.values().iterator(); iterator.hasNext();)
{
// Get next child
final Component component = (Component)iterator.next();
// Remove child
iterator.remove();
// Tell the page we removed the component
if (page != null)
{
page.componentRemoved(component);
}
}
}
/**
* Replaces a child component of this container with another
*
* @param child
* The child
* @throws IllegalArgumentException
* Thrown if there was no child with the same name.
* @return This
*/
public MarkupContainer replace(final Component child)
{
// Get child name
final String childName = child.getId();
if (log.isDebugEnabled())
{
log.debug("Add " + childName + " to " + this);
}
if (child.getParent() != this)
{
// First reset the childs parent (can't set them at once with
// another)
child.setParent(null);
// Set child's parent
child.setParent(this);
// Are we using MicroMap optimization?
if (optimizeChildMapsForSpace)
{
if (childForName.size() == MicroMap.MAX_ENTRIES)
{
// Reallocate MicroMap as MiniMap
childForName = new MiniMap(childForName, MINIMAP_MAX_ENTRIES);
}
else if (childForName.size() == MINIMAP_MAX_ENTRIES)
{
// Reallocate MiniMap as full HashMap
childForName = new HashMap(childForName);
}
}
// Add to map
final Component replaced = (Component)childForName.put(childName, child);
// Look up to make sure it was already in the map
if (replaced == null)
{
throw new IllegalArgumentException(
exceptionMessage("A child component with the name '" + childName
+ "' didn't exist"));
}
replaced.setParent(null);
// Notify the page that the replace happened
final Page page = findPage();
if (page != null)
{
page.componentRemoved(replaced);
page.componentAdded(child);
}
}
return this;
}
/**
* Get the number of children in this container.
*
* @return Number of children in this container
*/
public final int size()
{
return childForName.size();
}
/**
* Get the string representation of this container.
*
* @return String representation of this container
*/
public String toString()
{
final StringBuffer buffer = new StringBuffer();
buffer.append("[");
buffer.append(super.toString());
if (markupStream != null)
{
buffer.append(", markupStream = " + markupStream);
}
if (childForName != null && childForName.size() != 0)
{
buffer.append(", children = " + childForName.values());
}
buffer.append(']');
return buffer.toString();
}
/**
* Traverses all child components of the given class in this container,
* calling the visitor's visit method at each one.
*
* @param c
* The class of child to visit, or null to visit all children
* @param visitor
* The visitor to call back to
* @return The return value from a visitor which halted the traversal, or
* null if the entire traversal occurred
*/
public final Object visitChildren(final Class c, final IVisitor visitor)
{
// Iterate through children on this container
for (Iterator iterator = iterator(); iterator.hasNext();)
{
// Get next child component
final Component child = (Component)iterator.next();
// Is the child of the correct class (or was no class specified)?
if ((c == null) || c.isInstance(child))
{
// Call visitor
final Object value = visitor.component(child);
// If visitor returns a non-null value, it halts the traversal
if (value != IVisitor.CONTINUE_TRAVERSAL)
{
return value;
}
}
// If child is a container
if (child instanceof MarkupContainer)
{
// visit the children in the container
final Object value = ((MarkupContainer)child).visitChildren(c, visitor);
// If visitor returns a non-null value, it halts the traversal
if (value != IVisitor.CONTINUE_TRAVERSAL)
{
return value;
}
}
}
return null;
}
/**
* Traverses all child components in this container, calling the visitor's
* visit method at each one.
*
* @param visitor
* The visitor to call back to
* @return The return value from a visitor which halted the traversal, or
* null if the entire traversal occurred
*/
public final Object visitChildren(final IVisitor visitor)
{
return visitChildren(null, visitor);
}
/**
* Get the markup stream for this component.
*
* @return The markup stream for this component, or if it doesn't have one,
* the markup stream for the nearest parent which does have one
*/
protected final MarkupStream findMarkupStream()
{
// Start here
MarkupContainer c = this;
// Walk up hierarchy until markup found
while (c.markupStream == null)
{
// Check parent
c = c.getParent();
// Are we at the top of the hierarchy?
if (c == null)
{
// Failed to find markup stream
throw new WicketRuntimeException(exceptionMessage("No markup found"));
}
}
return c.markupStream;
}
/**
* Get the markup stream set on this container.
*
* @return Returns the markup stream set on this container.
*/
protected final MarkupStream getMarkupStream()
{
return markupStream;
}
/**
* Get the type of associated markup for this component.
*
* @return The type of associated markup for this component (for example,
* "html", "wml" or "vxml"). The markup type for a component is
* independent of whether or not the component actually has an
* associated markup resource file (which is determined at runtime).
* If there is no markup type for a component, null may be returned,
* but this means that no markup can be loaded for the class.
*/
protected String getMarkupType()
{
throw new IllegalStateException(
exceptionMessage("You cannot directly subclass Page or MarkupContainer. Instead, subclass a markup-specific class, such as WebPage or WebMarkupContainer"));
}
/**
* Handle the container's body. If your override of this method does not
* advance the markup stream to the close tag for the openTag, a runtime
* exception will be thrown by the framework.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
renderComponentTagBody(markupStream, openTag);
}
/**
* Renders this component.
*/
protected void onRender()
{
renderAll(findMarkupStream());
}
/**
* Renders the entire associated markup stream for a container such as a
* Border or Panel. Any leading or trailing raw markup in the associated
* markup is skipped.
*
* @param openTagName
* the tag to render the associated markup for
* @param exceptionMessage
* message that will be used for exceptions
*/
protected final void renderAssociatedMarkup(final String openTagName,
final String exceptionMessage)
{
// Get markup associated with Border or Panel component
final MarkupStream originalMarkupStream = getMarkupStream();
final MarkupStream associatedMarkupStream = getAssociatedMarkupStream();
associatedMarkupStream.skipRawMarkup();
setMarkupStream(associatedMarkupStream);
// Get open tag in associated markup of border component
final ComponentTag associatedMarkupOpenTag = associatedMarkupStream.getTag();
// Check for required open tag name
if (!(associatedMarkupStream.atOpenTag(openTagName) && (associatedMarkupOpenTag instanceof ComponentWicketTag)))
{
associatedMarkupStream.throwMarkupException(exceptionMessage);
}
renderComponentTag(associatedMarkupOpenTag);
associatedMarkupStream.next();
renderComponentTagBody(associatedMarkupStream, associatedMarkupOpenTag);
renderClosingComponentTag(associatedMarkupStream, associatedMarkupOpenTag);
setMarkupStream(originalMarkupStream);
}
/**
* Renders markup for the body of a ComponentTag from the current position
* in the given markup stream. If the open tag passed in does not require a
* close tag, nothing happens. Markup is rendered until the closing tag for
* openTag is reached.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag
*/
protected final void renderComponentTagBody(final MarkupStream markupStream,
final ComponentTag openTag)
{
// If the open tag requires a close tag
if (openTag.requiresCloseTag())
{
// Loop through the markup in this container
while (markupStream.hasMore() && !markupStream.get().closes(openTag))
{
// Render markup element. Doing so must advance the markup
// stream
final int index = markupStream.getCurrentIndex();
renderNext(markupStream);
if (index == markupStream.getCurrentIndex())
{
markupStream.throwMarkupException("Markup element at index " + index
+ " failed to advance the markup stream");
}
}
}
}
/**
* The MarkupContainer was not able to resolve the component name.
* Subclasses may augment the default strategy by subclassing
* resolveComponent().
*
* @see wicket.markup.html.border.Border for an example.
* <p>
* Note: resolveComponent must also render the components created
*
* @param markupStream
* The current markup stream
* @param tag
* The current component tag
* @return true, if MarkupContainer was able to resolve the component name
* and to render the component
*/
protected boolean resolveComponent(final MarkupStream markupStream, final ComponentTag tag)
{
return false;
}
/**
* Set markup stream for this container.
*
* @param markupStream
* The markup stream
*/
protected final void setMarkupStream(final MarkupStream markupStream)
{
this.markupStream = markupStream;
}
/**
* Gets any (immutable) markup resource for this class.
*
* @return Markup resource
*/
final Markup getAssociatedMarkup()
{
synchronized (markupCache)
{
// Look up markup tag list by class, locale, style and markup type
final String key = markupKey();
Markup markup = (Markup)markupCache.get(key);
// If no markup in map
if (markup == null)
{
// Locate markup resource, searching up class hierarchy
IResource markupResource = null;
Class containerClass = getClass();
while ((markupResource == null) && (containerClass != MarkupContainer.class))
{
// Look for markup resource for containerClass
markupResource = getApplication().getResourceLocator().locate(containerClass,
getStyle(), getLocale(), getMarkupType());
containerClass = containerClass.getSuperclass();
}
// Found markup?
if (markupResource != null)
{
// load the markup and watch for changes
markup = loadMarkupAndWatchForChanges(key, markupResource);
}
else
{
// flag markup as non-existent (as opposed to null, which
// might mean that it's simply not loaded into the cache)
markup = Markup.NO_MARKUP;
}
// Save any markup list (or absence of one) for next time
markupCache.put(key, markup);
}
return markup;
}
}
/**
* Gets a fresh markup stream that contains the (immutable) markup resource
* for this class.
*
* @return A stream of MarkupElement elements
*/
final MarkupStream getAssociatedMarkupStream()
{
// Look for associated markup
final Markup markup = getAssociatedMarkup();
// If we found markup for this container
if (markup != Markup.NO_MARKUP)
{
// return a MarkupStream for the markup
return new MarkupStream(markup);
}
else
{
// throw exception since there is no associated markup
throw new WicketRuntimeException(
exceptionMessage("Markup of type '"
+ getMarkupType()
+ "' for component '"
+ getClass().getName()
+ "' not found."
+ " Enable debug messages for wicket.util.resource.Resource to get a list of all filenames tried."));
}
}
/**
* @return True if this markup container has associated markup
*/
final boolean hasAssociatedMarkup()
{
return getAssociatedMarkup() != Markup.NO_MARKUP;
}
/**
* Renders this component and all sub-components using the given markup
* stream.
*
* @param markupStream
* The markup stream
*/
final void renderAll(final MarkupStream markupStream)
{
// Loop through the markup in this container
while (markupStream.hasMore())
{
// Element rendering is responsible for advancing markup stream!
final int index = markupStream.getCurrentIndex();
renderNext(markupStream);
if (index == markupStream.getCurrentIndex())
{
markupStream.throwMarkupException("Component at markup stream index " + index
+ " failed to advance the markup stream");
}
}
}
/**
* Loads markup.
*
* @param application
* Application
* @param key
* Key under which markup should be cached
* @param markupResource
* The markup resource to load
* @return The markup
* @throws ParseException
* @throws IOException
* @throws ResourceNotFoundException
*/
private Markup loadMarkup(final Application application, final String key,
final IResource markupResource) throws ParseException, IOException,
ResourceNotFoundException
{
final Markup markup = application.getMarkupParser().readAndParse(markupResource);
markupCache.put(key, markup);
return markup;
}
/**
* Load markup and add a {@link ModificationWatcher}to the markup resource.
*
* @param key
* The key for the resource
* @param markupResource
* The markup file to load and begin to watch
* @return The markup in the file
*/
private Markup loadMarkupAndWatchForChanges(final String key, final IResource markupResource)
{
final Application application = getApplication();
try
{
// Watch file in the future
final ModificationWatcher watcher = application.getResourceWatcher();
if (watcher != null)
{
watcher.add(markupResource, new IChangeListener()
{
public void onChange()
{
synchronized (markupCache)
{
try
{
log.info("Reloading markup from " + markupResource);
loadMarkup(application, key, markupResource);
}
catch (ParseException e)
{
log.error("Unable to parse markup from " + markupResource, e);
}
catch (ResourceNotFoundException e)
{
log.error("Unable to find markup from " + markupResource, e);
}
catch (IOException e)
{
log.error("Unable to read markup from " + markupResource, e);
}
}
}
});
}
log.info("Loading markup from " + markupResource);
return loadMarkup(application, key, markupResource);
}
catch (ParseException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to parse markup from " + markupResource), e);
}
catch (MarkupException e)
{
throw new MarkupException(markupResource, exceptionMessage(e.getMessage()));
}
catch (ResourceNotFoundException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to find markup from " + markupResource), e);
}
catch (IOException e)
{
throw new MarkupException(markupResource,
exceptionMessage("Unable to read markup from " + markupResource), e);
}
}
/**
* @return Key that uniquely identifies any markup that might be associated
* with this markup container.
*/
private String markupKey()
{
return getClass().getName() + getLocale() + getStyle() + getMarkupType();
}
/**
* Optimize child name mapping.
*/
private void optimize()
{
if (optimizeChildMapsForSpace)
{
childForName = new MicroMap();
}
else
{
childForName = new HashMap();
}
}
/**
* Renders the next element of markup in the given markup stream.
*
* @param markupStream
* The markup stream
*/
private void renderNext(final MarkupStream markupStream)
{
// Get the current markup element
final MarkupElement element = markupStream.get();
// If it a tag like <wicket..> or <span wicket:id="..." >
if (element instanceof ComponentTag && !markupStream.atCloseTag())
{
// Get element as tag
final ComponentTag tag = (ComponentTag)element;
// Get component name
final String componentId = tag.getId();
// Get the component for the component name from the given container
final Component component = get(componentId);
// Failed to find it?
if (component != null)
{
component.render();
}
else
{
// 2nd try: all static name resolvers
final List componentResolvers = this.getApplication().getComponentResolvers();
final Iterator iter = componentResolvers.iterator();
while (iter.hasNext())
{
final IComponentResolver resolver = (IComponentResolver)iter.next();
if (resolver.resolve(this, markupStream, tag))
{
return;
}
}
// 3rd try: a subclass replacing resolveComponent()
MarkupContainer container = this;
while (container != null)
{
if (container.resolveComponent(markupStream, tag))
{
return;
}
container = container.findParent(MarkupContainer.class);
}
// No one was able to handle the component name
markupStream.throwMarkupException("Unable to find component named '"
+ componentId + "' in " + this);
}
}
else
{
// Render as raw markup
log.debug("Rendering raw markup");
getResponse().write(element.toString());
markupStream.next();
}
}
} | component iterator for transpartent removing with undo support
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@456255 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/java/wicket/MarkupContainer.java | component iterator for transpartent removing with undo support |
|
Java | apache-2.0 | 363f568b6de8c093d6669b45d29c804783c9f39e | 0 | google/guice,google/guice,google/guice,mcculls/guice,mcculls/guice,mcculls/guice | /*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.Element;
import java.util.List;
/**
* Abstract base class for creating an injector from module elements.
*
* <p>Extending classes must return {@code true} from any overridden {@code visit*()} methods, in
* order for the element processor to remove the handled element.
*
* @author [email protected] (Jesse Wilson)
*/
abstract class AbstractProcessor extends DefaultElementVisitor<Boolean> {
protected Errors errors;
protected InjectorImpl injector;
protected AbstractProcessor(Errors errors) {
this.errors = errors;
}
public void process(Iterable<InjectorShell> isolatedInjectorBuilders) {
for (InjectorShell injectorShell : isolatedInjectorBuilders) {
process(injectorShell.getInjector(), injectorShell.getElements());
}
}
public void process(InjectorImpl injector, List<Element> elements) {
Errors errorsAnyElement = this.errors;
this.injector = injector;
try {
elements.removeIf(
e -> {
this.errors = errorsAnyElement.withSource(e.getSource());
return e.acceptVisitor(this);
});
} finally {
this.errors = errorsAnyElement;
this.injector = null;
}
}
@Override
protected Boolean visitOther(Element element) {
return false;
}
}
| core/src/com/google/inject/internal/AbstractProcessor.java | /*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.internal;
import com.google.inject.spi.DefaultElementVisitor;
import com.google.inject.spi.Element;
import java.util.Iterator;
import java.util.List;
/**
* Abstract base class for creating an injector from module elements.
*
* <p>Extending classes must return {@code true} from any overridden {@code visit*()} methods, in
* order for the element processor to remove the handled element.
*
* @author [email protected] (Jesse Wilson)
*/
abstract class AbstractProcessor extends DefaultElementVisitor<Boolean> {
protected Errors errors;
protected InjectorImpl injector;
protected AbstractProcessor(Errors errors) {
this.errors = errors;
}
public void process(Iterable<InjectorShell> isolatedInjectorBuilders) {
for (InjectorShell injectorShell : isolatedInjectorBuilders) {
process(injectorShell.getInjector(), injectorShell.getElements());
}
}
public void process(InjectorImpl injector, List<Element> elements) {
Errors errorsAnyElement = this.errors;
this.injector = injector;
try {
for (Iterator<Element> i = elements.iterator(); i.hasNext(); ) {
Element element = i.next();
this.errors = errorsAnyElement.withSource(element.getSource());
Boolean allDone = element.acceptVisitor(this);
if (allDone) {
i.remove();
}
}
} finally {
this.errors = errorsAnyElement;
this.injector = null;
}
}
@Override
protected Boolean visitOther(Element element) {
return false;
}
}
| Fix quadratic behavior of AbstractProcessor.process() observed in profiles.
The received lists are always ArrayList, for which removing items one-by-one
from the left is inefficient.
This changes the behavior on exception. Unlike std::remove_if,
ArrayList.removeIf() buffers all filter results before shifting any elements.
PiperOrigin-RevId: 347469725
| core/src/com/google/inject/internal/AbstractProcessor.java | Fix quadratic behavior of AbstractProcessor.process() observed in profiles. The received lists are always ArrayList, for which removing items one-by-one from the left is inefficient. |
|
Java | apache-2.0 | 3775e1245dbd9eaabef6eb56554f4426ffca8d01 | 0 | huitseeker/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j,huitseeker/deeplearning4j,dmmiller612/deeplearning4j,kinbod/deeplearning4j,dmmiller612/deeplearning4j | package org.deeplearning4j.gradientcheck;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.distribution.UniformDistribution;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.LossLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.SoftMax;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.linalg.lossfunctions.impl.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Alex on 12/09/2016.
*/
@Slf4j
public class LossFunctionGradientCheck {
private static final boolean PRINT_RESULTS = true;
private static final boolean RETURN_ON_FIRST_FAILURE = false;
private static final double DEFAULT_EPS = 1e-6;
private static final double DEFAULT_MAX_REL_ERROR = 1e-5;
private static final double DEFAULT_MIN_ABS_ERROR = 1e-8;
@Test
public void lossFunctionGradientCheck(){
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(),
new LossBinaryXENT(),
new LossCosineProximity(),
new LossHinge(),
new LossKLD(),
new LossKLD(),
new LossL1(),
new LossL1(),
new LossL1(),
new LossL2(),
new LossL2(),
new LossMAE(),
new LossMAE(),
new LossMAPE(),
new LossMAPE(),
new LossMCXENT(),
new LossMSE(),
new LossMSE(),
new LossMSLE(),
new LossMSLE(),
new LossNegativeLogLikelihood(),
new LossNegativeLogLikelihood(),
new LossPoisson(),
new LossSquaredHinge()
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"sigmoid", //xent
"tanh", //cosine
"tanh", //hinge -> trying to predict 1 or -1
"sigmoid", //kld -> probab so should be between 0 and 1
"softmax", //kld + softmax
"tanh", //l1
"rationaltanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
"sigmoid", //poisson - requires positive predictions due to log... not sure if this is the best option
"tanh" //squared hinge
};
int[] nOut = new int[]{
1, //xent
3, //xent
5, //cosine
3, //hinge
3, //kld
3, //kld + softmax
3, //l1
3, //l1
3, //l1 + softmax
3, //l2
3, //l2 + softmax
3, //mae
3, //mae + softmax
3, //mape
3, //mape + softmax
3, //mcxent
3, //mse
3, //mse + softmax
3, //msle
3, //msle + softmax
3, //nll
3, //nll + softmax
3, //poisson
3 //squared hinge
};
int[] minibatchSizes = new int[]{1, 3};
// int[] minibatchSizes = new int[]{3};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for( int i=0; i<lossFunctions.length; i++ ){
for( int j=0; j<minibatchSizes.length; j++ ) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j];
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-2, 2))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(4).activation("tanh").build())
.layer(1, new OutputLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.nIn(4).nOut(nOut[i])
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, nOut[i], 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try{
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch(Exception e){
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if(gradOK){
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
System.out.println("---- Passed ----");
for(String s : passed){
System.out.println(s);
}
System.out.println("---- Failed ----");
for(String s : failed){
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
@Test
public void lossFunctionGradientCheckLossLayer(){
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(),
new LossBinaryXENT(),
new LossCosineProximity(),
new LossHinge(),
new LossKLD(),
new LossKLD(),
new LossL1(),
new LossL1(),
new LossL2(),
new LossL2(),
new LossMAE(),
new LossMAE(),
new LossMAPE(),
new LossMAPE(),
new LossMCXENT(),
new LossMSE(),
new LossMSE(),
new LossMSLE(),
new LossMSLE(),
new LossNegativeLogLikelihood(),
new LossNegativeLogLikelihood(),
new LossPoisson(),
new LossSquaredHinge()
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"sigmoid", //xent
"tanh", //cosine
"tanh", //hinge -> trying to predict 1 or -1
"sigmoid", //kld -> probab so should be between 0 and 1
"softmax", //kld + softmax
"tanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
"sigmoid", //poisson - requires positive predictions due to log... not sure if this is the best option
"tanh" //squared hinge
};
int[] nOut = new int[]{
1, //xent
3, //xent
5, //cosine
3, //hinge
3, //kld
3, //kld + softmax
3, //l1
3, //l1 + softmax
3, //l2
3, //l2 + softmax
3, //mae
3, //mae + softmax
3, //mape
3, //mape + softmax
3, //mcxent
3, //mse
3, //mse + softmax
3, //msle
3, //msle + softmax
3, //nll
3, //nll + softmax
3, //poisson
3 //squared hinge
};
int[] minibatchSizes = new int[]{1, 3};
// int[] minibatchSizes = new int[]{3};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for( int i=0; i<lossFunctions.length; i++ ){
for( int j=0; j<minibatchSizes.length; j++ ) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j];
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-2, 2))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(nOut[i]).activation("tanh").build())
.layer(1, new LossLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
assertTrue(((LossLayer)net.getLayer(1).conf().getLayer()).getLossFn().getClass() == lossFunctions[i].getClass());
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, nOut[i], 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try{
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch(Exception e){
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if(gradOK){
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
System.out.println("---- Passed ----");
for(String s : passed){
System.out.println(s);
}
System.out.println("---- Failed ----");
for(String s : failed){
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
private static INDArray[] getFeaturesAndLabels(ILossFunction l, int minibatch, int nIn, int nOut, long seed){
Nd4j.getRandom().setSeed(seed);
Random r = new Random(seed);
INDArray[] ret = new INDArray[2];
ret[0] = Nd4j.rand(minibatch, nIn);
switch(l.getClass().getSimpleName()){
case "LossBinaryXENT":
//Want binary vector labels
ret[1] = Nd4j.rand(minibatch, nOut);
BooleanIndexing.replaceWhere(ret[1],0, Conditions.lessThanOrEqual(0.5));
BooleanIndexing.replaceWhere(ret[1],1, Conditions.greaterThanOrEqual(0.5));
break;
case "LossCosineProximity":
//Should be real-valued??
ret[1] = Nd4j.rand(minibatch, nOut).subi(0.5);
break;
case "LossKLD":
//KL divergence: should be a probability distribution for labels??
ret[1] = Nd4j.rand(minibatch, nOut);
Nd4j.getExecutioner().exec(new SoftMax(ret[1]),1);
break;
case "LossMCXENT":
case "LossNegativeLogLikelihood":
ret[1] = Nd4j.zeros(minibatch, nOut);
for( int i=0; i<minibatch; i++ ){
ret[1].putScalar(i, r.nextInt(nOut), 1.0);
}
break;
case "LossHinge":
case "LossSquaredHinge":
ret[1] = Nd4j.ones(minibatch, nOut);
for( int i=0; i<minibatch; i++ ){
ret[1].putScalar(i, r.nextInt(nOut), -1.0);
}
break;
case "LossMAPE":
//requires non-zero values for actual...
ret[1] = Nd4j.rand(minibatch, nOut).addi(1.0); //1 to 2
break;
case "LossMAE":
case "LossMSE":
case "LossL1":
case "LossL2":
ret[1] = Nd4j.rand(minibatch, nOut).muli(2).subi(1);
break;
case "LossMSLE":
//Requires positive labels/activations due to log
ret[1] = Nd4j.rand(minibatch, nOut);
break;
case "LossPoisson":
//Binary vector labels should be OK here??
ret[1] = Nd4j.rand(minibatch, nOut);
BooleanIndexing.replaceWhere(ret[1],0, Conditions.lessThanOrEqual(0.5));
BooleanIndexing.replaceWhere(ret[1],1, Conditions.greaterThanOrEqual(0.5));
break;
default:
throw new IllegalArgumentException("Unknown class: " + l.getClass().getSimpleName());
}
return ret;
}
@Test
public void lossFunctionWeightedGradientCheck() {
INDArray[] weights = new INDArray[]{
Nd4j.create(new double[]{0.2, 0.3, 0.5}),
Nd4j.create(new double[]{1.0, 0.5, 2.0})};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for (INDArray w : weights) {
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(w),
new LossL1(w),
new LossL1(w),
new LossL2(w),
new LossL2(w),
new LossMAE(w),
new LossMAE(w),
new LossMAPE(w),
new LossMAPE(w),
new LossMCXENT(w),
new LossMSE(w),
new LossMSE(w),
new LossMSLE(w),
new LossMSLE(w),
new LossNegativeLogLikelihood(w),
new LossNegativeLogLikelihood(w),
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"tanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
};
int[] minibatchSizes = new int[]{1, 3};
for (int i = 0; i < lossFunctions.length; i++) {
for (int j = 0; j < minibatchSizes.length; j++) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j] + "; weights = " + w;
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-3, 3))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(4).activation("tanh").build())
.layer(1, new OutputLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.nIn(4).nOut(3)
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, 3, 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try {
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch (Exception e) {
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if (gradOK) {
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
}
System.out.println("---- Passed ----");
for (String s : passed) {
System.out.println(s);
}
System.out.println("---- Failed ----");
for (String s : failed) {
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
}
| deeplearning4j-core/src/test/java/org/deeplearning4j/gradientcheck/LossFunctionGradientCheck.java | package org.deeplearning4j.gradientcheck;
import lombok.extern.slf4j.Slf4j;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.distribution.NormalDistribution;
import org.deeplearning4j.nn.conf.distribution.UniformDistribution;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.LossLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.SoftMax;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.indexing.BooleanIndexing;
import org.nd4j.linalg.indexing.conditions.Conditions;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.linalg.lossfunctions.impl.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by Alex on 12/09/2016.
*/
@Slf4j
public class LossFunctionGradientCheck {
private static final boolean PRINT_RESULTS = true;
private static final boolean RETURN_ON_FIRST_FAILURE = false;
private static final double DEFAULT_EPS = 1e-6;
private static final double DEFAULT_MAX_REL_ERROR = 1e-5;
private static final double DEFAULT_MIN_ABS_ERROR = 1e-8;
@Test
public void lossFunctionGradientCheck(){
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(),
new LossBinaryXENT(),
new LossCosineProximity(),
new LossHinge(),
new LossKLD(),
new LossKLD(),
new LossL1(),
new LossL1(),
new LossL2(),
new LossL2(),
new LossMAE(),
new LossMAE(),
new LossMAPE(),
new LossMAPE(),
new LossMCXENT(),
new LossMSE(),
new LossMSE(),
new LossMSLE(),
new LossMSLE(),
new LossNegativeLogLikelihood(),
new LossNegativeLogLikelihood(),
new LossPoisson(),
new LossSquaredHinge()
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"sigmoid", //xent
"tanh", //cosine
"tanh", //hinge -> trying to predict 1 or -1
"sigmoid", //kld -> probab so should be between 0 and 1
"softmax", //kld + softmax
"tanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
"sigmoid", //poisson - requires positive predictions due to log... not sure if this is the best option
"tanh" //squared hinge
};
int[] nOut = new int[]{
1, //xent
3, //xent
5, //cosine
3, //hinge
3, //kld
3, //kld + softmax
3, //l1
3, //l1 + softmax
3, //l2
3, //l2 + softmax
3, //mae
3, //mae + softmax
3, //mape
3, //mape + softmax
3, //mcxent
3, //mse
3, //mse + softmax
3, //msle
3, //msle + softmax
3, //nll
3, //nll + softmax
3, //poisson
3 //squared hinge
};
int[] minibatchSizes = new int[]{1, 3};
// int[] minibatchSizes = new int[]{3};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for( int i=0; i<lossFunctions.length; i++ ){
for( int j=0; j<minibatchSizes.length; j++ ) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j];
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-2, 2))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(4).activation("tanh").build())
.layer(1, new OutputLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.nIn(4).nOut(nOut[i])
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, nOut[i], 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try{
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch(Exception e){
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if(gradOK){
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
System.out.println("---- Passed ----");
for(String s : passed){
System.out.println(s);
}
System.out.println("---- Failed ----");
for(String s : failed){
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
@Test
public void lossFunctionGradientCheckLossLayer(){
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(),
new LossBinaryXENT(),
new LossCosineProximity(),
new LossHinge(),
new LossKLD(),
new LossKLD(),
new LossL1(),
new LossL1(),
new LossL2(),
new LossL2(),
new LossMAE(),
new LossMAE(),
new LossMAPE(),
new LossMAPE(),
new LossMCXENT(),
new LossMSE(),
new LossMSE(),
new LossMSLE(),
new LossMSLE(),
new LossNegativeLogLikelihood(),
new LossNegativeLogLikelihood(),
new LossPoisson(),
new LossSquaredHinge()
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"sigmoid", //xent
"tanh", //cosine
"tanh", //hinge -> trying to predict 1 or -1
"sigmoid", //kld -> probab so should be between 0 and 1
"softmax", //kld + softmax
"tanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
"sigmoid", //poisson - requires positive predictions due to log... not sure if this is the best option
"tanh" //squared hinge
};
int[] nOut = new int[]{
1, //xent
3, //xent
5, //cosine
3, //hinge
3, //kld
3, //kld + softmax
3, //l1
3, //l1 + softmax
3, //l2
3, //l2 + softmax
3, //mae
3, //mae + softmax
3, //mape
3, //mape + softmax
3, //mcxent
3, //mse
3, //mse + softmax
3, //msle
3, //msle + softmax
3, //nll
3, //nll + softmax
3, //poisson
3 //squared hinge
};
int[] minibatchSizes = new int[]{1, 3};
// int[] minibatchSizes = new int[]{3};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for( int i=0; i<lossFunctions.length; i++ ){
for( int j=0; j<minibatchSizes.length; j++ ) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j];
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-2, 2))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(nOut[i]).activation("tanh").build())
.layer(1, new LossLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
assertTrue(((LossLayer)net.getLayer(1).conf().getLayer()).getLossFn().getClass() == lossFunctions[i].getClass());
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, nOut[i], 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try{
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch(Exception e){
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if(gradOK){
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
System.out.println("---- Passed ----");
for(String s : passed){
System.out.println(s);
}
System.out.println("---- Failed ----");
for(String s : failed){
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
private static INDArray[] getFeaturesAndLabels(ILossFunction l, int minibatch, int nIn, int nOut, long seed){
Nd4j.getRandom().setSeed(seed);
Random r = new Random(seed);
INDArray[] ret = new INDArray[2];
ret[0] = Nd4j.rand(minibatch, nIn);
switch(l.getClass().getSimpleName()){
case "LossBinaryXENT":
//Want binary vector labels
ret[1] = Nd4j.rand(minibatch, nOut);
BooleanIndexing.replaceWhere(ret[1],0, Conditions.lessThanOrEqual(0.5));
BooleanIndexing.replaceWhere(ret[1],1, Conditions.greaterThanOrEqual(0.5));
break;
case "LossCosineProximity":
//Should be real-valued??
ret[1] = Nd4j.rand(minibatch, nOut).subi(0.5);
break;
case "LossKLD":
//KL divergence: should be a probability distribution for labels??
ret[1] = Nd4j.rand(minibatch, nOut);
Nd4j.getExecutioner().exec(new SoftMax(ret[1]),1);
break;
case "LossMCXENT":
case "LossNegativeLogLikelihood":
ret[1] = Nd4j.zeros(minibatch, nOut);
for( int i=0; i<minibatch; i++ ){
ret[1].putScalar(i, r.nextInt(nOut), 1.0);
}
break;
case "LossHinge":
case "LossSquaredHinge":
ret[1] = Nd4j.ones(minibatch, nOut);
for( int i=0; i<minibatch; i++ ){
ret[1].putScalar(i, r.nextInt(nOut), -1.0);
}
break;
case "LossMAPE":
//requires non-zero values for actual...
ret[1] = Nd4j.rand(minibatch, nOut).addi(1.0); //1 to 2
break;
case "LossMAE":
case "LossMSE":
case "LossL1":
case "LossL2":
ret[1] = Nd4j.rand(minibatch, nOut).muli(2).subi(1);
break;
case "LossMSLE":
//Requires positive labels/activations due to log
ret[1] = Nd4j.rand(minibatch, nOut);
break;
case "LossPoisson":
//Binary vector labels should be OK here??
ret[1] = Nd4j.rand(minibatch, nOut);
BooleanIndexing.replaceWhere(ret[1],0, Conditions.lessThanOrEqual(0.5));
BooleanIndexing.replaceWhere(ret[1],1, Conditions.greaterThanOrEqual(0.5));
break;
default:
throw new IllegalArgumentException("Unknown class: " + l.getClass().getSimpleName());
}
return ret;
}
@Test
public void lossFunctionWeightedGradientCheck() {
INDArray[] weights = new INDArray[]{
Nd4j.create(new double[]{0.2, 0.3, 0.5}),
Nd4j.create(new double[]{1.0, 0.5, 2.0})};
List<String> passed = new ArrayList<>();
List<String> failed = new ArrayList<>();
for (INDArray w : weights) {
ILossFunction[] lossFunctions = new ILossFunction[]{
new LossBinaryXENT(w),
new LossL1(w),
new LossL1(w),
new LossL2(w),
new LossL2(w),
new LossMAE(w),
new LossMAE(w),
new LossMAPE(w),
new LossMAPE(w),
new LossMCXENT(w),
new LossMSE(w),
new LossMSE(w),
new LossMSLE(w),
new LossMSLE(w),
new LossNegativeLogLikelihood(w),
new LossNegativeLogLikelihood(w),
};
String[] outputActivationFn = new String[]{
"sigmoid", //xent
"tanh", //l1
"softmax", //l1 + softmax
"tanh", //l2
"softmax", //l2 + softmax
"identity", //mae
"softmax", //mae + softmax
"identity", //mape
"softmax", //mape + softmax
"softmax", //mcxent
"identity", //mse
"softmax", //mse + softmax
"sigmoid", //msle - requires positive labels/activations due to log
"softmax", //msle + softmax
"sigmoid", //nll
"softmax", //nll + softmax
};
int[] minibatchSizes = new int[]{1, 3};
for (int i = 0; i < lossFunctions.length; i++) {
for (int j = 0; j < minibatchSizes.length; j++) {
String testName = lossFunctions[i] + " - " + outputActivationFn[i] + " - minibatchSize = " + minibatchSizes[j] + "; weights = " + w;
Nd4j.getRandom().setSeed(12345);
MultiLayerConfiguration conf = new NeuralNetConfiguration.Builder()
.iterations(1).optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.seed(12345)
.updater(Updater.NONE)
.regularization(false)
.weightInit(WeightInit.DISTRIBUTION).dist(new UniformDistribution(-3, 3))
.list()
.layer(0, new DenseLayer.Builder().nIn(4).nOut(4).activation("tanh").build())
.layer(1, new OutputLayer.Builder()
.lossFunction(lossFunctions[i])
.activation(outputActivationFn[i])
.nIn(4).nOut(3)
.build())
.pretrain(false).backprop(true).build();
MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
INDArray[] inOut = getFeaturesAndLabels(lossFunctions[i], minibatchSizes[j], 4, 3, 12345);
INDArray input = inOut[0];
INDArray labels = inOut[1];
log.info(" ***** Starting test: {} *****", testName);
// System.out.println(Arrays.toString(labels.data().asDouble()));
// System.out.println(Arrays.toString(net.output(input,false).data().asDouble()));
// System.out.println(net.score(new DataSet(input,labels)));
boolean gradOK;
try {
gradOK = GradientCheckUtil.checkGradients(net, DEFAULT_EPS, DEFAULT_MAX_REL_ERROR, DEFAULT_MIN_ABS_ERROR,
PRINT_RESULTS, RETURN_ON_FIRST_FAILURE, input, labels);
} catch (Exception e) {
e.printStackTrace();
failed.add(testName + "\t" + "EXCEPTION");
continue;
}
if (gradOK) {
passed.add(testName);
} else {
failed.add(testName);
}
System.out.println("\n\n");
}
}
}
System.out.println("---- Passed ----");
for (String s : passed) {
System.out.println(s);
}
System.out.println("---- Failed ----");
for (String s : failed) {
System.out.println(s);
}
assertEquals("Tests failed", 0, failed.size());
}
}
| rational tanh activation
Former-commit-id: 27d47c9913759903dbfe031d067e554226990fd5 | deeplearning4j-core/src/test/java/org/deeplearning4j/gradientcheck/LossFunctionGradientCheck.java | rational tanh activation |
|
Java | apache-2.0 | a70da4bea617b2fb57f33299db8be11ebea0e9d5 | 0 | cushon/error-prone,cushon/error-prone,google/error-prone,google/error-prone,cushon/error-prone,cushon/error-prone | /*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
import java.util.Objects;
/**
* Check for calls to Objects' {@link Objects#hashCode} with a primitive parameter.
*
* @author [email protected] (Sabrina Seibel)
*/
@BugPattern(
name = "ObjectsHashCodePrimitive",
summary = "Objects.hashCode(Object o) should not be passed a primitive value",
severity = WARNING,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class ObjectsHashCodePrimitive extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> OBJECTS_HASHCODE_CALLS =
allOf(
staticMethod().onClass("java.util.Objects").named("hashCode"),
argument(0, isPrimitiveType()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return OBJECTS_HASHCODE_CALLS.matches(tree, state)
? describeMatch(tree, adjustHashCodeCall(tree, state))
: Description.NO_MATCH;
}
private static Fix adjustHashCodeCall(MethodInvocationTree tree, VisitorState state) {
String argumentClass =
state
.getTypes()
.boxedTypeOrType(ASTHelpers.getType(tree.getArguments().get(0)))
.tsym
.getSimpleName()
.toString();
return SuggestedFix.builder()
.prefixWith(tree, argumentClass + ".hashCode(")
.replace(tree, state.getSourceForNode(tree.getArguments().get(0)))
.postfixWith(tree, ")")
.build();
}
}
| core/src/main/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitive.java | /*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.argument;
import static com.google.errorprone.matchers.Matchers.isPrimitiveType;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.ProvidesFix;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
import java.util.Objects;
/**
* Check for calls to Objects' {@link Objects#hashCode} with a primitive parameter.
*
* @author [email protected] (Sabrina Seibel)
*/
@BugPattern(
name = "ObjectsHashCodePrimitive",
summary = "Objects.hashCode(Object o) should not be passed a primitive value",
explanation =
"When Objects.hashCode(Object o) is given a primitive parameter,"
+ "it calls the primitive type's valueOf() function and gets that hashCode instead of "
+ "getting a unique hashcode for that parameter. Instead, we want the primitive value "
+ "to be treated as an Object and thus receive a unique hashcode.",
severity = WARNING,
providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION)
public final class ObjectsHashCodePrimitive extends BugChecker
implements MethodInvocationTreeMatcher {
private static final Matcher<MethodInvocationTree> OBJECTS_HASHCODE_CALLS =
allOf(
staticMethod().onClass("java.util.Objects").named("hashCode"),
argument(0, isPrimitiveType()));
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return OBJECTS_HASHCODE_CALLS.matches(tree, state)
? describeMatch(tree, adjustHashCodeCall(tree, state))
: Description.NO_MATCH;
}
private static Fix adjustHashCodeCall(MethodInvocationTree tree, VisitorState state) {
String argumentClass =
state
.getTypes()
.boxedTypeOrType(ASTHelpers.getType(tree.getArguments().get(0)))
.tsym
.getSimpleName()
.toString();
return SuggestedFix.builder()
.prefixWith(tree, argumentClass + ".hashCode(")
.replace(tree, state.getSourceForNode(tree.getArguments().get(0)))
.postfixWith(tree, ")")
.build();
}
}
| Remove explanation annotation element from ObjectsHashCodePrimitive (it has a sidecar explanation file).
RELNOTES: n/a
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=202336105
| core/src/main/java/com/google/errorprone/bugpatterns/ObjectsHashCodePrimitive.java | Remove explanation annotation element from ObjectsHashCodePrimitive (it has a sidecar explanation file). |
|
Java | apache-2.0 | 1b9367d465dc99559b4ac36b30be5e2e98ff67a7 | 0 | amyvmiwei/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,justintung/hbase,gustavoanatoly/hbase,gustavoanatoly/hbase,apurtell/hbase,apurtell/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,mahak/hbase,ultratendency/hbase,apurtell/hbase,ultratendency/hbase,vincentpoon/hbase,JingchengDu/hbase,ultratendency/hbase,andrewmains12/hbase,ChinmaySKulkarni/hbase,amyvmiwei/hbase,justintung/hbase,HubSpot/hbase,juwi/hbase,ultratendency/hbase,francisliu/hbase,lshmouse/hbase,ndimiduk/hbase,Eshcar/hbase,ndimiduk/hbase,Eshcar/hbase,joshelser/hbase,ndimiduk/hbase,joshelser/hbase,andrewmains12/hbase,mahak/hbase,joshelser/hbase,juwi/hbase,amyvmiwei/hbase,SeekerResource/hbase,HubSpot/hbase,Eshcar/hbase,StackVista/hbase,justintung/hbase,apurtell/hbase,Apache9/hbase,gustavoanatoly/hbase,justintung/hbase,vincentpoon/hbase,andrewmains12/hbase,ndimiduk/hbase,juwi/hbase,StackVista/hbase,juwi/hbase,ChinmaySKulkarni/hbase,Guavus/hbase,joshelser/hbase,SeekerResource/hbase,joshelser/hbase,lshmouse/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,justintung/hbase,HubSpot/hbase,StackVista/hbase,Guavus/hbase,andrewmains12/hbase,ultratendency/hbase,andrewmains12/hbase,ndimiduk/hbase,mahak/hbase,Guavus/hbase,francisliu/hbase,Eshcar/hbase,justintung/hbase,HubSpot/hbase,HubSpot/hbase,andrewmains12/hbase,Guavus/hbase,andrewmains12/hbase,lshmouse/hbase,joshelser/hbase,ChinmaySKulkarni/hbase,vincentpoon/hbase,bijugs/hbase,justintung/hbase,JingchengDu/hbase,StackVista/hbase,SeekerResource/hbase,apurtell/hbase,narendragoyal/hbase,bijugs/hbase,juwi/hbase,StackVista/hbase,amyvmiwei/hbase,narendragoyal/hbase,JingchengDu/hbase,SeekerResource/hbase,JingchengDu/hbase,amyvmiwei/hbase,mahak/hbase,justintung/hbase,vincentpoon/hbase,StackVista/hbase,amyvmiwei/hbase,Eshcar/hbase,StackVista/hbase,andrewmains12/hbase,mahak/hbase,lshmouse/hbase,mahak/hbase,vincentpoon/hbase,mahak/hbase,ultratendency/hbase,ultratendency/hbase,Apache9/hbase,lshmouse/hbase,bijugs/hbase,bijugs/hbase,JingchengDu/hbase,bijugs/hbase,ChinmaySKulkarni/hbase,francisliu/hbase,francisliu/hbase,Eshcar/hbase,StackVista/hbase,SeekerResource/hbase,SeekerResource/hbase,gustavoanatoly/hbase,narendragoyal/hbase,lshmouse/hbase,apurtell/hbase,lshmouse/hbase,Apache9/hbase,ndimiduk/hbase,Guavus/hbase,bijugs/hbase,StackVista/hbase,Guavus/hbase,ndimiduk/hbase,Eshcar/hbase,Apache9/hbase,Guavus/hbase,gustavoanatoly/hbase,Guavus/hbase,joshelser/hbase,mahak/hbase,lshmouse/hbase,ultratendency/hbase,bijugs/hbase,Eshcar/hbase,francisliu/hbase,amyvmiwei/hbase,Guavus/hbase,juwi/hbase,narendragoyal/hbase,JingchengDu/hbase,lshmouse/hbase,bijugs/hbase,SeekerResource/hbase,StackVista/hbase,Guavus/hbase,JingchengDu/hbase,gustavoanatoly/hbase,gustavoanatoly/hbase,francisliu/hbase,ndimiduk/hbase,amyvmiwei/hbase,bijugs/hbase,narendragoyal/hbase,HubSpot/hbase,JingchengDu/hbase,vincentpoon/hbase,HubSpot/hbase,narendragoyal/hbase,ultratendency/hbase,JingchengDu/hbase,gustavoanatoly/hbase,SeekerResource/hbase,narendragoyal/hbase,narendragoyal/hbase,vincentpoon/hbase,ChinmaySKulkarni/hbase,juwi/hbase,JingchengDu/hbase,lshmouse/hbase,amyvmiwei/hbase,Apache9/hbase,andrewmains12/hbase,joshelser/hbase,SeekerResource/hbase,vincentpoon/hbase,ultratendency/hbase,vincentpoon/hbase,gustavoanatoly/hbase,francisliu/hbase,HubSpot/hbase,Apache9/hbase,francisliu/hbase,Eshcar/hbase,HubSpot/hbase,gustavoanatoly/hbase,SeekerResource/hbase,francisliu/hbase,amyvmiwei/hbase,apurtell/hbase,bijugs/hbase,juwi/hbase,Apache9/hbase,ChinmaySKulkarni/hbase,ndimiduk/hbase,joshelser/hbase,apurtell/hbase,narendragoyal/hbase,vincentpoon/hbase,mahak/hbase,juwi/hbase,joshelser/hbase,apurtell/hbase,justintung/hbase,mahak/hbase,justintung/hbase,ndimiduk/hbase,ChinmaySKulkarni/hbase,HubSpot/hbase,apurtell/hbase,Apache9/hbase,Apache9/hbase,narendragoyal/hbase,Eshcar/hbase | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.IOException;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.io.hfile.HFileScanner;
import org.apache.hadoop.hbase.util.Bytes;
/**
* This class runs performance benchmarks for {@link HFile}.
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
public class HFilePerformanceEvaluation {
private static final int ROW_LENGTH = 10;
private static final int ROW_COUNT = 1000000;
private static final int RFILE_BLOCKSIZE = 8 * 1024;
static final Log LOG =
LogFactory.getLog(HFilePerformanceEvaluation.class.getName());
static byte [] format(final int i) {
String v = Integer.toString(i);
return Bytes.toBytes("0000000000".substring(v.length()) + v);
}
static ImmutableBytesWritable format(final int i, ImmutableBytesWritable w) {
w.set(format(i));
return w;
}
static Cell createCell(final int i) {
return createCell(i, HConstants.EMPTY_BYTE_ARRAY);
}
/**
* HFile is Cell-based. It used to be byte arrays. Doing this test, pass Cells. All Cells
* intentionally have same coordinates in all fields but row.
* @param i Integer to format as a row Key.
* @param value Value to use
* @return Created Cell.
*/
static Cell createCell(final int i, final byte [] value) {
return createCell(format(i), value);
}
static Cell createCell(final byte [] keyRow) {
return CellUtil.createCell(keyRow);
}
static Cell createCell(final byte [] keyRow, final byte [] value) {
return CellUtil.createCell(keyRow, value);
}
private void runBenchmarks() throws Exception {
final Configuration conf = new Configuration();
final FileSystem fs = FileSystem.get(conf);
final Path mf = fs.makeQualified(new Path("performanceevaluation.mapfile"));
if (fs.exists(mf)) {
fs.delete(mf, true);
}
runBenchmark(new SequentialWriteBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new UniformRandomSmallScan(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new UniformRandomReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new GaussianRandomReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new SequentialReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
protected void runBenchmark(RowOrientedBenchmark benchmark, int rowCount)
throws Exception {
LOG.info("Running " + benchmark.getClass().getSimpleName() + " for " +
rowCount + " rows.");
long elapsedTime = benchmark.run();
LOG.info("Running " + benchmark.getClass().getSimpleName() + " for " +
rowCount + " rows took " + elapsedTime + "ms.");
}
static abstract class RowOrientedBenchmark {
protected final Configuration conf;
protected final FileSystem fs;
protected final Path mf;
protected final int totalRows;
public RowOrientedBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
this.conf = conf;
this.fs = fs;
this.mf = mf;
this.totalRows = totalRows;
}
void setUp() throws Exception {
// do nothing
}
abstract void doRow(int i) throws Exception;
protected int getReportingPeriod() {
return this.totalRows / 10;
}
void tearDown() throws Exception {
// do nothing
}
/**
* Run benchmark
* @return elapsed time.
* @throws Exception
*/
long run() throws Exception {
long elapsedTime;
setUp();
long startTime = System.currentTimeMillis();
try {
for (int i = 0; i < totalRows; i++) {
if (i > 0 && i % getReportingPeriod() == 0) {
LOG.info("Processed " + i + " rows.");
}
doRow(i);
}
elapsedTime = System.currentTimeMillis() - startTime;
} finally {
tearDown();
}
return elapsedTime;
}
}
static class SequentialWriteBenchmark extends RowOrientedBenchmark {
protected HFile.Writer writer;
private Random random = new Random();
private byte[] bytes = new byte[ROW_LENGTH];
public SequentialWriteBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
HFileContext hFileContext = new HFileContextBuilder().withBlockSize(RFILE_BLOCKSIZE).build();
writer =
HFile.getWriterFactoryNoCache(conf)
.withPath(fs, mf)
.withFileContext(hFileContext)
.withComparator(new KeyValue.RawBytesComparator())
.create();
}
@Override
void doRow(int i) throws Exception {
writer.append(createCell(i, generateValue()));
}
private byte[] generateValue() {
random.nextBytes(bytes);
return bytes;
}
@Override
protected int getReportingPeriod() {
return this.totalRows; // don't report progress
}
@Override
void tearDown() throws Exception {
writer.close();
}
}
static abstract class ReadBenchmark extends RowOrientedBenchmark {
protected HFile.Reader reader;
public ReadBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
reader = HFile.createReader(this.fs, this.mf, new CacheConfig(this.conf), this.conf);
this.reader.loadFileInfo();
}
@Override
void tearDown() throws Exception {
reader.close();
}
}
static class SequentialReadBenchmark extends ReadBenchmark {
private HFileScanner scanner;
public SequentialReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
super.setUp();
this.scanner = this.reader.getScanner(false, false);
this.scanner.seekTo();
}
@Override
void doRow(int i) throws Exception {
if (this.scanner.next()) {
// TODO: Fix. Make Scanner do Cells.
Cell c = this.scanner.getKeyValue();
PerformanceEvaluationCommons.assertKey(format(i + 1), c);
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
}
@Override
protected int getReportingPeriod() {
return this.totalRows; // don't report progress
}
}
static class UniformRandomReadBenchmark extends ReadBenchmark {
private Random random = new Random();
public UniformRandomReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, true);
byte [] b = getRandomRow();
if (scanner.seekTo(createCell(b)) < 0) {
LOG.info("Not able to seekTo " + new String(b));
return;
}
// TODO: Fix scanner so it does Cells
Cell c = scanner.getKeyValue();
PerformanceEvaluationCommons.assertKey(b, c);
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
private byte [] getRandomRow() {
return format(random.nextInt(totalRows));
}
}
static class UniformRandomSmallScan extends ReadBenchmark {
private Random random = new Random();
public UniformRandomSmallScan(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows/10);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, false);
byte [] b = getRandomRow();
// System.out.println("Random row: " + new String(b));
Cell c = createCell(b);
if (scanner.seekTo(c) != 0) {
LOG.info("Nonexistent row: " + new String(b));
return;
}
// TODO: HFileScanner doesn't do Cells yet. Temporary fix.
c = scanner.getKeyValue();
// System.out.println("Found row: " +
// new String(c.getRowArray(), c.getRowOffset(), c.getRowLength()));
PerformanceEvaluationCommons.assertKey(b, c);
for (int ii = 0; ii < 30; ii++) {
if (!scanner.next()) {
LOG.info("NOTHING FOLLOWS");
return;
}
c = scanner.getKeyValue();
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
}
private byte [] getRandomRow() {
return format(random.nextInt(totalRows));
}
}
static class GaussianRandomReadBenchmark extends ReadBenchmark {
private RandomData randomData = new RandomDataImpl();
public GaussianRandomReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, true);
byte[] gaussianRandomRowBytes = getGaussianRandomRowBytes();
scanner.seekTo(createCell(gaussianRandomRowBytes));
for (int ii = 0; ii < 30; ii++) {
if (!scanner.next()) {
LOG.info("NOTHING FOLLOWS");
return;
}
// TODO: Fix. Make scanner do Cells.
scanner.getKeyValue();
}
}
private byte [] getGaussianRandomRowBytes() {
int r = (int) randomData.nextGaussian((double)totalRows / 2.0,
(double)totalRows / 10.0);
// make sure r falls into [0,totalRows)
return format(Math.min(totalRows, Math.max(r,0)));
}
}
/**
* @param args
* @throws Exception
* @throws IOException
*/
public static void main(String[] args) throws Exception {
new HFilePerformanceEvaluation().runBenchmarks();
}
}
| hbase-server/src/test/java/org/apache/hadoop/hbase/HFilePerformanceEvaluation.java | /**
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import java.io.IOException;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.io.hfile.CacheConfig;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.io.hfile.HFileScanner;
import org.apache.hadoop.hbase.util.Bytes;
/**
* This class runs performance benchmarks for {@link HFile}.
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
public class HFilePerformanceEvaluation {
private static final int ROW_LENGTH = 10;
private static final int ROW_COUNT = 1000000;
private static final int RFILE_BLOCKSIZE = 8 * 1024;
static final Log LOG =
LogFactory.getLog(HFilePerformanceEvaluation.class.getName());
static byte [] format(final int i) {
String v = Integer.toString(i);
return Bytes.toBytes("0000000000".substring(v.length()) + v);
}
static ImmutableBytesWritable format(final int i, ImmutableBytesWritable w) {
w.set(format(i));
return w;
}
static Cell createCell(final int i) {
return createCell(i, HConstants.EMPTY_BYTE_ARRAY);
}
/**
* HFile is Cell-based. It used to be byte arrays. Doing this test, pass Cells. All Cells
* intentionally have same coordinates in all fields but row.
* @param i Integer to format as a row Key.
* @param value Value to use
* @return Created Cell.
*/
static Cell createCell(final int i, final byte [] value) {
return createCell(format(i), value);
}
static Cell createCell(final byte [] keyRow) {
return createCell(keyRow);
}
static Cell createCell(final byte [] keyRow, final byte [] value) {
return CellUtil.createCell(keyRow, value);
}
private void runBenchmarks() throws Exception {
final Configuration conf = new Configuration();
final FileSystem fs = FileSystem.get(conf);
final Path mf = fs.makeQualified(new Path("performanceevaluation.mapfile"));
if (fs.exists(mf)) {
fs.delete(mf, true);
}
runBenchmark(new SequentialWriteBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new UniformRandomSmallScan(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new UniformRandomReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new GaussianRandomReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
PerformanceEvaluationCommons.concurrentReads(new Runnable() {
@Override
public void run() {
try {
runBenchmark(new SequentialReadBenchmark(conf, fs, mf, ROW_COUNT),
ROW_COUNT);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
protected void runBenchmark(RowOrientedBenchmark benchmark, int rowCount)
throws Exception {
LOG.info("Running " + benchmark.getClass().getSimpleName() + " for " +
rowCount + " rows.");
long elapsedTime = benchmark.run();
LOG.info("Running " + benchmark.getClass().getSimpleName() + " for " +
rowCount + " rows took " + elapsedTime + "ms.");
}
static abstract class RowOrientedBenchmark {
protected final Configuration conf;
protected final FileSystem fs;
protected final Path mf;
protected final int totalRows;
public RowOrientedBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
this.conf = conf;
this.fs = fs;
this.mf = mf;
this.totalRows = totalRows;
}
void setUp() throws Exception {
// do nothing
}
abstract void doRow(int i) throws Exception;
protected int getReportingPeriod() {
return this.totalRows / 10;
}
void tearDown() throws Exception {
// do nothing
}
/**
* Run benchmark
* @return elapsed time.
* @throws Exception
*/
long run() throws Exception {
long elapsedTime;
setUp();
long startTime = System.currentTimeMillis();
try {
for (int i = 0; i < totalRows; i++) {
if (i > 0 && i % getReportingPeriod() == 0) {
LOG.info("Processed " + i + " rows.");
}
doRow(i);
}
elapsedTime = System.currentTimeMillis() - startTime;
} finally {
tearDown();
}
return elapsedTime;
}
}
static class SequentialWriteBenchmark extends RowOrientedBenchmark {
protected HFile.Writer writer;
private Random random = new Random();
private byte[] bytes = new byte[ROW_LENGTH];
public SequentialWriteBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
HFileContext hFileContext = new HFileContextBuilder().withBlockSize(RFILE_BLOCKSIZE).build();
writer =
HFile.getWriterFactoryNoCache(conf)
.withPath(fs, mf)
.withFileContext(hFileContext)
.withComparator(new KeyValue.RawBytesComparator())
.create();
}
@Override
void doRow(int i) throws Exception {
writer.append(createCell(i, generateValue()));
}
private byte[] generateValue() {
random.nextBytes(bytes);
return bytes;
}
@Override
protected int getReportingPeriod() {
return this.totalRows; // don't report progress
}
@Override
void tearDown() throws Exception {
writer.close();
}
}
static abstract class ReadBenchmark extends RowOrientedBenchmark {
protected HFile.Reader reader;
public ReadBenchmark(Configuration conf, FileSystem fs, Path mf,
int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
reader = HFile.createReader(this.fs, this.mf, new CacheConfig(this.conf), this.conf);
this.reader.loadFileInfo();
}
@Override
void tearDown() throws Exception {
reader.close();
}
}
static class SequentialReadBenchmark extends ReadBenchmark {
private HFileScanner scanner;
public SequentialReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void setUp() throws Exception {
super.setUp();
this.scanner = this.reader.getScanner(false, false);
this.scanner.seekTo();
}
@Override
void doRow(int i) throws Exception {
if (this.scanner.next()) {
// TODO: Fix. Make Scanner do Cells.
Cell c = this.scanner.getKeyValue();
PerformanceEvaluationCommons.assertKey(format(i + 1), c);
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
}
@Override
protected int getReportingPeriod() {
return this.totalRows; // don't report progress
}
}
static class UniformRandomReadBenchmark extends ReadBenchmark {
private Random random = new Random();
public UniformRandomReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, true);
byte [] b = getRandomRow();
if (scanner.seekTo(createCell(b)) < 0) {
LOG.info("Not able to seekTo " + new String(b));
return;
}
// TODO: Fix scanner so it does Cells
Cell c = scanner.getKeyValue();
PerformanceEvaluationCommons.assertKey(b, c);
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
private byte [] getRandomRow() {
return format(random.nextInt(totalRows));
}
}
static class UniformRandomSmallScan extends ReadBenchmark {
private Random random = new Random();
public UniformRandomSmallScan(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows/10);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, false);
byte [] b = getRandomRow();
// System.out.println("Random row: " + new String(b));
Cell c = createCell(b);
if (scanner.seekTo(c) != 0) {
LOG.info("Nonexistent row: " + new String(b));
return;
}
// TODO: HFileScanner doesn't do Cells yet. Temporary fix.
c = scanner.getKeyValue();
// System.out.println("Found row: " +
// new String(c.getRowArray(), c.getRowOffset(), c.getRowLength()));
PerformanceEvaluationCommons.assertKey(b, c);
for (int ii = 0; ii < 30; ii++) {
if (!scanner.next()) {
LOG.info("NOTHING FOLLOWS");
return;
}
c = scanner.getKeyValue();
PerformanceEvaluationCommons.assertValueSize(c.getValueLength(), ROW_LENGTH);
}
}
private byte [] getRandomRow() {
return format(random.nextInt(totalRows));
}
}
static class GaussianRandomReadBenchmark extends ReadBenchmark {
private RandomData randomData = new RandomDataImpl();
public GaussianRandomReadBenchmark(Configuration conf, FileSystem fs,
Path mf, int totalRows) {
super(conf, fs, mf, totalRows);
}
@Override
void doRow(int i) throws Exception {
HFileScanner scanner = this.reader.getScanner(false, true);
byte[] gaussianRandomRowBytes = getGaussianRandomRowBytes();
scanner.seekTo(createCell(gaussianRandomRowBytes));
for (int ii = 0; ii < 30; ii++) {
if (!scanner.next()) {
LOG.info("NOTHING FOLLOWS");
return;
}
// TODO: Fix. Make scanner do Cells.
scanner.getKeyValue();
}
}
private byte [] getGaussianRandomRowBytes() {
int r = (int) randomData.nextGaussian((double)totalRows / 2.0,
(double)totalRows / 10.0);
// make sure r falls into [0,totalRows)
return format(Math.min(totalRows, Math.max(r,0)));
}
}
/**
* @param args
* @throws Exception
* @throws IOException
*/
public static void main(String[] args) throws Exception {
new HFilePerformanceEvaluation().runBenchmarks();
}
}
| HBASE-12917 HFilePerformanceEvaluation Scan tests fail with StackOverflowError due to recursive call in createCell function (Vikas Vishwakarma)
| hbase-server/src/test/java/org/apache/hadoop/hbase/HFilePerformanceEvaluation.java | HBASE-12917 HFilePerformanceEvaluation Scan tests fail with StackOverflowError due to recursive call in createCell function (Vikas Vishwakarma) |
|
Java | apache-2.0 | d7c0e622689835974415388a5f93f324a9e623fc | 0 | apache/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,kalaspuffar/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationSquare;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* This unit test validates the correct working behavior of PDPage annotations
* filtering
*
* @author <a href="mailto:[email protected]">Maxime Veron</a>
*
*/
public class TestPDPageAnnotationsFiltering
{
// test mock page for annotations filtering
private PDPage page;
@Before
public void initMock()
{
COSDictionary mockedPageWithAnnotations = new COSDictionary();
COSArray annotsDictionnary = new COSArray();
annotsDictionnary.add(new PDAnnotationRubberStamp().getCOSObject());
annotsDictionnary.add(new PDAnnotationSquare().getCOSObject());
annotsDictionnary.add(new PDAnnotationLink().getCOSObject());
mockedPageWithAnnotations.setItem(COSName.ANNOTS, annotsDictionnary);
page = new PDPage(mockedPageWithAnnotations);
}
@Test
public void validateNoFiltering() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations();
Assert.assertEquals(3, annotations.size());
Assert.assertTrue(annotations.get(0) instanceof PDAnnotationRubberStamp);
Assert.assertTrue(annotations.get(1) instanceof PDAnnotationSquare);
Assert.assertTrue(annotations.get(2) instanceof PDAnnotationLink);
}
@Test
public void validateAllFiltered() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations(annotation -> false);
Assert.assertEquals(0, annotations.size());
}
@Test
public void validateSelectedFew() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations(annotation ->
(annotation instanceof PDAnnotationLink || annotation instanceof PDAnnotationSquare));
Assert.assertEquals(2, annotations.size());
Assert.assertTrue(annotations.get(0) instanceof PDAnnotationSquare);
Assert.assertTrue(annotations.get(1) instanceof PDAnnotationLink);
}
} | pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageAnnotationsFiltering.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.interactive.annotation.AnnotationFilter;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationRubberStamp;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationSquare;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* This unit test validates the correct working behavior of PDPage annotations
* filtering
*
* @author <a href="mailto:[email protected]">Maxime Veron</a>
*
*/
public class TestPDPageAnnotationsFiltering
{
// test mock page for annotations filtering
private PDPage page;
@Before
public void initMock()
{
COSDictionary mockedPageWithAnnotations = new COSDictionary();
COSArray annotsDictionnary = new COSArray();
annotsDictionnary.add(new PDAnnotationRubberStamp().getCOSObject());
annotsDictionnary.add(new PDAnnotationSquare().getCOSObject());
annotsDictionnary.add(new PDAnnotationLink().getCOSObject());
mockedPageWithAnnotations.setItem(COSName.ANNOTS, annotsDictionnary);
page = new PDPage(mockedPageWithAnnotations);
}
@Test
public void validateNoFiltering() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations();
Assert.assertEquals(3, annotations.size());
Assert.assertTrue(annotations.get(0) instanceof PDAnnotationRubberStamp);
Assert.assertTrue(annotations.get(1) instanceof PDAnnotationSquare);
Assert.assertTrue(annotations.get(2) instanceof PDAnnotationLink);
}
@Test
public void validateAllFiltered() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations(new AnnotationFilter()
{
@Override
public boolean accept(PDAnnotation annotation)
{
return false;
}
});
Assert.assertEquals(0, annotations.size());
}
@Test
public void validateSelectedFew() throws IOException
{
List<PDAnnotation> annotations = page.getAnnotations(new AnnotationFilter()
{
@Override
public boolean accept(PDAnnotation annotation)
{
return (annotation instanceof PDAnnotationLink || annotation instanceof PDAnnotationSquare);
}
});
Assert.assertEquals(2, annotations.size());
Assert.assertTrue(annotations.get(0) instanceof PDAnnotationSquare);
Assert.assertTrue(annotations.get(1) instanceof PDAnnotationLink);
}
} | PDFBOX-4071: use jdk8 lambda expressions
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1867428 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/test/java/org/apache/pdfbox/pdmodel/TestPDPageAnnotationsFiltering.java | PDFBOX-4071: use jdk8 lambda expressions |
|
Java | apache-2.0 | 5281ec9747aec02355cb47334c2b9c45f4a99353 | 0 | tensorflow/tflite-support,tensorflow/tflite-support,tensorflow/tflite-support,tensorflow/tflite-support,tensorflow/tflite-support,tensorflow/tflite-support | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.lite.task.vision.segmenter;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.os.ParcelFileDescriptor;
import com.google.auto.value.AutoValue;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.task.core.TaskJniUtils;
import org.tensorflow.lite.task.core.TaskJniUtils.EmptyHandleProvider;
import org.tensorflow.lite.task.core.vision.ImageProcessingOptions;
import org.tensorflow.lite.task.vision.core.BaseVisionTaskApi;
import org.tensorflow.lite.task.vision.core.BaseVisionTaskApi.InferenceProvider;
/**
* Performs segmentation on images.
*
* <p>The API expects a TFLite model with <a
* href="https://www.tensorflow.org/lite/convert/metadata">TFLite Model Metadata.</a>.
*
* <p>The API supports models with one image input tensor and one output tensor. To be more
* specific, here are the requirements.
*
* <ul>
* <li>Input image tensor ({@code kTfLiteUInt8}/{@code kTfLiteFloat32})
* <ul>
* <li>image input of size {@code [batch x height x width x channels]}.
* <li>batch inference is not supported ({@code batch} is required to be 1).
* <li>only RGB inputs are supported ({@code channels} is required to be 3).
* <li>if type is {@code kTfLiteFloat32}, NormalizationOptions are required to be attached
* to the metadata for input normalization.
* </ul>
* <li>Output image tensor ({@code kTfLiteUInt8}/{@code kTfLiteFloat32})
* <ul>
* <li>tensor of size {@code [batch x mask_height x mask_width x num_classes]}, where {@code
* batch} is required to be 1, {@code mask_width} and {@code mask_height} are the
* dimensions of the segmentation masks produced by the model, and {@code num_classes}
* is the number of classes supported by the model.
* <li>optional (but recommended) label map(s) can be attached as AssociatedFile-s with type
* TENSOR_AXIS_LABELS, containing one label per line. The first such AssociatedFile (if
* any) is used to fill the class name, i.e. {@link ColoredLabel#getlabel} of the
* results. The display name, i.e. {@link ColoredLabel#getDisplayName}, is filled from
* the AssociatedFile (if any) whose locale matches the `display_names_locale` field of
* the `ImageSegmenterOptions` used at creation time ("en" by default, i.e. English). If
* none of these are available, only the `index` field of the results will be filled.
* </ul>
* </ul>
*
* <p>An example of such model can be found on <a
* href="https://tfhub.dev/tensorflow/lite-model/deeplabv3/1/metadata/1">TensorFlow Hub.</a>.
*/
public final class ImageSegmenter extends BaseVisionTaskApi {
private static final String IMAGE_SEGMENTER_NATIVE_LIB = "task_vision_jni";
private static final int OPTIONAL_FD_LENGTH = -1;
private static final int OPTIONAL_FD_OFFSET = -1;
private final OutputType outputType;
/**
* Creates an {@link ImageSegmenter} instance from the default {@link ImageSegmenterOptions}.
*
* @param modelPath path of the segmentation model with metadata in the assets
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFile(Context context, String modelPath)
throws IOException {
return createFromFileAndOptions(context, modelPath, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance from the default {@link ImageSegmenterOptions}.
*
* @param modelFile the segmentation model {@link File} instance
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFile(File modelFile) throws IOException {
return createFromFileAndOptions(modelFile, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance with a model buffer and the default {@link
* ImageSegmenterOptions}.
*
* @param modelBuffer a direct {@link ByteBuffer} or a {@link MappedByteBuffer} of the
* segmentation model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
* @throws IllegalArgumentException if the model buffer is not a direct {@link ByteBuffer} or a
* {@link MappedByteBuffer}
*/
public static ImageSegmenter createFromBuffer(final ByteBuffer modelBuffer) {
return createFromBufferAndOptions(modelBuffer, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance from {@link ImageSegmenterOptions}.
*
* @param modelPath path of the segmentation model with metadata in the assets
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFileAndOptions(
Context context, String modelPath, final ImageSegmenterOptions options) throws IOException {
try (AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(modelPath)) {
return createFromModelFdAndOptions(
/*fileDescriptor=*/ assetFileDescriptor.getParcelFileDescriptor().getFd(),
/*fileDescriptorLength=*/ assetFileDescriptor.getLength(),
/*fileDescriptorOffset=*/ assetFileDescriptor.getStartOffset(),
options);
}
}
/**
* Creates an {@link ImageSegmenter} instance from {@link ImageSegmenterOptions}.
*
* @param modelFile the segmentation model {@link File} instance
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFileAndOptions(
File modelFile, final ImageSegmenterOptions options) throws IOException {
try (ParcelFileDescriptor descriptor =
ParcelFileDescriptor.open(modelFile, ParcelFileDescriptor.MODE_READ_ONLY)) {
return createFromModelFdAndOptions(
/*fileDescriptor=*/ descriptor.getFd(),
/*fileDescriptorLength=*/ OPTIONAL_FD_LENGTH,
/*fileDescriptorOffset=*/ OPTIONAL_FD_OFFSET,
options);
}
}
/**
* Creates an {@link ImageSegmenter} instance with a model buffer and {@link
* ImageSegmenterOptions}.
*
* @param modelBuffer a direct {@link ByteBuffer} or a {@link MappedByteBuffer} of the
* segmentation model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
* @throws IllegalArgumentException if the model buffer is not a direct {@link ByteBuffer} or a
* {@link MappedByteBuffer}
*/
public static ImageSegmenter createFromBufferAndOptions(
final ByteBuffer modelBuffer, final ImageSegmenterOptions options) {
if (!(modelBuffer.isDirect() || modelBuffer instanceof MappedByteBuffer)) {
throw new IllegalArgumentException(
"The model buffer should be either a direct ByteBuffer or a MappedByteBuffer.");
}
return new ImageSegmenter(
TaskJniUtils.createHandleFromLibrary(
new EmptyHandleProvider() {
@Override
public long createHandle() {
return initJniWithByteBuffer(
modelBuffer,
options.getDisplayNamesLocale(),
options.getOutputType().getValue(),
options.getNumThreads());
}
},
IMAGE_SEGMENTER_NATIVE_LIB),
options.getOutputType());
}
/**
* Constructor to initialize the JNI with a pointer from C++.
*
* @param nativeHandle a pointer referencing memory allocated in C++
*/
private ImageSegmenter(long nativeHandle, OutputType outputType) {
super(nativeHandle);
this.outputType = outputType;
}
/** Options for setting up an {@link ImageSegmenter}. */
@AutoValue
public abstract static class ImageSegmenterOptions {
private static final String DEFAULT_DISPLAY_NAME_LOCALE = "en";
private static final OutputType DEFAULT_OUTPUT_TYPE = OutputType.CATEGORY_MASK;
private static final int NUM_THREADS = -1;
public abstract String getDisplayNamesLocale();
public abstract OutputType getOutputType();
public abstract int getNumThreads();
public static Builder builder() {
return new AutoValue_ImageSegmenter_ImageSegmenterOptions.Builder()
.setDisplayNamesLocale(DEFAULT_DISPLAY_NAME_LOCALE)
.setOutputType(DEFAULT_OUTPUT_TYPE)
.setNumThreads(NUM_THREADS);
}
/** Builder for {@link ImageSegmenterOptions}. */
@AutoValue.Builder
public abstract static class Builder {
/**
* Sets the locale to use for display names specified through the TFLite Model Metadata, if
* any.
*
* <p>Defaults to English({@code "en"}). See the <a
* href="https://github.com/tensorflow/tflite-support/blob/3ce83f0cfe2c68fecf83e019f2acc354aaba471f/tensorflow_lite_support/metadata/metadata_schema.fbs#L147">TFLite
* Metadata schema file.</a> for the accepted pattern of locale.
*/
public abstract Builder setDisplayNamesLocale(String displayNamesLocale);
public abstract Builder setOutputType(OutputType outputType);
/**
* Sets the number of threads to be used for TFLite ops that support multi-threading when
* running inference with CPU. Defaults to -1.
*
* <p>numThreads should be greater than 0 or equal to -1. Setting numThreads to -1 has the
* effect to let TFLite runtime set the value.
*/
public abstract Builder setNumThreads(int numThreads);
public abstract ImageSegmenterOptions build();
}
}
/**
* Performs actual segmentation on the provided image.
*
* <p>{@link ImageSegmenter} supports the following {@link TensorImage} color space types:
*
* <ul>
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#RGB}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV21}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV21}
* </ul>
*
* @param image a UINT8 {@link TensorImage} object that represents an RGB or YUV image
* @return results of performing image segmentation. Note that at the time, a single {@link
* Segmentation} element is expected to be returned. The result is stored in a {@link List}
* for later extension to e.g. instance segmentation models, which may return one segmentation
* per object.
* @throws AssertionError if error occurs when segmenting the image from the native code
* @throws IllegalArgumentException if the color space type of image is unsupported
*/
public List<Segmentation> segment(TensorImage image) {
return segment(image, ImageProcessingOptions.builder().build());
}
/**
* Performs actual segmentation on the provided image with {@link ImageProcessingOptions}.
*
* <p>{@link ImageSegmenter} supports the following {@link TensorImage} color space types:
*
* <ul>
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#RGB}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV21}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV21}
* </ul>
*
* <p>{@link ImageSegmenter} supports the following options:
*
* <ul>
* <li>image rotation (through {@link ImageProcessingOptions.Builder#setOrientation}). It
* defaults to {@link ImageProcessingOptions.Orientation#TOP_LEFT}
* </ul>
*
* @param image a UINT8 {@link TensorImage} object that represents an RGB or YUV image
* @param options the options configure how to preprocess the image
* @return results of performing image segmentation. Note that at the time, a single {@link
* Segmentation} element is expected to be returned. The result is stored in a {@link List}
* for later extension to e.g. instance segmentation models, which may return one segmentation
* per object.
* @throws AssertionError if error occurs when segmenting the image from the native code
* @throws IllegalArgumentException if the color space type of image is unsupported
*/
public List<Segmentation> segment(TensorImage image, ImageProcessingOptions options) {
return run(
new InferenceProvider<List<Segmentation>>() {
@Override
public List<Segmentation> run(
long frameBufferHandle, int width, int height, ImageProcessingOptions options) {
return segment(frameBufferHandle, options);
}
},
image,
options);
}
public List<Segmentation> segment(long frameBufferHandle, ImageProcessingOptions options) {
checkNotClosed();
List<byte[]> maskByteArrays = new ArrayList<>();
List<ColoredLabel> coloredLabels = new ArrayList<>();
int[] maskShape = new int[2];
segmentNative(getNativeHandle(), frameBufferHandle, maskByteArrays, maskShape, coloredLabels);
List<ByteBuffer> maskByteBuffers = new ArrayList<>();
for (byte[] bytes : maskByteArrays) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
// Change the byte order to little_endian, since the buffers were generated in jni.
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
maskByteBuffers.add(byteBuffer);
}
return Arrays.asList(
Segmentation.create(
outputType,
outputType.createMasksFromBuffer(maskByteBuffers, maskShape),
coloredLabels));
}
private static ImageSegmenter createFromModelFdAndOptions(
final int fileDescriptor,
final long fileDescriptorLength,
final long fileDescriptorOffset,
final ImageSegmenterOptions options) {
long nativeHandle =
TaskJniUtils.createHandleFromLibrary(
new EmptyHandleProvider() {
@Override
public long createHandle() {
return initJniWithModelFdAndOptions(
fileDescriptor,
fileDescriptorLength,
fileDescriptorOffset,
options.getDisplayNamesLocale(),
options.getOutputType().getValue(),
options.getNumThreads());
}
},
IMAGE_SEGMENTER_NATIVE_LIB);
return new ImageSegmenter(nativeHandle, options.getOutputType());
}
private static native long initJniWithModelFdAndOptions(
int fileDescriptor,
long fileDescriptorLength,
long fileDescriptorOffset,
String displayNamesLocale,
int outputType,
int numThreads);
private static native long initJniWithByteBuffer(
ByteBuffer modelBuffer, String displayNamesLocale, int outputType, int numThreads);
/**
* The native method to segment the image.
*
* <p>{@code maskBuffers}, {@code maskShape}, {@code coloredLabels} will be updated in the native
* layer.
*/
private static native void segmentNative(
long nativeHandle,
long frameBufferHandle,
List<byte[]> maskByteArrays,
int[] maskShape,
List<ColoredLabel> coloredLabels);
@Override
protected void deinit(long nativeHandle) {
deinitJni(nativeHandle);
}
/**
* Native implementation to release memory pointed by the pointer.
*
* @param nativeHandle pointer to memory allocated
*/
private native void deinitJni(long nativeHandle);
}
| tensorflow_lite_support/java/src/java/org/tensorflow/lite/task/vision/segmenter/ImageSegmenter.java | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
package org.tensorflow.lite.task.vision.segmenter;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.os.ParcelFileDescriptor;
import com.google.auto.value.AutoValue;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.task.core.TaskJniUtils;
import org.tensorflow.lite.task.core.TaskJniUtils.EmptyHandleProvider;
import org.tensorflow.lite.task.core.vision.ImageProcessingOptions;
import org.tensorflow.lite.task.vision.core.BaseVisionTaskApi;
import org.tensorflow.lite.task.vision.core.BaseVisionTaskApi.InferenceProvider;
/**
* Performs segmentation on images.
*
* <p>The API expects a TFLite model with <a
* href="https://www.tensorflow.org/lite/convert/metadata">TFLite Model Metadata.</a>.
*
* <p>The API supports models with one image input tensor and one output tensor. To be more
* specific, here are the requirements.
*
* <ul>
* <li>Input image tensor ({@code kTfLiteUInt8}/{@code kTfLiteFloat32})
* <ul>
* <li>image input of size {@code [batch x height x width x channels]}.
* <li>batch inference is not supported ({@code batch} is required to be 1).
* <li>only RGB inputs are supported ({@code channels} is required to be 3).
* <li>if type is {@code kTfLiteFloat32}, NormalizationOptions are required to be attached
* to the metadata for input normalization.
* </ul>
* <li>Output image tensor ({@code kTfLiteUInt8}/{@code kTfLiteFloat32})
* <ul>
* <li>tensor of size {@code [batch x mask_height x mask_width x num_classes]}, where {@code
* batch} is required to be 1, {@code mask_width} and {@code mask_height} are the
* dimensions of the segmentation masks produced by the model, and {@code num_classes}
* is the number of classes supported by the model.
* <li>optional (but recommended) label map(s) can be attached as AssociatedFile-s with type
* TENSOR_AXIS_LABELS, containing one label per line. The first such AssociatedFile (if
* any) is used to fill the class name, i.e. {@link ColoredLabel#getlabel} of the
* results. The display name, i.e. {@link ColoredLabel#getDisplayName}, is filled from
* the AssociatedFile (if any) whose locale matches the `display_names_locale` field of
* the `ImageSegmenterOptions` used at creation time ("en" by default, i.e. English). If
* none of these are available, only the `index` field of the results will be filled.
* </ul>
* </ul>
*
* <p>An example of such model can be found on <a
* href="https://tfhub.dev/tensorflow/lite-model/deeplabv3/1/metadata/1">TensorFlow Hub.</a>.
*/
public final class ImageSegmenter extends BaseVisionTaskApi {
private static final String IMAGE_SEGMENTER_NATIVE_LIB = "task_vision_jni";
private static final int OPTIONAL_FD_LENGTH = -1;
private static final int OPTIONAL_FD_OFFSET = -1;
private final OutputType outputType;
/**
* Creates an {@link ImageSegmenter} instance from the default {@link ImageSegmenterOptions}.
*
* @param modelPath path of the segmentation model with metadata in the assets
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFile(Context context, String modelPath)
throws IOException {
return createFromFileAndOptions(context, modelPath, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance from the default {@link ImageSegmenterOptions}.
*
* @param modelFile the segmentation model {@link File} instance
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFile(File modelFile) throws IOException {
return createFromFileAndOptions(modelFile, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance with a model buffer and the default {@link
* ImageSegmenterOptions}.
*
* @param modelBuffer a direct {@link ByteBuffer} or a {@link MappedByteBuffer} of the
* segmentation model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
* @throws IllegalArgumentException if the model buffer is not a direct {@link ByteBuffer} or a
* {@link MappedByteBuffer}
*/
public static ImageSegmenter createFromBuffer(final ByteBuffer modelBuffer) {
return createFromBufferAndOptions(modelBuffer, ImageSegmenterOptions.builder().build());
}
/**
* Creates an {@link ImageSegmenter} instance from {@link ImageSegmenterOptions}.
*
* @param modelPath path of the segmentation model with metadata in the assets
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFileAndOptions(
Context context, String modelPath, final ImageSegmenterOptions options) throws IOException {
try (AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(modelPath)) {
return createFromModelFdAndOptions(
/*fileDescriptor=*/ assetFileDescriptor.getParcelFileDescriptor().getFd(),
/*fileDescriptorLength=*/ assetFileDescriptor.getLength(),
/*fileDescriptorOffset=*/ assetFileDescriptor.getStartOffset(),
options);
}
}
/**
* Creates an {@link ImageSegmenter} instance from {@link ImageSegmenterOptions}.
*
* @param modelFile the segmentation model {@link File} instance
* @throws IOException if an I/O error occurs when loading the tflite model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
*/
public static ImageSegmenter createFromFileAndOptions(
File modelFile, final ImageSegmenterOptions options) throws IOException {
try (ParcelFileDescriptor descriptor =
ParcelFileDescriptor.open(modelFile, ParcelFileDescriptor.MODE_READ_ONLY)) {
return createFromModelFdAndOptions(
/*fileDescriptor=*/ descriptor.getFd(),
/*fileDescriptorLength=*/ OPTIONAL_FD_LENGTH,
/*fileDescriptorOffset=*/ OPTIONAL_FD_OFFSET,
options);
}
}
/**
* Creates an {@link ImageSegmenter} instance with a model buffer and {@link
* ImageSegmenterOptions}.
*
* @param modelBuffer a direct {@link ByteBuffer} or a {@link MappedByteBuffer} of the
* segmentation model
* @throws AssertionError if error occurs when creating {@link ImageSegmenter} from the native
* code
* @throws IllegalArgumentException if the model buffer is not a direct {@link ByteBuffer} or a
* {@link MappedByteBuffer}
*/
public static ImageSegmenter createFromBufferAndOptions(
final ByteBuffer modelBuffer, final ImageSegmenterOptions options) {
if (!(modelBuffer.isDirect() || modelBuffer instanceof MappedByteBuffer)) {
throw new IllegalArgumentException(
"The model buffer should be either a direct ByteBuffer or a MappedByteBuffer.");
}
return new ImageSegmenter(
TaskJniUtils.createHandleFromLibrary(
new EmptyHandleProvider() {
@Override
public long createHandle() {
return initJniWithByteBuffer(
modelBuffer,
options.getDisplayNamesLocale(),
options.getOutputType().getValue(),
options.getNumThreads());
}
},
IMAGE_SEGMENTER_NATIVE_LIB),
options.getOutputType());
}
/**
* Constructor to initialize the JNI with a pointer from C++.
*
* @param nativeHandle a pointer referencing memory allocated in C++
*/
private ImageSegmenter(long nativeHandle, OutputType outputType) {
super(nativeHandle);
this.outputType = outputType;
}
/** Options for setting up an {@link ImageSegmenter}. */
@AutoValue
public abstract static class ImageSegmenterOptions {
private static final String DEFAULT_DISPLAY_NAME_LOCALE = "en";
private static final OutputType DEFAULT_OUTPUT_TYPE = OutputType.CATEGORY_MASK;
private static final int NUM_THREADS = -1;
public abstract String getDisplayNamesLocale();
public abstract OutputType getOutputType();
public abstract int getNumThreads();
public static Builder builder() {
return new AutoValue_ImageSegmenter_ImageSegmenterOptions.Builder()
.setDisplayNamesLocale(DEFAULT_DISPLAY_NAME_LOCALE)
.setOutputType(DEFAULT_OUTPUT_TYPE)
.setNumThreads(NUM_THREADS);
}
/** Builder for {@link ImageSegmenterOptions}. */
@AutoValue.Builder
public abstract static class Builder {
/**
* Sets the locale to use for display names specified through the TFLite Model Metadata, if
* any.
*
* <p>Defaults to English({@code "en"}). See the <a
* href="https://github.com/tensorflow/tflite-support/blob/3ce83f0cfe2c68fecf83e019f2acc354aaba471f/tensorflow_lite_support/metadata/metadata_schema.fbs#L147">TFLite
* Metadata schema file.</a> for the accepted pattern of locale.
*/
public abstract Builder setDisplayNamesLocale(String displayNamesLocale);
public abstract Builder setOutputType(OutputType outputType);
/**
* Sets the number of threads to be used for TFLite ops that support multi-threading when
* running inference with CPU. Defaults to -1.
*
* <p>numThreads should be greater than 0 or equal to -1. Setting numThreads to -1 has the
* effect to let TFLite runtime set the value.
*/
public abstract Builder setNumThreads(int numThreads);
public abstract ImageSegmenterOptions build();
}
}
/**
* Performs actual segmentation on the provided image.
*
* <p>{@link ImageSegmenter} supports the following {@link TensorImage} color space types:
*
* <ul>
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#RGB}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV21}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV21}
* </ul>
*
* @param image a UINT8 {@link TensorImage} object that represents an RGB or YUV image
* @return results of performing image segmentation. Note that at the time, a single {@link
* Segmentation} element is expected to be returned. The result is stored in a {@link List}
* for later extension to e.g. instance segmentation models, which may return one segmentation
* per object.
* @throws AssertionError if error occurs when segmenting the image from the native code
* @throws IllegalArgumentException if the color space type of image is unsupported
*/
public List<Segmentation> segment(TensorImage image) {
return segment(image, ImageProcessingOptions.builder().build());
}
/**
* Performs actual segmentation on the provided image with {@link ImageProcessingOptions}.
*
* <p>{@link ImageSegmenter} supports the following {@link TensorImage} color space types:
*
* <ul>
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#RGB}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#NV21}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV12}
* <li>{@link org.tensorflow.lite.support.image.ColorSpaceType#YV21}
* </ul>
*
* @param image a UINT8 {@link TensorImage} object that represents an RGB or YUV image
* @param options {@link ImageSegmenter} only supports image rotation (through {@link
* ImageProcessingOptions.Builder#setOrientation}) currently. The orientation of an image
* defaults to {@link ImageProcessingOptions.Orientation#TOP_LEFT}.
* @return results of performing image segmentation. Note that at the time, a single {@link
* Segmentation} element is expected to be returned. The result is stored in a {@link List}
* for later extension to e.g. instance segmentation models, which may return one segmentation
* per object.
* @throws AssertionError if error occurs when segmenting the image from the native code
* @throws IllegalArgumentException if the color space type of image is unsupported
*/
public List<Segmentation> segment(TensorImage image, ImageProcessingOptions options) {
return run(
new InferenceProvider<List<Segmentation>>() {
@Override
public List<Segmentation> run(
long frameBufferHandle, int width, int height, ImageProcessingOptions options) {
return segment(frameBufferHandle, options);
}
},
image,
options);
}
public List<Segmentation> segment(long frameBufferHandle, ImageProcessingOptions options) {
checkNotClosed();
List<byte[]> maskByteArrays = new ArrayList<>();
List<ColoredLabel> coloredLabels = new ArrayList<>();
int[] maskShape = new int[2];
segmentNative(getNativeHandle(), frameBufferHandle, maskByteArrays, maskShape, coloredLabels);
List<ByteBuffer> maskByteBuffers = new ArrayList<>();
for (byte[] bytes : maskByteArrays) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
// Change the byte order to little_endian, since the buffers were generated in jni.
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
maskByteBuffers.add(byteBuffer);
}
return Arrays.asList(
Segmentation.create(
outputType,
outputType.createMasksFromBuffer(maskByteBuffers, maskShape),
coloredLabels));
}
private static ImageSegmenter createFromModelFdAndOptions(
final int fileDescriptor,
final long fileDescriptorLength,
final long fileDescriptorOffset,
final ImageSegmenterOptions options) {
long nativeHandle =
TaskJniUtils.createHandleFromLibrary(
new EmptyHandleProvider() {
@Override
public long createHandle() {
return initJniWithModelFdAndOptions(
fileDescriptor,
fileDescriptorLength,
fileDescriptorOffset,
options.getDisplayNamesLocale(),
options.getOutputType().getValue(),
options.getNumThreads());
}
},
IMAGE_SEGMENTER_NATIVE_LIB);
return new ImageSegmenter(nativeHandle, options.getOutputType());
}
private static native long initJniWithModelFdAndOptions(
int fileDescriptor,
long fileDescriptorLength,
long fileDescriptorOffset,
String displayNamesLocale,
int outputType,
int numThreads);
private static native long initJniWithByteBuffer(
ByteBuffer modelBuffer, String displayNamesLocale, int outputType, int numThreads);
/**
* The native method to segment the image.
*
* <p>{@code maskBuffers}, {@code maskShape}, {@code coloredLabels} will be updated in the native
* layer.
*/
private static native void segmentNative(
long nativeHandle,
long frameBufferHandle,
List<byte[]> maskByteArrays,
int[] maskShape,
List<ColoredLabel> coloredLabels);
@Override
protected void deinit(long nativeHandle) {
deinitJni(nativeHandle);
}
/**
* Native implementation to release memory pointed by the pointer.
*
* @param nativeHandle pointer to memory allocated
*/
private native void deinitJni(long nativeHandle);
}
| Internal codebase change
PiperOrigin-RevId: 381256317
| tensorflow_lite_support/java/src/java/org/tensorflow/lite/task/vision/segmenter/ImageSegmenter.java | Internal codebase change |
|
Java | apache-2.0 | f123fc3de72b427d0f48858e2c24a387f8595cad | 0 | jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics | /*
* Java Genetic Algorithm Library (@!identifier!@).
* Copyright (c) @!year!@ Franz Wilhelmstötter
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author:
* Franz Wilhelmstötter ([email protected])
*
*/
package org.jenetics.util;
import static org.jenetics.util.Validator.nonNull;
import java.io.Serializable;
import javax.measure.Measurable;
import javax.measure.Measure;
import javax.measure.quantity.Duration;
import javax.measure.unit.SI;
import javolution.lang.Reusable;
/**
* Timer for measure the performance of the GA. The timer uses nano second
* precision (by using {@link System#nanoTime()}). This timer is not synchronized.
* It's up to the user to ensure thread safety.
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version $Id$
*/
public class Timer
implements
Comparable<Timer>,
Reusable,
Serializable,
Cloneable
{
private static final long serialVersionUID = 1L;
private static final String DEFAULT_LABEL = "Timer";
private String _label;
private long _start = 0;
private long _stop = 0;
private long _sum = 0;
/**
* Create a new time with the given label. The label is use in the
* {@link #toString()} method.
*
* @param label the timer label.
* @throws NullPointerException if the {@code label} is {@code null}.
*/
public Timer(final String label) {
_label = nonNull(label, "Time label");
}
/**
* Create a new Timer object.
*/
public Timer() {
this(DEFAULT_LABEL);
}
/**
* Start the timer.
*/
public void start() {
_start = System.nanoTime();
}
/**
* Stop the timer.
*/
public void stop() {
_stop = System.nanoTime();
_sum += _stop - _start;
}
/**
* Reset the timer.
*/
@Override
public void reset() {
_sum = 0;
_start = 0;
_stop = 0;
}
/**
* Return the overall time of this timer. The following code snippet would
* return a measured time of 10 s (theoretically).
* [code]
* final Timer timer = new Timer();
* for (int i = 0; i < 10) {
* timer.start();
* Thread.sleep(1000);
* timer.stop();
* }
* [/code]
*
* @return the measured time so far.
*/
public Measurable<Duration> getTime() {
return Measure.valueOf(_sum, SI.NANO(SI.SECOND));
}
/**
* Return the time between two successive calls of {@link #start()} and
* {@link #stop()}.
*
* @return the interim time measured.
*/
public Measurable<Duration> getInterimTime() {
return Measure.valueOf(_stop - _start, SI.NANO(SI.SECOND));
}
/**
* Return the timer label.
*
* @return the timer label.
*/
public String getLabel() {
return _label;
}
/**
* Set the timer label.
*
* @param label the new timer label
*/
public void setLabel(final String label) {
_label = nonNull(label, "Timer label");
}
@Override
public int compareTo(final Timer timer) {
nonNull(timer, "Timer");
long diff = _sum - timer._sum;
int comp = 0;
if (diff < 0) {
comp = -1;
} else if (diff > 0) {
comp = 1;
}
return comp;
}
@Override
public int hashCode() {
int hash = 17;
hash += 37*_label.hashCode() + 17;
hash += 37*_start + 17;
hash += 37*_stop + 17;
hash += 37*_sum + 17;
return hash;
}
@Override
public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Timer)) {
return false;
}
final Timer timer = (Timer)object;
return _start == timer._start &&
_stop == timer._stop &&
_sum == timer._sum &&
_label.equals(timer._label);
}
@Override
public Timer clone() {
try {
return (Timer)super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
@Override
public String toString() {
return String.format(
"%s: %11.11f s", _label,
getTime().doubleValue(SI.SECOND)
);
}
}
| src/main/java/org/jenetics/util/Timer.java | /*
* Java Genetic Algorithm Library (@!identifier!@).
* Copyright (c) @!year!@ Franz Wilhelmstötter
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author:
* Franz Wilhelmstötter ([email protected])
*
*/
package org.jenetics.util;
import static org.jenetics.util.Validator.nonNull;
import java.io.Serializable;
import javax.measure.Measurable;
import javax.measure.Measure;
import javax.measure.quantity.Duration;
import javax.measure.unit.SI;
import javolution.lang.Reusable;
/**
* Timer for measure the performance of the GA. The timer uses nano second
* precision (by using {@link System#nanoTime()}). This timer is not synchronized.
* It's up to the user to ensure thread safety.
*
* @author <a href="mailto:[email protected]">Franz Wilhelmstötter</a>
* @version $Id$
*/
public class Timer
implements
Comparable<Timer>,
Reusable,
Serializable,
Cloneable
{
private static final long serialVersionUID = 1L;
private static final String DEFAULT_LABEL = "Timer";
private String _label;
private long _start = 0;
private long _stop = 0;
private long _sum = 0;
/**
* Create a new time with the given label. The label is use in the
* {@link #toString()} method.
*
* @param label the timer label.
* @throws NullPointerException if the {@code label} is {@code null}.
*/
public Timer(final String label) {
_label = nonNull(label, "Time label");
}
/**
* Create a new Timer object.
*/
public Timer() {
this(DEFAULT_LABEL);
}
/**
* Start the timer.
*/
public void start() {
_start = System.nanoTime();
}
/**
* Stop the timer.
*/
public void stop() {
_stop = System.nanoTime();
_sum += _stop - _start;
}
/**
* Reset the timer.
*/
@Override
public void reset() {
_sum = 0;
_start = 0;
_stop = 0;
}
/**
* Return the overall time of this timer. The following code snippet would
* return a measured time of 10 s (theoretically).
* [code]
* final Timer timer = new Timer();
* for (int i = 0; i < 10) {
* timer.start();
* Thread.sleep(1000);
* timer.stop();
* }
* [/code]
*
* @return the measured time so far.
*/
public Measurable<Duration> getTime() {
return Measure.valueOf(_sum, SI.NANO(SI.SECOND));
}
/**
* Return the time between two successive calls of {@link #start()} and
* {@link #stop()}.
*
* @return the interim time measured.
*/
public Measurable<Duration> getInterimTime() {
return Measure.valueOf(_stop - _start, SI.NANO(SI.SECOND));
}
/**
* Return the timer label.
*
* @return the timer label.
*/
public String getLabel() {
return _label;
}
/**
* Set the timer label.
*
* @param label the new timer label
*/
public void setLabel(final String label) {
_label = nonNull(label, "Timer label");
}
@Override
public int compareTo(final Timer timer) {
nonNull(timer, "Timer");
long diff = _sum - timer._sum;
int comp = 0;
if (diff < 0) {
comp = -1;
} else if (diff > 0) {
comp = 1;
}
return comp;
}
@Override
public int hashCode() {
int hash = 17;
hash += 37*_label.hashCode() + 17;
hash += 37*_start + 17;
hash += 37*_stop + 17;
hash += 37*_sum + 17;
return hash;
}
@Override
public boolean equals(final Object object) {
if (object == this) {
return true;
}
if (!(object instanceof Timer)) {
return false;
}
final Timer timer = (Timer)object;
return _start == timer._start &&
_stop == timer._stop &&
_sum == timer._sum &&
_label.equals(timer._label);
}
@Override
public Timer clone() {
try {
return (Timer)super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
@Override
public String toString() {
return String.format("%s: %11.11f s", _label, getTime().doubleValue(SI.SECOND));
}
}
| Incomplete - # 13: Code and test improvements
https://sourceforge.net/apps/trac/jenetics/ticket/13
| src/main/java/org/jenetics/util/Timer.java | Incomplete - # 13: Code and test improvements https://sourceforge.net/apps/trac/jenetics/ticket/13 |
|
Java | apache-2.0 | 8411c64a6ffefba4332e9f0c74b90d1204fd53c7 | 0 | gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.crypto.key;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
import org.apache.ranger.kms.dao.DaoManager;
import org.apache.ranger.kms.dao.RangerMasterKeyDao;
import org.apache.ranger.entity.XXRangerMasterKey;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class RangerMasterKey implements RangerKMSMKI{
static final Logger logger = Logger.getLogger(RangerMasterKey.class);
private static final String MK_CIPHER = "AES";
private static final int MK_KeySize = 256;
private static final int SALT_SIZE = 8;
private static final String PBE_ALGO = "PBEWithMD5AndTripleDES";
private static final String MD_ALGO = "MD5";
private DaoManager daoManager;
public RangerMasterKey() {
}
public RangerMasterKey(DaoManager daoManager) {
this.daoManager = daoManager;
}
/**
* To get Master Key
* @param password password to be used for decryption
* @return Decrypted Master Key
* @throws Throwable
*/
@Override
public String getMasterKey(String password) throws Throwable{
logger.info("Getting Master Key");
byte masterKeyByte[] = getEncryptedMK();
if(masterKeyByte != null && masterKeyByte.length > 0){
return decryptMasterKey(masterKeyByte, password);
}else{
throw new Exception("No Master Key Found");
}
}
public SecretKey getMasterSecretKey(String password) throws Throwable{
logger.info("Getting Master Key");
byte masterKeyByte[] = getEncryptedMK();
if(masterKeyByte != null && masterKeyByte.length > 0){
return decryptMasterKeySK(masterKeyByte, password);
}else{
throw new Exception("No Master Key Found");
}
}
/**
* Generate the master key, encrypt it and save it in the database
* @param password password to be used for encryption
* @return true if the master key was successfully created
* false if master key generation was unsuccessful or the master key already exists
* @throws Throwable
*/
@Override
public boolean generateMasterKey(String password) throws Throwable{
logger.info("Generating Master Key");
String encryptedMasterKey = encryptMasterKey(password);
String savedKey = saveEncryptedMK(encryptedMasterKey, daoManager);
if(savedKey != null && !savedKey.trim().equals("")){
logger.debug("Master Key Created with id = "+savedKey);
return true;
}
return false;
}
public boolean generateMKFromHSMMK(String password, byte[] key) throws Throwable{
logger.info("Generating Master Key");
String encryptedMasterKey = encryptMasterKey(password, key);
String savedKey = saveEncryptedMK(encryptedMasterKey, daoManager);
if(savedKey != null && !savedKey.trim().equals("")){
logger.debug("Master Key Created with id = "+savedKey);
return true;
}
return false;
}
private String decryptMasterKey(byte masterKey[], String password) throws Throwable {
logger.debug("Decrypting Master Key");
PBEKeySpec pbeKeyspec = getPBEParameterSpec(password) ;
byte[] masterKeyFromDBDecrypted = decryptKey(masterKey, pbeKeyspec) ;
SecretKey masterKeyFromDB = getMasterKeyFromBytes(masterKeyFromDBDecrypted) ;
return Base64.encode(masterKeyFromDB.getEncoded());
}
private SecretKey decryptMasterKeySK(byte masterKey[], String password) throws Throwable {
logger.debug("Decrypting Master Key");
PBEKeySpec pbeKeyspec = getPBEParameterSpec(password) ;
byte[] masterKeyFromDBDecrypted = decryptKey(masterKey, pbeKeyspec) ;
return getMasterKeyFromBytes(masterKeyFromDBDecrypted) ;
}
private byte[] getEncryptedMK() throws Base64DecodingException {
logger.debug("Retrieving Encrypted Master Key from database");
try{
if(daoManager != null){
RangerMasterKeyDao rangerKMSDao = new RangerMasterKeyDao(daoManager);
List<XXRangerMasterKey> lstRangerMasterKey = rangerKMSDao.getAll();
if(lstRangerMasterKey.size() < 1){
throw new Exception("No Master Key exists");
}else if(lstRangerMasterKey.size() > 1){
throw new Exception("More than one Master Key exists");
}else {
XXRangerMasterKey rangerMasterKey = rangerKMSDao.getById(lstRangerMasterKey.get(0).getId());
String masterKeyStr = rangerMasterKey.getMasterKey();
return Base64.decode(masterKeyStr) ;
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private String saveEncryptedMK(String encryptedMasterKey, DaoManager daoManager) {
logger.debug("Saving Encrypted Master Key to database");
XXRangerMasterKey xxRangerMasterKey = new XXRangerMasterKey();
xxRangerMasterKey.setCipher(MK_CIPHER);
xxRangerMasterKey.setBitLength(MK_KeySize);
xxRangerMasterKey.setMasterKey(encryptedMasterKey);
try{
if(daoManager != null){
RangerMasterKeyDao rangerKMSDao = new RangerMasterKeyDao(daoManager);
Long l = rangerKMSDao.getAllCount();
if(l < 1){
XXRangerMasterKey rangerMasterKey = rangerKMSDao.create(xxRangerMasterKey);
return rangerMasterKey.getId().toString();
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private String encryptMasterKey(String password) throws Throwable {
logger.debug("Encrypting Master Key");
Key secretKey = generateMasterKey();
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey.getEncoded(), pbeKeySpec);
return Base64.encode(masterKeyToDB) ;
}
private String encryptMasterKey(String password, byte[] secretKey) throws Throwable {
logger.debug("Encrypting Master Key");
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey, pbeKeySpec);
return Base64.encode(masterKeyToDB) ;
}
private Key generateMasterKey() throws NoSuchAlgorithmException{
KeyGenerator kg = KeyGenerator.getInstance(MK_CIPHER);
kg.init(MK_KeySize);
return kg.generateKey();
}
private PBEKeySpec getPBEParameterSpec(String password) throws Throwable {
MessageDigest md = MessageDigest.getInstance(MD_ALGO) ;
byte[] saltGen = md.digest(password.getBytes()) ;
byte[] salt = new byte[SALT_SIZE] ;
System.arraycopy(saltGen, 0, salt, 0, SALT_SIZE);
int iteration = password.toCharArray().length + 1 ;
return new PBEKeySpec(password.toCharArray(), salt, iteration) ;
}
private byte[] encryptKey(byte[] data, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec) ;
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount()) ;
Cipher c = Cipher.getInstance(key.getAlgorithm()) ;
c.init(Cipher.ENCRYPT_MODE, key,paramSpec);
return c.doFinal(data) ;
}
private SecretKey getPasswordKey(PBEKeySpec keyspec) throws Throwable {
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGO) ;
return factory.generateSecret(keyspec) ;
}
private byte[] decryptKey(byte[] encrypted, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec) ;
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount()) ;
Cipher c = Cipher.getInstance(key.getAlgorithm()) ;
c.init(Cipher.DECRYPT_MODE, key, paramSpec);
return c.doFinal(encrypted) ;
}
private SecretKey getMasterKeyFromBytes(byte[] keyData) throws Throwable {
return new SecretKeySpec(keyData, MK_CIPHER) ;
}
public Map<String, String> getPropertiesWithPrefix(Properties props, String prefix) {
Map<String, String> prefixedProperties = new HashMap<String, String>();
if(props != null && prefix != null) {
for(String key : props.stringPropertyNames()) {
if(key == null) {
continue;
}
String val = props.getProperty(key);
if(key.startsWith(prefix)) {
key = key.substring(prefix.length());
if(key != null) {
prefixedProperties.put(key, val);
}
}
}
}
return prefixedProperties;
}
}
| kms/src/main/java/org/apache/hadoop/crypto/key/RangerMasterKey.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.crypto.key;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
import org.apache.ranger.kms.dao.DaoManager;
import org.apache.ranger.kms.dao.RangerMasterKeyDao;
import org.apache.ranger.entity.XXRangerMasterKey;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class RangerMasterKey implements RangerKMSMKI{
static final Logger logger = Logger.getLogger(RangerMasterKey.class);
private static final String MK_CIPHER = "AES";
private static final int MK_KeySize = 256;
private static final int SALT_SIZE = 8;
private static final String PBE_ALGO = "PBEWithMD5AndTripleDES";
private static final String MD_ALGO = "MD5";
private DaoManager daoManager;
public RangerMasterKey() {
}
public RangerMasterKey(DaoManager daoManager) {
this.daoManager = daoManager;
}
/**
* To get Master Key
* @param password password to be used for decryption
* @return Decrypted Master Key
* @throws Throwable
*/
@Override
public String getMasterKey(String password) throws Throwable{
logger.info("Getting Master Key");
byte masterKeyByte[] = getEncryptedMK();
if(masterKeyByte != null && masterKeyByte.length > 0){
String masterKey = decryptMasterKey(masterKeyByte, password);
return masterKey;
}else{
throw new Exception("No Master Key Found");
}
}
public SecretKey getMasterSecretKey(String password) throws Throwable{
logger.info("Getting Master Key");
byte masterKeyByte[] = getEncryptedMK();
if(masterKeyByte != null && masterKeyByte.length > 0){
return decryptMasterKeySK(masterKeyByte, password);
}else{
throw new Exception("No Master Key Found");
}
}
/**
* Generate the master key, encrypt it and save it in the database
* @param password password to be used for encryption
* @return true if the master key was successfully created
* false if master key generation was unsuccessful or the master key already exists
* @throws Throwable
*/
@Override
public boolean generateMasterKey(String password) throws Throwable{
logger.info("Generating Master Key");
String encryptedMasterKey = encryptMasterKey(password);
String savedKey = saveEncryptedMK(encryptedMasterKey, daoManager);
if(savedKey != null && !savedKey.trim().equals("")){
logger.debug("Master Key Created with id = "+savedKey);
return true;
}
return false;
}
public boolean generateMKFromHSMMK(String password, byte[] key) throws Throwable{
logger.info("Generating Master Key");
String encryptedMasterKey = encryptMasterKey(password, key);
String savedKey = saveEncryptedMK(encryptedMasterKey, daoManager);
if(savedKey != null && !savedKey.trim().equals("")){
logger.debug("Master Key Created with id = "+savedKey);
return true;
}
return false;
}
private String decryptMasterKey(byte masterKey[], String password) throws Throwable {
logger.debug("Decrypting Master Key");
PBEKeySpec pbeKeyspec = getPBEParameterSpec(password) ;
byte[] masterKeyFromDBDecrypted = decryptKey(masterKey, pbeKeyspec) ;
SecretKey masterKeyFromDB = getMasterKeyFromBytes(masterKeyFromDBDecrypted) ;
return Base64.encode(masterKeyFromDB.getEncoded());
}
private SecretKey decryptMasterKeySK(byte masterKey[], String password) throws Throwable {
logger.debug("Decrypting Master Key");
PBEKeySpec pbeKeyspec = getPBEParameterSpec(password) ;
byte[] masterKeyFromDBDecrypted = decryptKey(masterKey, pbeKeyspec) ;
return getMasterKeyFromBytes(masterKeyFromDBDecrypted) ;
}
private byte[] getEncryptedMK() throws Base64DecodingException {
logger.debug("Retrieving Encrypted Master Key from database");
try{
if(daoManager != null){
RangerMasterKeyDao rangerKMSDao = new RangerMasterKeyDao(daoManager);
List<XXRangerMasterKey> lstRangerMasterKey = rangerKMSDao.getAll();
if(lstRangerMasterKey.size() < 1){
throw new Exception("No Master Key exists");
}else if(lstRangerMasterKey.size() > 1){
throw new Exception("More than one Master Key exists");
}else {
XXRangerMasterKey rangerMasterKey = rangerKMSDao.getById(lstRangerMasterKey.get(0).getId());
String masterKeyStr = rangerMasterKey.getMasterKey();
byte[] masterKeyFromDBEncrypted = Base64.decode(masterKeyStr) ;
return masterKeyFromDBEncrypted;
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private String saveEncryptedMK(String encryptedMasterKey, DaoManager daoManager) {
logger.debug("Saving Encrypted Master Key to database");
XXRangerMasterKey xxRangerMasterKey = new XXRangerMasterKey();
xxRangerMasterKey.setCipher(MK_CIPHER);
xxRangerMasterKey.setBitLength(MK_KeySize);
xxRangerMasterKey.setMasterKey(encryptedMasterKey);
try{
if(daoManager != null){
RangerMasterKeyDao rangerKMSDao = new RangerMasterKeyDao(daoManager);
Long l = rangerKMSDao.getAllCount();
if(l < 1){
XXRangerMasterKey rangerMasterKey = rangerKMSDao.create(xxRangerMasterKey);
return rangerMasterKey.getId().toString();
}
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
private String encryptMasterKey(String password) throws Throwable {
logger.debug("Encrypting Master Key");
Key secretKey = generateMasterKey();
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey.getEncoded(), pbeKeySpec);
String masterKey = Base64.encode(masterKeyToDB) ;
return masterKey;
}
private String encryptMasterKey(String password, byte[] secretKey) throws Throwable {
logger.debug("Encrypting Master Key");
PBEKeySpec pbeKeySpec = getPBEParameterSpec(password);
byte[] masterKeyToDB = encryptKey(secretKey, pbeKeySpec);
String masterKey = Base64.encode(masterKeyToDB) ;
return masterKey;
}
private Key generateMasterKey() throws NoSuchAlgorithmException{
KeyGenerator kg = KeyGenerator.getInstance(MK_CIPHER);
kg.init(MK_KeySize);
return kg.generateKey();
}
private PBEKeySpec getPBEParameterSpec(String password) throws Throwable {
MessageDigest md = MessageDigest.getInstance(MD_ALGO) ;
byte[] saltGen = md.digest(password.getBytes()) ;
byte[] salt = new byte[SALT_SIZE] ;
System.arraycopy(saltGen, 0, salt, 0, SALT_SIZE);
int iteration = password.toCharArray().length + 1 ;
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iteration) ;
return spec ;
}
private byte[] encryptKey(byte[] data, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec) ;
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount()) ;
Cipher c = Cipher.getInstance(key.getAlgorithm()) ;
c.init(Cipher.ENCRYPT_MODE, key,paramSpec);
byte[] encrypted = c.doFinal(data) ;
return encrypted ;
}
private SecretKey getPasswordKey(PBEKeySpec keyspec) throws Throwable {
SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGO) ;
SecretKey PbKey = factory.generateSecret(keyspec) ;
return PbKey ;
}
private byte[] decryptKey(byte[] encrypted, PBEKeySpec keyspec) throws Throwable {
SecretKey key = getPasswordKey(keyspec) ;
PBEParameterSpec paramSpec = new PBEParameterSpec(keyspec.getSalt(), keyspec.getIterationCount()) ;
Cipher c = Cipher.getInstance(key.getAlgorithm()) ;
c.init(Cipher.DECRYPT_MODE, key, paramSpec);
byte[] data = c.doFinal(encrypted) ;
return data ;
}
private SecretKey getMasterKeyFromBytes(byte[] keyData) throws Throwable {
SecretKeySpec sks = new SecretKeySpec(keyData, MK_CIPHER) ;
return sks ;
}
public Map<String, String> getPropertiesWithPrefix(Properties props, String prefix) {
Map<String, String> prefixedProperties = new HashMap<String, String>();
if(props != null && prefix != null) {
for(String key : props.stringPropertyNames()) {
if(key == null) {
continue;
}
String val = props.getProperty(key);
if(key.startsWith(prefix)) {
key = key.substring(prefix.length());
if(key == null) {
continue;
}
prefixedProperties.put(key, val);
}
}
}
return prefixedProperties;
}
}
| Trivial cleanup II
| kms/src/main/java/org/apache/hadoop/crypto/key/RangerMasterKey.java | Trivial cleanup II |
|
Java | apache-2.0 | e95c6fbe045d83daa6bc41cf0047a62347a98cfe | 0 | michael-rapp/AndroidMaterialDialog | /*
* Copyright 2014 - 2018 Michael Rapp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.mrapp.android.dialog.decorator;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import de.mrapp.android.dialog.DialogValidator;
import de.mrapp.android.dialog.R;
import de.mrapp.android.dialog.model.ButtonBarDialog;
import de.mrapp.android.dialog.model.ValidateableDialog;
import de.mrapp.android.dialog.view.DialogRootView.ViewType;
import de.mrapp.android.validation.ValidationListener;
import de.mrapp.android.validation.Validator;
import de.mrapp.util.Condition;
import de.mrapp.util.datastructure.ListenerList;
/**
* A decorator, which allows to modify the view hierarchy of a dialog, which is designed according
* to Android 5's Material Design guidelines even on pre-Lollipop devices and contains an {@link
* EditText} widget.
*
* @author Michael Rapp
* @since 5.1.0
*/
public class EditTextDialogDecorator extends AbstractDialogDecorator<ButtonBarDialog>
implements de.mrapp.android.dialog.model.EditTextDialogDecorator, DialogValidator {
/**
* The name of the extra, which is used to store the text of the dialog's edit text widget
* within a bundle.
*/
private static final String TEXT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::text";
/**
* The name of the extra, which is used to store the hint of the dialog's edit text widget
* within a bundle.
*/
private static final String HINT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::hint";
/**
* The name of the extra, which is used to store the helper text of the dialog's edit text
* widget within a bundle.
*/
private static final String HELPER_TEXT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::helperText";
/**
* The name of the extra, which is used to store the error color of the dialog's edit text
* widget within a bundle.
*/
private static final String ERROR_COLOR_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::errorColor";
/**
* The name of the extra, which is used to store the helper text color of the dialog's edit text
* widget within a bundle.
*/
private static final String HELPER_TEXT_COLOR_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::helperTextColor";
/**
* The name of the extra, which is used to store, whether the dialog's edit text widget should
* be validated when its value changed, within a bundle.
*/
private static final String VALIDATE_ON_VALUE_CHANGE_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::validateOnValueChange";
/**
* The name of the extra, which is used to store, whether the dialog's edit text widget should
* be validated when it list its focus, within a bundle.
*/
private static final String VALIDATE_ON_FOCUS_LOST_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::validateOnFocusLost";
/**
* A set, which contains the validators of the dialog's edit text widget.
*/
private final Set<Validator<CharSequence>> validators = new LinkedHashSet<>();
/**
* Contains the listeners that should be notified when the dialog's edit text widget has been
* validated.
*/
private final ListenerList<ValidationListener<CharSequence>> validationListeners =
new ListenerList<>();
/**
* The text of the dialog's edit text widget.
*/
private CharSequence text;
/**
* The hint of the dialog's edit text widget.
*/
private CharSequence hint;
/**
* The helper text of the dialog's edit text widget.
*/
private CharSequence helperText;
/**
* The error color of the dialog's edit text widget.
*/
private ColorStateList errorColor;
/**
* The helper text color of the dialog's edit text widget.
*/
private ColorStateList helperTextColor;
/**
* True, if the dialog's edit text widget is validated when its text has been changed, false
* otherwise.
*/
private boolean validateOnValueChange = true;
/**
* True, if the dialog's edit text widget is validated when its focus got lost, false
* otherwise.
*/
private boolean validateOnFocusLost = true;
/**
* The dialog's text input layout.
*/
private TextInputLayout textInputLayout;
/**
* The dialog's edit text widget.
*/
private EditText editText;
/**
* Inflates the dialog's edit text widget.
*/
private void inflateEditText() {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.edit_text_dialog, getRootView(), false);
getDialog().setView(view);
View textInputLayoutView = view.findViewById(R.id.text_input_layout);
textInputLayout = textInputLayoutView instanceof TextInputLayout ?
(TextInputLayout) textInputLayoutView : null;
View editTextView = view.findViewById(R.id.edit_text);
editText = editTextView instanceof EditText ? (EditText) editTextView : null;
adaptHint();
adaptErrorColor();
adaptHelperTextColor();
adaptHelperText();
adaptText();
validate();
adaptTextChangedListener();
adaptFocusChangeListener();
}
/**
* Adapts the text of the edit text widget, which is contained by the dialog.
*/
private void adaptText() {
if (editText != null) {
editText.setText(text);
if (text != null) {
editText.setSelection(text.length());
}
}
}
/**
* Adapts the hint of the dialog's edit text widget.
*/
private void adaptHint() {
if (textInputLayout != null) {
textInputLayout.setHint(hint);
} else if (editText != null) {
editText.setHint(hint);
}
}
/**
* Adapts the error color of the dialog's edit text widget.
*/
private void adaptErrorColor() {
if (textInputLayout != null && errorColor != null) {
textInputLayout.setErrorTextColor(errorColor);
}
}
/**
* Adapts the helper text color of the dialog's edit text widget.
*/
private void adaptHelperTextColor() {
if (textInputLayout != null && helperTextColor != null) {
textInputLayout.setHelperTextColor(helperTextColor);
}
}
/**
* Adapts the helper text of the dialog's edit text widget.
*/
private void adaptHelperText() {
if (textInputLayout != null && TextUtils.isEmpty(getText())) {
textInputLayout.setHelperText(helperText);
textInputLayout.setHelperTextEnabled(true);
}
}
/**
* Shows an error text.
*/
private void showErrorText(@Nullable final CharSequence errorText) {
if (textInputLayout != null) {
if (TextUtils.isEmpty(errorText)) {
textInputLayout.setError(null);
textInputLayout.setErrorEnabled(false);
adaptHelperTextColor();
} else {
textInputLayout.setHelperText(null);
textInputLayout.setHelperTextEnabled(false);
textInputLayout.setError(errorText);
textInputLayout.setErrorEnabled(true);
}
}
}
/**
* Adapts the enable state of the dialog's positive button.
*
* @param enabled
* True, if the button should be enabled, false otherwise
*/
private void adaptPositiveButtonEnableState(final boolean enabled) {
Button button = getDialog().getButton(DialogInterface.BUTTON_POSITIVE);
if (button != null) {
button.setEnabled(enabled);
}
}
/**
* Adapts the listener, which allows to observe when the text of the the dialog's edit text has
* changed.
*/
private void adaptTextChangedListener() {
if (editText != null) {
editText.addTextChangedListener(createTextChangedListener());
}
}
/**
* Creates and returns a listener, which allows to observe when the text of the dialog's edit
* text has changed.
*
* @return The listener, which has been created, as an instance of the type {@link TextWatcher}.
* The listener may not be null
*/
@NonNull
private TextWatcher createTextChangedListener() {
return new TextWatcher() {
@Override
public void beforeTextChanged(final CharSequence text, final int start, final int count,
final int after) {
}
@Override
public void afterTextChanged(final Editable text) {
}
@Override
public void onTextChanged(final CharSequence text, final int start, final int before,
final int count) {
EditTextDialogDecorator.this.text = text;
if (validateOnValueChange) {
validate();
}
}
};
}
/**
* Adapts the listener, which allows to observe when the dialog's edit text has lost its focus.
*/
private void adaptFocusChangeListener() {
if (editText != null) {
editText.setOnFocusChangeListener(createFocusChangeListener());
}
}
/**
* Creates and returns a listener, which allows to validate the dialog's edit text widget when
* its focus got lost.
*
* @return The listener, which has been created, as an instance of the type {@link
* View.OnFocusChangeListener}. The listener may not be null
*/
@NonNull
private View.OnFocusChangeListener createFocusChangeListener() {
return new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (!hasFocus && validateOnFocusLost) {
validate();
}
}
};
}
/**
* Notifies the listeners that the validation of the dialog's edit text widget has failed.
*
* @param validator
* The validator, which caused the validation to fail, as an instance of the type {@link
* Validator}. The validator may not be null
*/
private void notifyOnValidationFailure(@NonNull final Validator<CharSequence> validator) {
for (ValidationListener<CharSequence> validationListener : validationListeners) {
validationListener.onValidationFailure(this, validator);
}
}
/**
* Notifies the listeners that the validation of the dialog's edit text widget has succeeded.
*/
private void notifyOnValidationSuccess() {
for (ValidationListener<CharSequence> validationListener : validationListeners) {
validationListener.onValidationSuccess(this);
}
}
/**
* Creates a new decorator, which allows to modify the view hierarchy of a dialog, which is
* designed according to Android 5's Material Design guidelines even on pre-Lollipop devices and
* contains an {@link EditText} widget.
*
* @param dialog
* The dialog, whose view hierarchy should be modified by the decorator, as an instance
* of the type {@link ButtonBarDialog}. The dialog may not be null
*/
public EditTextDialogDecorator(@NonNull final ButtonBarDialog dialog) {
super(dialog);
}
@Override
public final TextInputLayout getTextInputLayout() {
return textInputLayout;
}
@Override
public final EditText getEditText() {
return editText;
}
@Override
public final CharSequence getText() {
return text;
}
@Override
public final void setText(@Nullable final CharSequence text) {
this.text = text;
adaptText();
}
@Override
public final CharSequence getHint() {
return hint;
}
@Override
public final void setHint(@Nullable final CharSequence hint) {
this.hint = hint;
adaptHint();
}
@Override
public final void setHint(@StringRes final int resourceId) {
setHint(getContext().getString(resourceId));
}
@Override
public final CharSequence getHelperText() {
return helperText;
}
@Override
public final void setHelperText(@Nullable final CharSequence helperText) {
this.helperText = helperText;
adaptHelperText();
}
@Override
public final void setHelperText(@StringRes final int resourceId) {
setHelperText(getContext().getString(resourceId));
}
@Override
public final ColorStateList getErrorColor() {
return errorColor;
}
@Override
public final void setErrorColor(@ColorInt final int color) {
setErrorColor(ColorStateList.valueOf(color));
}
@Override
public final void setErrorColor(@NonNull final ColorStateList colorStateList) {
Condition.INSTANCE.ensureNotNull(colorStateList, "The color state list may not be null");
this.errorColor = colorStateList;
adaptErrorColor();
}
@Override
public final ColorStateList getHelperTextColor() {
return helperTextColor;
}
@Override
public final void setHelperTextColor(@ColorInt final int color) {
setHelperTextColor(ColorStateList.valueOf(color));
}
@Override
public final void setHelperTextColor(@NonNull final ColorStateList colorStateList) {
Condition.INSTANCE.ensureNotNull(colorStateList, "The color state list may not be null");
this.helperTextColor = colorStateList;
adaptHelperTextColor();
}
@Override
public final Collection<Validator<CharSequence>> getValidators() {
return Collections.unmodifiableSet(validators);
}
@Override
public final void addValidator(@NonNull final Validator<CharSequence> validator) {
Condition.INSTANCE.ensureNotNull(validator, "The validator may not be null");
this.validators.add(validator);
}
@Override
public final void addAllValidators(
@NonNull final Collection<Validator<CharSequence>> validators) {
Condition.INSTANCE.ensureNotNull(validators, "The collection may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@SafeVarargs
@Override
public final void addAllValidators(@NonNull final Validator<CharSequence>... validators) {
Condition.INSTANCE.ensureNotNull(validators, "The array may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@Override
public final void removeValidator(@NonNull final Validator<CharSequence> validator) {
Condition.INSTANCE.ensureNotNull(validator, "The validator may not be null");
this.validators.remove(validator);
}
@Override
public final void removeAllValidators(
@NonNull final Collection<Validator<CharSequence>> validators) {
Condition.INSTANCE.ensureNotNull(validators, "The collection may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@SafeVarargs
@Override
public final void removeAllValidators(@NonNull final Validator<CharSequence>... validators) {
Condition.INSTANCE.ensureNotNull(validators, "The array may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@Override
public final void removeAllValidators() {
this.validators.clear();
}
@Override
public final boolean validate() {
for (Validator<CharSequence> validator : validators) {
if (!validator.validate(getText())) {
showErrorText(validator.getErrorMessage());
adaptPositiveButtonEnableState(false);
notifyOnValidationFailure(validator);
return false;
}
}
showErrorText(null);
adaptPositiveButtonEnableState(true);
notifyOnValidationSuccess();
return true;
}
@Override
public final boolean isValidatedOnValueChange() {
return validateOnValueChange;
}
@Override
public final void validateOnValueChange(final boolean validateOnValueChange) {
this.validateOnValueChange = validateOnValueChange;
}
@Override
public final boolean isValidatedOnFocusLost() {
return validateOnFocusLost;
}
@Override
public final void validateOnFocusLost(final boolean validateOnFocusLost) {
this.validateOnFocusLost = validateOnFocusLost;
}
@Override
public final void addValidationListener(
@NonNull final ValidationListener<CharSequence> listener) {
validationListeners.add(listener);
}
@Override
public final void removeValidationListener(
@NonNull final ValidationListener<CharSequence> listener) {
validationListeners.remove(listener);
}
@Override
public final void onSaveInstanceState(@NonNull final Bundle outState) {
outState.putCharSequence(TEXT_EXTRA, getText());
outState.putCharSequence(HINT_EXTRA, getHint());
outState.putCharSequence(HELPER_TEXT_EXTRA, getHelperText());
outState.putParcelable(ERROR_COLOR_EXTRA, getErrorColor());
outState.putParcelable(HELPER_TEXT_COLOR_EXTRA, getHelperTextColor());
outState.putBoolean(VALIDATE_ON_VALUE_CHANGE_EXTRA, isValidatedOnValueChange());
outState.putBoolean(VALIDATE_ON_FOCUS_LOST_EXTRA, isValidatedOnFocusLost());
}
@Override
public final void onRestoreInstanceState(@NonNull final Bundle savedInstanceState) {
setText(savedInstanceState.getCharSequence(TEXT_EXTRA));
setHint(savedInstanceState.getCharSequence(HINT_EXTRA));
setHelperText(savedInstanceState.getCharSequence(HELPER_TEXT_EXTRA));
validateOnValueChange(savedInstanceState.getBoolean(VALIDATE_ON_VALUE_CHANGE_EXTRA));
validateOnFocusLost(savedInstanceState.getBoolean(VALIDATE_ON_FOCUS_LOST_EXTRA));
ColorStateList errorColor = savedInstanceState.getParcelable(ERROR_COLOR_EXTRA);
ColorStateList helperTextColor = savedInstanceState.getParcelable(HELPER_TEXT_COLOR_EXTRA);
if (errorColor != null) {
setErrorColor(errorColor);
}
if (helperTextColor != null) {
setHelperTextColor(helperTextColor);
}
validate();
}
@NonNull
@Override
protected final Map<ViewType, View> onAttach(@NonNull final Window window,
@NonNull final View view,
@NonNull final Map<ViewType, View> areas,
final Void param) {
inflateEditText();
getDialog().addDialogValidator(this);
return Collections.emptyMap();
}
@Override
protected final void onDetach() {
getDialog().removeDialogValidator(this);
editText = null;
textInputLayout = null;
}
@Override
public boolean validate(@NonNull final ValidateableDialog dialog) {
return validate();
}
} | library/src/main/java/de/mrapp/android/dialog/decorator/EditTextDialogDecorator.java | /*
* Copyright 2014 - 2018 Michael Rapp
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package de.mrapp.android.dialog.decorator;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import de.mrapp.android.dialog.DialogValidator;
import de.mrapp.android.dialog.R;
import de.mrapp.android.dialog.model.ButtonBarDialog;
import de.mrapp.android.dialog.model.ValidateableDialog;
import de.mrapp.android.dialog.view.DialogRootView.ViewType;
import de.mrapp.android.validation.ValidationListener;
import de.mrapp.android.validation.Validator;
import de.mrapp.util.Condition;
import de.mrapp.util.datastructure.ListenerList;
/**
* A decorator, which allows to modify the view hierarchy of a dialog, which is designed according
* to Android 5's Material Design guidelines even on pre-Lollipop devices and contains an {@link
* EditText} widget.
*
* @author Michael Rapp
* @since 5.1.0
*/
public class EditTextDialogDecorator extends AbstractDialogDecorator<ButtonBarDialog>
implements de.mrapp.android.dialog.model.EditTextDialogDecorator, DialogValidator {
/**
* The name of the extra, which is used to store the text of the dialog's edit text widget
* within a bundle.
*/
private static final String TEXT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::text";
/**
* The name of the extra, which is used to store the hint of the dialog's edit text widget
* within a bundle.
*/
private static final String HINT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::hint";
/**
* The name of the extra, which is used to store the helper text of the dialog's edit text
* widget within a bundle.
*/
private static final String HELPER_TEXT_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::helperText";
/**
* The name of the extra, which is used to store the error color of the dialog's edit text
* widget within a bundle.
*/
private static final String ERROR_COLOR_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::errorColor";
/**
* The name of the extra, which is used to store the helper text color of the dialog's edit text
* widget within a bundle.
*/
private static final String HELPER_TEXT_COLOR_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::helperTextColor";
/**
* The name of the extra, which is used to store, whether the dialog's edit text widget should
* be validated when its value changed, within a bundle.
*/
private static final String VALIDATE_ON_VALUE_CHANGE_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::validateOnValueChange";
/**
* The name of the extra, which is used to store, whether the dialog's edit text widget should
* be validated when it list its focus, within a bundle.
*/
private static final String VALIDATE_ON_FOCUS_LOST_EXTRA =
EditTextDialogDecorator.class.getSimpleName() + "::validateOnFocusLost";
/**
* A set, which contains the validators of the dialog's edit text widget.
*/
private final Set<Validator<CharSequence>> validators = new LinkedHashSet<>();
/**
* Contains the listeners that should be notified when the dialog's edit text widget has been
* validated.
*/
private final ListenerList<ValidationListener<CharSequence>> validationListeners =
new ListenerList<>();
/**
* The text of the dialog's edit text widget.
*/
private CharSequence text;
/**
* The hint of the dialog's edit text widget.
*/
private CharSequence hint;
/**
* The helper text of the dialog's edit text widget.
*/
private CharSequence helperText;
/**
* The error color of the dialog's edit text widget.
*/
private ColorStateList errorColor;
/**
* The helper text color of the dialog's edit text widget.
*/
private ColorStateList helperTextColor;
/**
* True, if the dialog's edit text widget is validated when its text has been changed, false
* otherwise.
*/
private boolean validateOnValueChange = true;
/**
* True, if the dialog's edit text widget is validated when its focus got lost, false
* otherwise.
*/
private boolean validateOnFocusLost = true;
/**
* The dialog's text input layout.
*/
private TextInputLayout textInputLayout;
/**
* The dialog's edit text widget.
*/
private EditText editText;
/**
* Inflates the dialog's edit text widget.
*/
private void inflateEditText() {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.edit_text_dialog, getRootView(), false);
getDialog().setView(view);
View textInputLayoutView = view.findViewById(R.id.text_input_layout);
textInputLayout = textInputLayoutView instanceof TextInputLayout ?
(TextInputLayout) textInputLayoutView : null;
View editTextView = view.findViewById(R.id.edit_text);
editText = editTextView instanceof EditText ? (EditText) editTextView : null;
adaptHint();
adaptErrorColor();
adaptHelperTextColor();
adaptHelperText();
adaptText();
validate();
adaptTextChangedListener();
adaptFocusChangeListener();
}
/**
* Adapts the text of the edit text widget, which is contained by the dialog.
*/
private void adaptText() {
if (editText != null) {
editText.setText(text);
if (text != null) {
editText.setSelection(text.length());
}
}
}
/**
* Adapts the hint of the dialog's edit text widget.
*/
private void adaptHint() {
if (textInputLayout != null) {
textInputLayout.setHint(hint);
} else if (editText != null) {
editText.setHint(hint);
}
}
/**
* Adapts the error color of the dialog's edit text widget.
*/
private void adaptErrorColor() {
if (textInputLayout != null && errorColor != null) {
textInputLayout.setErrorTextColor(errorColor);
}
}
/**
* Adapts the helper text color of the dialog's edit text widget.
*/
private void adaptHelperTextColor() {
if (textInputLayout != null && helperTextColor != null) {
textInputLayout.setHelperTextColor(helperTextColor);
}
}
/**
* Adapts the helper text of the dialog's edit text widget.
*/
private void adaptHelperText() {
if (textInputLayout != null && TextUtils.isEmpty(getText())) {
textInputLayout.setHelperText(helperText);
textInputLayout.setHelperTextEnabled(true);
}
}
/**
* Shows an error text.
*/
private void showErrorText(@Nullable final CharSequence errorText) {
if (textInputLayout != null) {
if (TextUtils.isEmpty(errorText)) {
textInputLayout.setError(null);
textInputLayout.setErrorEnabled(false);
adaptHelperTextColor();
} else {
textInputLayout.setHelperText(null);
textInputLayout.setHelperTextEnabled(false);
textInputLayout.setError(errorText);
textInputLayout.setErrorEnabled(true);
}
}
}
/**
* Adapts the listener, which allows to observe when the text of the the dialog's edit text has
* changed.
*/
private void adaptTextChangedListener() {
if (editText != null) {
editText.addTextChangedListener(createTextChangedListener());
}
}
/**
* Creates and returns a listener, which allows to observe when the text of the dialog's edit
* text has changed.
*
* @return The listener, which has been created, as an instance of the type {@link TextWatcher}.
* The listener may not be null
*/
@NonNull
private TextWatcher createTextChangedListener() {
return new TextWatcher() {
@Override
public void beforeTextChanged(final CharSequence text, final int start, final int count,
final int after) {
}
@Override
public void afterTextChanged(final Editable text) {
}
@Override
public void onTextChanged(final CharSequence text, final int start, final int before,
final int count) {
EditTextDialogDecorator.this.text = text;
if (validateOnValueChange) {
validate();
}
}
};
}
/**
* Adapts the listener, which allows to observe when the dialog's edit text has lost its focus.
*/
private void adaptFocusChangeListener() {
if (editText != null) {
editText.setOnFocusChangeListener(createFocusChangeListener());
}
}
/**
* Creates and returns a listener, which allows to validate the dialog's edit text widget when
* its focus got lost.
*
* @return The listener, which has been created, as an instance of the type {@link
* View.OnFocusChangeListener}. The listener may not be null
*/
@NonNull
private View.OnFocusChangeListener createFocusChangeListener() {
return new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (!hasFocus && validateOnFocusLost) {
validate();
}
}
};
}
/**
* Notifies the listeners that the validation of the dialog's edit text widget has failed.
*
* @param validator
* The validator, which caused the validation to fail, as an instance of the type {@link
* Validator}. The validator may not be null
*/
private void notifyOnValidationFailure(@NonNull final Validator<CharSequence> validator) {
for (ValidationListener<CharSequence> validationListener : validationListeners) {
validationListener.onValidationFailure(this, validator);
}
}
/**
* Notifies the listeners that the validation of the dialog's edit text widget has succeeded.
*/
private void notifyOnValidationSuccess() {
for (ValidationListener<CharSequence> validationListener : validationListeners) {
validationListener.onValidationSuccess(this);
}
}
/**
* Creates a new decorator, which allows to modify the view hierarchy of a dialog, which is
* designed according to Android 5's Material Design guidelines even on pre-Lollipop devices and
* contains an {@link EditText} widget.
*
* @param dialog
* The dialog, whose view hierarchy should be modified by the decorator, as an instance
* of the type {@link ButtonBarDialog}. The dialog may not be null
*/
public EditTextDialogDecorator(@NonNull final ButtonBarDialog dialog) {
super(dialog);
}
@Override
public final TextInputLayout getTextInputLayout() {
return textInputLayout;
}
@Override
public final EditText getEditText() {
return editText;
}
@Override
public final CharSequence getText() {
return text;
}
@Override
public final void setText(@Nullable final CharSequence text) {
this.text = text;
adaptText();
}
@Override
public final CharSequence getHint() {
return hint;
}
@Override
public final void setHint(@Nullable final CharSequence hint) {
this.hint = hint;
adaptHint();
}
@Override
public final void setHint(@StringRes final int resourceId) {
setHint(getContext().getString(resourceId));
}
@Override
public final CharSequence getHelperText() {
return helperText;
}
@Override
public final void setHelperText(@Nullable final CharSequence helperText) {
this.helperText = helperText;
adaptHelperText();
}
@Override
public final void setHelperText(@StringRes final int resourceId) {
setHelperText(getContext().getString(resourceId));
}
@Override
public final ColorStateList getErrorColor() {
return errorColor;
}
@Override
public final void setErrorColor(@ColorInt final int color) {
setErrorColor(ColorStateList.valueOf(color));
}
@Override
public final void setErrorColor(@NonNull final ColorStateList colorStateList) {
Condition.INSTANCE.ensureNotNull(colorStateList, "The color state list may not be null");
this.errorColor = colorStateList;
adaptErrorColor();
}
@Override
public final ColorStateList getHelperTextColor() {
return helperTextColor;
}
@Override
public final void setHelperTextColor(@ColorInt final int color) {
setHelperTextColor(ColorStateList.valueOf(color));
}
@Override
public final void setHelperTextColor(@NonNull final ColorStateList colorStateList) {
Condition.INSTANCE.ensureNotNull(colorStateList, "The color state list may not be null");
this.helperTextColor = colorStateList;
adaptHelperTextColor();
}
@Override
public final Collection<Validator<CharSequence>> getValidators() {
return Collections.unmodifiableSet(validators);
}
@Override
public final void addValidator(@NonNull final Validator<CharSequence> validator) {
Condition.INSTANCE.ensureNotNull(validator, "The validator may not be null");
this.validators.add(validator);
}
@Override
public final void addAllValidators(
@NonNull final Collection<Validator<CharSequence>> validators) {
Condition.INSTANCE.ensureNotNull(validators, "The collection may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@SafeVarargs
@Override
public final void addAllValidators(@NonNull final Validator<CharSequence>... validators) {
Condition.INSTANCE.ensureNotNull(validators, "The array may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@Override
public final void removeValidator(@NonNull final Validator<CharSequence> validator) {
Condition.INSTANCE.ensureNotNull(validator, "The validator may not be null");
this.validators.remove(validator);
}
@Override
public final void removeAllValidators(
@NonNull final Collection<Validator<CharSequence>> validators) {
Condition.INSTANCE.ensureNotNull(validators, "The collection may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@SafeVarargs
@Override
public final void removeAllValidators(@NonNull final Validator<CharSequence>... validators) {
Condition.INSTANCE.ensureNotNull(validators, "The array may not be null");
for (Validator<CharSequence> validator : validators) {
addValidator(validator);
}
}
@Override
public final void removeAllValidators() {
this.validators.clear();
}
@Override
public final boolean validate() {
for (Validator<CharSequence> validator : validators) {
if (!validator.validate(getText())) {
showErrorText(validator.getErrorMessage());
notifyOnValidationFailure(validator);
return false;
}
}
showErrorText(null);
notifyOnValidationSuccess();
return true;
}
@Override
public final boolean isValidatedOnValueChange() {
return validateOnValueChange;
}
@Override
public final void validateOnValueChange(final boolean validateOnValueChange) {
this.validateOnValueChange = validateOnValueChange;
}
@Override
public final boolean isValidatedOnFocusLost() {
return validateOnFocusLost;
}
@Override
public final void validateOnFocusLost(final boolean validateOnFocusLost) {
this.validateOnFocusLost = validateOnFocusLost;
}
@Override
public final void addValidationListener(
@NonNull final ValidationListener<CharSequence> listener) {
validationListeners.add(listener);
}
@Override
public final void removeValidationListener(
@NonNull final ValidationListener<CharSequence> listener) {
validationListeners.remove(listener);
}
@Override
public final void onSaveInstanceState(@NonNull final Bundle outState) {
outState.putCharSequence(TEXT_EXTRA, getText());
outState.putCharSequence(HINT_EXTRA, getHint());
outState.putCharSequence(HELPER_TEXT_EXTRA, getHelperText());
outState.putParcelable(ERROR_COLOR_EXTRA, getErrorColor());
outState.putParcelable(HELPER_TEXT_COLOR_EXTRA, getHelperTextColor());
outState.putBoolean(VALIDATE_ON_VALUE_CHANGE_EXTRA, isValidatedOnValueChange());
outState.putBoolean(VALIDATE_ON_FOCUS_LOST_EXTRA, isValidatedOnFocusLost());
}
@Override
public final void onRestoreInstanceState(@NonNull final Bundle savedInstanceState) {
setText(savedInstanceState.getCharSequence(TEXT_EXTRA));
setHint(savedInstanceState.getCharSequence(HINT_EXTRA));
setHelperText(savedInstanceState.getCharSequence(HELPER_TEXT_EXTRA));
validateOnValueChange(savedInstanceState.getBoolean(VALIDATE_ON_VALUE_CHANGE_EXTRA));
validateOnFocusLost(savedInstanceState.getBoolean(VALIDATE_ON_FOCUS_LOST_EXTRA));
ColorStateList errorColor = savedInstanceState.getParcelable(ERROR_COLOR_EXTRA);
ColorStateList helperTextColor = savedInstanceState.getParcelable(HELPER_TEXT_COLOR_EXTRA);
if (errorColor != null) {
setErrorColor(errorColor);
}
if (helperTextColor != null) {
setHelperTextColor(helperTextColor);
}
validate();
}
@NonNull
@Override
protected final Map<ViewType, View> onAttach(@NonNull final Window window,
@NonNull final View view,
@NonNull final Map<ViewType, View> areas,
final Void param) {
inflateEditText();
getDialog().addDialogValidator(this);
return Collections.emptyMap();
}
@Override
protected final void onDetach() {
getDialog().removeDialogValidator(this);
editText = null;
textInputLayout = null;
}
@Override
public boolean validate(@NonNull final ValidateableDialog dialog) {
return validate();
}
} | Disable the positive button of an EditTextDialog when the validation failed.
| library/src/main/java/de/mrapp/android/dialog/decorator/EditTextDialogDecorator.java | Disable the positive button of an EditTextDialog when the validation failed. |
|
Java | apache-2.0 | ba207248c844652951b43aaeaedb460de1ac69cc | 0 | quanticc/sentry,quanticc/sentry,quanticc/sentry | package top.quantic.sentry.event;
import de.androidpit.colorthief.ColorThief;
import de.androidpit.colorthief.MMCQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.util.EmbedBuilder;
import top.quantic.sentry.web.rest.vm.TwitchStream;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public class TwitchStreamEvent extends SentryEvent {
private static final Logger log = LoggerFactory.getLogger(TwitchStreamEvent.class);
public TwitchStreamEvent(TwitchStream source) {
super(source);
}
@Override
public TwitchStream getSource() {
return (TwitchStream) super.getSource();
}
@Override
public String getContentId() {
return Integer.toHexString(Objects.hash(getSource().getId()));
}
@Override
public String asContent() {
TwitchStream stream = getSource();
return "@here " + stream.getChannel().getDisplayName() + " is now live on <" + stream.getChannel().getUrl() + "> !";
}
@Override
public EmbedObject asEmbed(Map<String, Object> dataMap) {
TwitchStream stream = getSource();
return new EmbedBuilder()
.withAuthorIcon(stream.getChannel().getLogo())
.withAuthorName(stream.getChannel().getDisplayName())
.withTitle(stream.getChannel().getStatus())
.withColor(getDominantColor(stream.getChannel().getLogo()))
.withThumbnail(stream.getChannel().getLogo())
.withUrl(stream.getChannel().getUrl())
.withImage(stream.getPreview().get("medium"))
.withFooterIcon("https://www.twitch.tv/favicon.ico")
.withFooterText("twitch.tv")
.appendField("Playing", stream.getGame(), true)
.appendField("Viewers", stream.getViewers() + "", true)
.build();
}
@Override
public Map<String, Object> asMap() {
TwitchStream stream = getSource();
Map<String, Object> map = new LinkedHashMap<>();
map.put("avatar", stream.getChannel().getLogo());
map.put("name", stream.getChannel().getDisplayName());
map.put("title", stream.getChannel().getStatus());
map.put("game", stream.getGame());
map.put("viewers", stream.getViewers());
map.put("preview", stream.getPreview().get("medium"));
map.put("url", stream.getChannel().getUrl());
map.put("createdAt", stream.getCreatedAt());
return map;
}
private Color getDominantColor(String urlStr) {
try {
URL url = new URL(urlStr);
BufferedImage image = ImageIO.read(url);
MMCQ.CMap result = ColorThief.getColorMap(image, 5);
MMCQ.VBox vBox = result.vboxes.get(0);
int[] rgb = vBox.avg(false);
return new Color(rgb[0], rgb[1], rgb[2]);
} catch (Exception e) {
log.warn("Could not analyze image", e);
}
return new Color(0x6441A4);
}
}
| src/main/java/top/quantic/sentry/event/TwitchStreamEvent.java | package top.quantic.sentry.event;
import de.androidpit.colorthief.ColorThief;
import de.androidpit.colorthief.MMCQ;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sx.blah.discord.api.internal.json.objects.EmbedObject;
import sx.blah.discord.util.EmbedBuilder;
import top.quantic.sentry.web.rest.vm.TwitchStream;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public class TwitchStreamEvent extends SentryEvent {
private static final Logger log = LoggerFactory.getLogger(TwitchStreamEvent.class);
public TwitchStreamEvent(TwitchStream source) {
super(source);
}
@Override
public TwitchStream getSource() {
return (TwitchStream) super.getSource();
}
@Override
public String getContentId() {
return Integer.toHexString(Objects.hash(getSource().getId()));
}
@Override
public String asContent() {
TwitchStream stream = getSource();
return "@here " + stream.getChannel().getDisplayName() + " is now live on <" + stream.getChannel().getUrl() + "> !";
}
@Override
public EmbedObject asEmbed(Map<String, Object> dataMap) {
TwitchStream stream = getSource();
return new EmbedBuilder()
.withAuthorIcon(stream.getChannel().getLogo())
.withAuthorName(stream.getChannel().getDisplayName())
.withTitle(stream.getChannel().getStatus())
.withColor(getDominantColor(stream.getChannel().getLogo()))
.withThumbnail(stream.getChannel().getLogo())
.withUrl(stream.getChannel().getUrl())
.withImage(stream.getPreview().get("medium"))
.withFooterIcon("https://www.twitch.tv/favicon.ico")
.withFooterText("twitch.tv")
.appendField("Playing", stream.getChannel().getStatus(), true)
.appendField("Viewers", stream.getViewers() + "", true)
.build();
}
@Override
public Map<String, Object> asMap() {
TwitchStream stream = getSource();
Map<String, Object> map = new LinkedHashMap<>();
map.put("avatar", stream.getChannel().getLogo());
map.put("name", stream.getChannel().getDisplayName());
map.put("title", stream.getChannel().getStatus());
map.put("game", stream.getGame());
map.put("viewers", stream.getViewers());
map.put("preview", stream.getPreview().get("medium"));
map.put("url", stream.getChannel().getUrl());
map.put("createdAt", stream.getCreatedAt());
return map;
}
private Color getDominantColor(String urlStr) {
try {
URL url = new URL(urlStr);
BufferedImage image = ImageIO.read(url);
MMCQ.CMap result = ColorThief.getColorMap(image, 5);
MMCQ.VBox vBox = result.vboxes.get(0);
int[] rgb = vBox.avg(false);
return new Color(rgb[0], rgb[1], rgb[2]);
} catch (Exception e) {
log.warn("Could not analyze image", e);
}
return new Color(0x6441A4);
}
}
| Fix embed field incorrectly set
| src/main/java/top/quantic/sentry/event/TwitchStreamEvent.java | Fix embed field incorrectly set |
|
Java | apache-2.0 | c76600eb02581040f785681514f9a4b01cdb944c | 0 | vorburger/MariaDB4j,vorburger/MariaDB4j | /*
* #%L
* MariaDB4j
* %%
* Copyright (C) 2012 - 2017 Michael Vorburger
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package ch.vorburger.mariadb4j;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.vorburger.exec.ManagedProcess;
import ch.vorburger.exec.ManagedProcessBuilder;
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.exec.OutputStreamLogDispatcher;
/**
* Provides capability to install, start, and use an embedded database.
*
* @author Michael Vorburger
* @author Michael Seaton
*/
public class DB {
private static final Logger logger = LoggerFactory.getLogger(DB.class);
protected final DBConfiguration configuration;
private File baseDir;
private File libDir;
private File dataDir;
private ManagedProcess mysqldProcess;
protected int dbStartMaxWaitInMS = 30000;
protected DB(DBConfiguration config) {
this.configuration = config;
}
public DBConfiguration getConfiguration() {
return configuration;
}
/**
* This factory method is the mechanism for constructing a new embedded database for use. This
* method automatically installs the database and prepares it for use.
*
* @param config Configuration of the embedded instance
* @return a new DB instance
* @throws ManagedProcessException if something fatal went wrong
*/
public static DB newEmbeddedDB(DBConfiguration config) throws ManagedProcessException {
DB db = new DB(config);
db.prepareDirectories();
db.unpackEmbeddedDb();
db.install();
return db;
}
/**
* This factory method is the mechanism for constructing a new embedded database for use. This
* method automatically installs the database and prepares it for use with default
* configuration, allowing only for specifying port.
*
* @param port the port to start the embedded database on
* @return a new DB instance
* @throws ManagedProcessException if something fatal went wrong
*/
public static DB newEmbeddedDB(int port) throws ManagedProcessException {
DBConfigurationBuilder config = new DBConfigurationBuilder();
config.setPort(port);
return newEmbeddedDB(config.build());
}
ManagedProcess installPreparation() throws ManagedProcessException, IOException {
logger.info("Installing a new embedded database to: " + baseDir);
File installDbCmdFile = newExecutableFile("bin", "mysql_install_db");
if (!installDbCmdFile.exists())
installDbCmdFile = newExecutableFile("scripts", "mysql_install_db");
if (!installDbCmdFile.exists())
throw new ManagedProcessException(
"mysql_install_db was not found, neither in bin/ nor in scripts/ under " + baseDir.getAbsolutePath());
ManagedProcessBuilder builder = new ManagedProcessBuilder(installDbCmdFile);
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysql_install_db"));
builder.getEnvironment().put(configuration.getOSLibraryEnvironmentVarName(), libDir.getAbsolutePath());
builder.addFileArgument("--datadir", dataDir).setWorkingDirectory(baseDir);
if (!configuration.isWindows()) {
builder.addFileArgument("--basedir", baseDir);
builder.addArgument("--no-defaults");
builder.addArgument("--force");
builder.addArgument("--skip-name-resolve");
// builder.addArgument("--verbose");
}
ManagedProcess mysqlInstallProcess = builder.build();
return mysqlInstallProcess;
}
/**
* Installs the database to the location specified in the configuration.
*
* @throws ManagedProcessException if something fatal went wrong
*/
synchronized protected void install() throws ManagedProcessException {
try {
ManagedProcess mysqlInstallProcess = installPreparation();
mysqlInstallProcess.start();
mysqlInstallProcess.waitForExit();
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while installing the database", e);
}
logger.info("Installation complete.");
}
protected String getWinExeExt() {
return configuration.isWindows() ? ".exe" : "";
}
/**
* Starts up the database, using the data directory and port specified in the configuration.
*
* @throws ManagedProcessException if something fatal went wrong
*/
public synchronized void start() throws ManagedProcessException {
logger.info("Starting up the database...");
boolean ready = false;
try {
mysqldProcess = startPreparation();
ready = mysqldProcess.startAndWaitForConsoleMessageMaxMs(getReadyForConnectionsTag(), dbStartMaxWaitInMS);
} catch (Exception e) {
logger.error("failed to start mysqld", e);
throw new ManagedProcessException("An error occurred while starting the database", e);
}
if (!ready) {
if (mysqldProcess.isAlive())
mysqldProcess.destroy();
throw new ManagedProcessException("Database does not seem to have started up correctly? Magic string not seen in "
+ dbStartMaxWaitInMS + "ms: " + getReadyForConnectionsTag() + mysqldProcess.getLastConsoleLines());
}
logger.info("Database startup complete.");
}
protected String getReadyForConnectionsTag() {
return "mysqld" + getWinExeExt() + ": ready for connections.";
}
synchronized ManagedProcess startPreparation() throws ManagedProcessException, IOException {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysqld"));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysqld"));
builder.getEnvironment().put(configuration.getOSLibraryEnvironmentVarName(), libDir.getAbsolutePath());
builder.addArgument("--no-defaults"); // *** THIS MUST COME FIRST ***
builder.addArgument("--console");
if(this.configuration.isSecurityDisabled()) {
builder.addArgument("--skip-grant-tables");
}
if (! hasArgument("--max_allowed_packet")) {
builder.addArgument("--max_allowed_packet=64M");
}
builder.addFileArgument("--basedir", baseDir).setWorkingDirectory(baseDir);
builder.addFileArgument("--datadir", dataDir);
addPortAndMaybeSocketArguments(builder);
for (String arg : configuration.getArgs()) {
builder.addArgument(arg);
}
cleanupOnExit();
// because cleanupOnExit() just installed our (class DB) own
// Shutdown hook, we don't need the one from ManagedProcess:
builder.setDestroyOnShutdown(false);
logger.info("mysqld executable: " + builder.getExecutable());
return builder.build();
}
protected boolean hasArgument(final String argumentName) {
for (String argument : this.configuration.getArgs()) {
if (argument.startsWith(argumentName)) {
return true;
}
}
return false;
}
protected File newExecutableFile(String dir, String exec) {
return new File(baseDir, dir + "/" + exec + getWinExeExt());
}
protected void addPortAndMaybeSocketArguments(ManagedProcessBuilder builder) throws IOException {
builder.addArgument("--port=" + configuration.getPort());
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
}
}
protected void addSocketOrPortArgument(ManagedProcessBuilder builder) throws IOException {
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
} else {
builder.addArgument("--port=" + configuration.getPort());
}
}
/**
* Config Socket as absolute path. By default this is the case because DBConfigurationBuilder
* creates the socket in /tmp, but if a user uses setSocket() he may give a relative location,
* so we double check.
*
* @return config.getSocket() as File getAbsolutePath()
*/
protected File getAbsoluteSocketFile() {
String socket = configuration.getSocket();
File socketFile = new File(socket);
return socketFile.getAbsoluteFile();
}
public void source(String resource) throws ManagedProcessException {
source(resource, null, null, null);
}
/**
* Takes in a string that represents a resource on the classpath and sources it via the mysql
* command line tool.
*
* @param resource the path to a resource on the classpath to source
* @param username the username used to login to the database
* @param password the password used to login to the database
* @param dbName the name of the database (schema) to source into
* @throws ManagedProcessException if something fatal went wrong
*/
public void source(String resource, String username, String password, String dbName) throws ManagedProcessException {
InputStream from = getClass().getClassLoader().getResourceAsStream(resource);
if (from == null)
throw new IllegalArgumentException("Could not find script file on the classpath at: " + resource);
run("script file sourced from the classpath at: " + resource, from, username, password, dbName);
}
public void run(String command, String username, String password, String dbName) throws ManagedProcessException {
InputStream from = IOUtils.toInputStream(command, Charset.defaultCharset());
run("command: " + command, from, username, password, dbName);
}
public void run(String command) throws ManagedProcessException {
run(command, null, null, null);
}
public void run(String command, String username, String password) throws ManagedProcessException {
run(command, username, password, null);
}
protected void run(String logInfoText, InputStream fromIS, String username, String password, String dbName)
throws ManagedProcessException {
logger.info("Running a " + logInfoText);
try {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysql"));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysql"));
builder.setWorkingDirectory(baseDir);
if (username != null && !username.isEmpty())
builder.addArgument("-u", username);
if (password != null && !password.isEmpty())
builder.addArgument("-p", password);
if (dbName != null && !dbName.isEmpty())
builder.addArgument("-D", dbName);
addSocketOrPortArgument(builder);
if (fromIS != null)
builder.setInputStream(fromIS);
ManagedProcess process = builder.build();
process.start();
process.waitForExit();
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while running a " + logInfoText, e);
} finally {
IOUtils.closeQuietly(fromIS);
}
logger.info("Successfully ran the " + logInfoText);
}
public void createDB(String dbName) throws ManagedProcessException {
this.run("create database if not exists `" + dbName + "`;");
}
public void createDB(String dbName, String username, String password) throws ManagedProcessException {
this.run("create database if not exists `" + dbName + "`;", username, password);
}
protected OutputStreamLogDispatcher getOutputStreamLogDispatcher(@SuppressWarnings("unused") String exec) {
return new MariaDBOutputStreamLogDispatcher();
}
/**
* Stops the database.
*
* @throws ManagedProcessException if something fatal went wrong
*/
public synchronized void stop() throws ManagedProcessException {
if (mysqldProcess.isAlive()) {
logger.debug("Stopping the database...");
mysqldProcess.destroy();
logger.info("Database stopped.");
} else {
logger.debug("Database was already stopped.");
}
}
/**
* Based on the current OS, unpacks the appropriate version of MariaDB to the file system based
* on the configuration.
*/
protected void unpackEmbeddedDb() {
if (configuration.getBinariesClassPathLocation() == null) {
logger.info("Not unpacking any embedded database (as BinariesClassPathLocation configuration is null)");
return;
}
try {
Util.extractFromClasspathToFile(configuration.getBinariesClassPathLocation(), baseDir);
if (!configuration.isWindows()) {
Util.forceExecutable(newExecutableFile("bin", "my_print_defaults"));
Util.forceExecutable(newExecutableFile("bin", "mysql_install_db"));
Util.forceExecutable(newExecutableFile("scripts", "mysql_install_db"));
Util.forceExecutable(newExecutableFile("bin", "mysqld"));
Util.forceExecutable(newExecutableFile("bin", "mysqldump"));
Util.forceExecutable(newExecutableFile("bin", "mysql"));
}
} catch (IOException e) {
throw new RuntimeException("Error unpacking embedded DB", e);
}
}
/**
* If the data directory specified in the configuration is a temporary directory, this deletes
* any previous version. It also makes sure that the directory exists.
*
* @throws ManagedProcessException if something fatal went wrong
*/
protected void prepareDirectories() throws ManagedProcessException {
baseDir = Util.getDirectory(configuration.getBaseDir());
libDir = Util.getDirectory(configuration.getLibDir());
try {
String dataDirPath = configuration.getDataDir();
if (Util.isTemporaryDirectory(dataDirPath)) {
FileUtils.deleteDirectory(new File(dataDirPath));
}
dataDir = Util.getDirectory(dataDirPath);
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while preparing the data directory", e);
}
}
/**
* Adds a shutdown hook to ensure that when the JVM exits, the database is stopped, and any
* temporary data directories are cleaned up.
*/
protected void cleanupOnExit() {
String threadName = "Shutdown Hook Deletion Thread for Temporary DB " + dataDir.toString();
final DB db = this;
Runtime.getRuntime().addShutdownHook(new Thread(threadName) {
@Override
public void run() {
// ManagedProcess DestroyOnShutdown ProcessDestroyer does
// something similar, but it shouldn't hurt to better be save
// than sorry and do it again ourselves here as well.
try {
// Shut up and don't log if it was already stop() before
if (mysqldProcess != null && mysqldProcess.isAlive()) {
logger.info("cleanupOnExit() ShutdownHook now stopping database");
db.stop();
}
} catch (ManagedProcessException e) {
logger.warn("cleanupOnExit() ShutdownHook: An error occurred while stopping the database", e);
}
if (dataDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB data directory: " + dataDir);
FileUtils.deleteQuietly(dataDir);
}
if (baseDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB base directory: " + baseDir);
FileUtils.deleteQuietly(baseDir);
}
}
});
}
// The dump*() methods are intentionally *NOT* made "synchronized",
// (even though with --lock-tables one could not run two dumps concurrently anyway)
// because in theory this could cause a long-running dump to deadlock an application
// wanting to stop() a DB. Let it thus be a caller's responsibility to not dump
// concurrently (and if she does, it just fails, which is much better than an
// unexpected deadlock).
public ManagedProcess dumpXML(File outputFile, String dbName, String user, String password)
throws IOException, ManagedProcessException {
return dump(outputFile, Arrays.asList(dbName), true, true, true, user, password);
}
public ManagedProcess dumpSQL(File outputFile, String dbName, String user, String password)
throws IOException, ManagedProcessException {
return dump(outputFile, Arrays.asList(dbName), true, true, false, user, password);
}
protected ManagedProcess dump(File outputFile, List<String> dbNamesToDump,
boolean compactDump, boolean lockTables, boolean asXml,
String user, String password)
throws ManagedProcessException, IOException {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysqldump"));
builder.addStdOut(new BufferedOutputStream(new FileOutputStream(outputFile)));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysqldump"));
builder.addArgument("--port=" + configuration.getPort());
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
}
if (lockTables) {
builder.addArgument("--flush-logs");
builder.addArgument("--lock-tables");
}
if (compactDump) {
builder.addArgument("--compact");
}
if (asXml) {
builder.addArgument("--xml");
}
if (StringUtils.isNotBlank(user)) {
builder.addArgument("-u");
builder.addArgument(user);
if (StringUtils.isNotBlank(password)) {
builder.addArgument("-p" + password);
}
}
builder.addArgument(StringUtils.join(dbNamesToDump, StringUtils.SPACE));
builder.setDestroyOnShutdown(true);
return builder.build();
}
}
| mariaDB4j-core/src/main/java/ch/vorburger/mariadb4j/DB.java | /*
* #%L
* MariaDB4j
* %%
* Copyright (C) 2012 - 2017 Michael Vorburger
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package ch.vorburger.mariadb4j;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.vorburger.exec.ManagedProcess;
import ch.vorburger.exec.ManagedProcessBuilder;
import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.exec.OutputStreamLogDispatcher;
/**
* Provides capability to install, start, and use an embedded database.
*
* @author Michael Vorburger
* @author Michael Seaton
*/
public class DB {
private static final Logger logger = LoggerFactory.getLogger(DB.class);
protected final DBConfiguration configuration;
private File baseDir;
private File libDir;
private File dataDir;
private ManagedProcess mysqldProcess;
protected int dbStartMaxWaitInMS = 30000;
protected DB(DBConfiguration config) {
this.configuration = config;
}
public DBConfiguration getConfiguration() {
return configuration;
}
/**
* This factory method is the mechanism for constructing a new embedded database for use. This
* method automatically installs the database and prepares it for use.
*
* @param config Configuration of the embedded instance
* @return a new DB instance
* @throws ManagedProcessException if something fatal went wrong
*/
public static DB newEmbeddedDB(DBConfiguration config) throws ManagedProcessException {
DB db = new DB(config);
db.prepareDirectories();
db.unpackEmbeddedDb();
db.install();
return db;
}
/**
* This factory method is the mechanism for constructing a new embedded database for use. This
* method automatically installs the database and prepares it for use with default
* configuration, allowing only for specifying port.
*
* @param port the port to start the embedded database on
* @return a new DB instance
* @throws ManagedProcessException if something fatal went wrong
*/
public static DB newEmbeddedDB(int port) throws ManagedProcessException {
DBConfigurationBuilder config = new DBConfigurationBuilder();
config.setPort(port);
return newEmbeddedDB(config.build());
}
ManagedProcess installPreparation() throws ManagedProcessException, IOException {
logger.info("Installing a new embedded database to: " + baseDir);
File installDbCmdFile = newExecutableFile("bin", "mysql_install_db");
if (!installDbCmdFile.exists())
installDbCmdFile = newExecutableFile("scripts", "mysql_install_db");
if (!installDbCmdFile.exists())
throw new ManagedProcessException(
"mysql_install_db was not found, neither in bin/ nor in scripts/ under " + baseDir.getAbsolutePath());
ManagedProcessBuilder builder = new ManagedProcessBuilder(installDbCmdFile);
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysql_install_db"));
builder.getEnvironment().put(configuration.getOSLibraryEnvironmentVarName(), libDir.getAbsolutePath());
builder.addFileArgument("--datadir", dataDir).setWorkingDirectory(baseDir);
if (!configuration.isWindows()) {
builder.addFileArgument("--basedir", baseDir);
builder.addArgument("--no-defaults");
builder.addArgument("--force");
builder.addArgument("--skip-name-resolve");
// builder.addArgument("--verbose");
}
ManagedProcess mysqlInstallProcess = builder.build();
return mysqlInstallProcess;
}
/**
* Installs the database to the location specified in the configuration.
*
* @throws ManagedProcessException if something fatal went wrong
*/
synchronized protected void install() throws ManagedProcessException {
try {
ManagedProcess mysqlInstallProcess = installPreparation();
mysqlInstallProcess.start();
mysqlInstallProcess.waitForExit();
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while installing the database", e);
}
logger.info("Installation complete.");
}
protected String getWinExeExt() {
return configuration.isWindows() ? ".exe" : "";
}
/**
* Starts up the database, using the data directory and port specified in the configuration.
*
* @throws ManagedProcessException if something fatal went wrong
*/
public synchronized void start() throws ManagedProcessException {
logger.info("Starting up the database...");
boolean ready = false;
try {
mysqldProcess = startPreparation();
ready = mysqldProcess.startAndWaitForConsoleMessageMaxMs(getReadyForConnectionsTag(), dbStartMaxWaitInMS);
} catch (Exception e) {
logger.error("failed to start mysqld", e);
throw new ManagedProcessException("An error occurred while starting the database", e);
}
if (!ready) {
if (mysqldProcess.isAlive())
mysqldProcess.destroy();
throw new ManagedProcessException("Database does not seem to have started up correctly? Magic string not seen in "
+ dbStartMaxWaitInMS + "ms: " + getReadyForConnectionsTag() + mysqldProcess.getLastConsoleLines());
}
logger.info("Database startup complete.");
}
protected String getReadyForConnectionsTag() {
return "mysqld" + getWinExeExt() + ": ready for connections.";
}
synchronized ManagedProcess startPreparation() throws ManagedProcessException, IOException {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysqld"));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysqld"));
builder.getEnvironment().put(configuration.getOSLibraryEnvironmentVarName(), libDir.getAbsolutePath());
builder.addArgument("--no-defaults"); // *** THIS MUST COME FIRST ***
builder.addArgument("--console");
if(this.configuration.isSecurityDisabled()) {
builder.addArgument("--skip-grant-tables");
}
builder.addArgument("--max_allowed_packet=64M");
builder.addFileArgument("--basedir", baseDir).setWorkingDirectory(baseDir);
builder.addFileArgument("--datadir", dataDir);
addPortAndMaybeSocketArguments(builder);
for (String arg : configuration.getArgs()) {
builder.addArgument(arg);
}
cleanupOnExit();
// because cleanupOnExit() just installed our (class DB) own
// Shutdown hook, we don't need the one from ManagedProcess:
builder.setDestroyOnShutdown(false);
logger.info("mysqld executable: " + builder.getExecutable());
return builder.build();
}
protected File newExecutableFile(String dir, String exec) {
return new File(baseDir, dir + "/" + exec + getWinExeExt());
}
protected void addPortAndMaybeSocketArguments(ManagedProcessBuilder builder) throws IOException {
builder.addArgument("--port=" + configuration.getPort());
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
}
}
protected void addSocketOrPortArgument(ManagedProcessBuilder builder) throws IOException {
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
} else {
builder.addArgument("--port=" + configuration.getPort());
}
}
/**
* Config Socket as absolute path. By default this is the case because DBConfigurationBuilder
* creates the socket in /tmp, but if a user uses setSocket() he may give a relative location,
* so we double check.
*
* @return config.getSocket() as File getAbsolutePath()
*/
protected File getAbsoluteSocketFile() {
String socket = configuration.getSocket();
File socketFile = new File(socket);
return socketFile.getAbsoluteFile();
}
public void source(String resource) throws ManagedProcessException {
source(resource, null, null, null);
}
/**
* Takes in a string that represents a resource on the classpath and sources it via the mysql
* command line tool.
*
* @param resource the path to a resource on the classpath to source
* @param username the username used to login to the database
* @param password the password used to login to the database
* @param dbName the name of the database (schema) to source into
* @throws ManagedProcessException if something fatal went wrong
*/
public void source(String resource, String username, String password, String dbName) throws ManagedProcessException {
InputStream from = getClass().getClassLoader().getResourceAsStream(resource);
if (from == null)
throw new IllegalArgumentException("Could not find script file on the classpath at: " + resource);
run("script file sourced from the classpath at: " + resource, from, username, password, dbName);
}
public void run(String command, String username, String password, String dbName) throws ManagedProcessException {
InputStream from = IOUtils.toInputStream(command, Charset.defaultCharset());
run("command: " + command, from, username, password, dbName);
}
public void run(String command) throws ManagedProcessException {
run(command, null, null, null);
}
public void run(String command, String username, String password) throws ManagedProcessException {
run(command, username, password, null);
}
protected void run(String logInfoText, InputStream fromIS, String username, String password, String dbName)
throws ManagedProcessException {
logger.info("Running a " + logInfoText);
try {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysql"));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysql"));
builder.setWorkingDirectory(baseDir);
if (username != null && !username.isEmpty())
builder.addArgument("-u", username);
if (password != null && !password.isEmpty())
builder.addArgument("-p", password);
if (dbName != null && !dbName.isEmpty())
builder.addArgument("-D", dbName);
addSocketOrPortArgument(builder);
if (fromIS != null)
builder.setInputStream(fromIS);
ManagedProcess process = builder.build();
process.start();
process.waitForExit();
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while running a " + logInfoText, e);
} finally {
IOUtils.closeQuietly(fromIS);
}
logger.info("Successfully ran the " + logInfoText);
}
public void createDB(String dbName) throws ManagedProcessException {
this.run("create database if not exists `" + dbName + "`;");
}
public void createDB(String dbName, String username, String password) throws ManagedProcessException {
this.run("create database if not exists `" + dbName + "`;", username, password);
}
protected OutputStreamLogDispatcher getOutputStreamLogDispatcher(@SuppressWarnings("unused") String exec) {
return new MariaDBOutputStreamLogDispatcher();
}
/**
* Stops the database.
*
* @throws ManagedProcessException if something fatal went wrong
*/
public synchronized void stop() throws ManagedProcessException {
if (mysqldProcess.isAlive()) {
logger.debug("Stopping the database...");
mysqldProcess.destroy();
logger.info("Database stopped.");
} else {
logger.debug("Database was already stopped.");
}
}
/**
* Based on the current OS, unpacks the appropriate version of MariaDB to the file system based
* on the configuration.
*/
protected void unpackEmbeddedDb() {
if (configuration.getBinariesClassPathLocation() == null) {
logger.info("Not unpacking any embedded database (as BinariesClassPathLocation configuration is null)");
return;
}
try {
Util.extractFromClasspathToFile(configuration.getBinariesClassPathLocation(), baseDir);
if (!configuration.isWindows()) {
Util.forceExecutable(newExecutableFile("bin", "my_print_defaults"));
Util.forceExecutable(newExecutableFile("bin", "mysql_install_db"));
Util.forceExecutable(newExecutableFile("scripts", "mysql_install_db"));
Util.forceExecutable(newExecutableFile("bin", "mysqld"));
Util.forceExecutable(newExecutableFile("bin", "mysqldump"));
Util.forceExecutable(newExecutableFile("bin", "mysql"));
}
} catch (IOException e) {
throw new RuntimeException("Error unpacking embedded DB", e);
}
}
/**
* If the data directory specified in the configuration is a temporary directory, this deletes
* any previous version. It also makes sure that the directory exists.
*
* @throws ManagedProcessException if something fatal went wrong
*/
protected void prepareDirectories() throws ManagedProcessException {
baseDir = Util.getDirectory(configuration.getBaseDir());
libDir = Util.getDirectory(configuration.getLibDir());
try {
String dataDirPath = configuration.getDataDir();
if (Util.isTemporaryDirectory(dataDirPath)) {
FileUtils.deleteDirectory(new File(dataDirPath));
}
dataDir = Util.getDirectory(dataDirPath);
} catch (Exception e) {
throw new ManagedProcessException("An error occurred while preparing the data directory", e);
}
}
/**
* Adds a shutdown hook to ensure that when the JVM exits, the database is stopped, and any
* temporary data directories are cleaned up.
*/
protected void cleanupOnExit() {
String threadName = "Shutdown Hook Deletion Thread for Temporary DB " + dataDir.toString();
final DB db = this;
Runtime.getRuntime().addShutdownHook(new Thread(threadName) {
@Override
public void run() {
// ManagedProcess DestroyOnShutdown ProcessDestroyer does
// something similar, but it shouldn't hurt to better be save
// than sorry and do it again ourselves here as well.
try {
// Shut up and don't log if it was already stop() before
if (mysqldProcess != null && mysqldProcess.isAlive()) {
logger.info("cleanupOnExit() ShutdownHook now stopping database");
db.stop();
}
} catch (ManagedProcessException e) {
logger.warn("cleanupOnExit() ShutdownHook: An error occurred while stopping the database", e);
}
if (dataDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB data directory: " + dataDir);
FileUtils.deleteQuietly(dataDir);
}
if (baseDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB base directory: " + baseDir);
FileUtils.deleteQuietly(baseDir);
}
}
});
}
// The dump*() methods are intentionally *NOT* made "synchronized",
// (even though with --lock-tables one could not run two dumps concurrently anyway)
// because in theory this could cause a long-running dump to deadlock an application
// wanting to stop() a DB. Let it thus be a caller's responsibility to not dump
// concurrently (and if she does, it just fails, which is much better than an
// unexpected deadlock).
public ManagedProcess dumpXML(File outputFile, String dbName, String user, String password)
throws IOException, ManagedProcessException {
return dump(outputFile, Arrays.asList(dbName), true, true, true, user, password);
}
public ManagedProcess dumpSQL(File outputFile, String dbName, String user, String password)
throws IOException, ManagedProcessException {
return dump(outputFile, Arrays.asList(dbName), true, true, false, user, password);
}
protected ManagedProcess dump(File outputFile, List<String> dbNamesToDump,
boolean compactDump, boolean lockTables, boolean asXml,
String user, String password)
throws ManagedProcessException, IOException {
ManagedProcessBuilder builder = new ManagedProcessBuilder(newExecutableFile("bin", "mysqldump"));
builder.addStdOut(new BufferedOutputStream(new FileOutputStream(outputFile)));
builder.setOutputStreamLogDispatcher(getOutputStreamLogDispatcher("mysqldump"));
builder.addArgument("--port=" + configuration.getPort());
if (!configuration.isWindows()) {
builder.addFileArgument("--socket", getAbsoluteSocketFile());
}
if (lockTables) {
builder.addArgument("--flush-logs");
builder.addArgument("--lock-tables");
}
if (compactDump) {
builder.addArgument("--compact");
}
if (asXml) {
builder.addArgument("--xml");
}
if (StringUtils.isNotBlank(user)) {
builder.addArgument("-u");
builder.addArgument(user);
if (StringUtils.isNotBlank(password)) {
builder.addArgument("-p" + password);
}
}
builder.addArgument(StringUtils.join(dbNamesToDump, StringUtils.SPACE));
builder.setDestroyOnShutdown(true);
return builder.build();
}
}
| Only set --max_allowed_packet if it is not in the args list.
| mariaDB4j-core/src/main/java/ch/vorburger/mariadb4j/DB.java | Only set --max_allowed_packet if it is not in the args list. |
|
Java | apache-2.0 | b543381be02f07e47e72eaafa862aa8d5f6af186 | 0 | krosenvold/commons-compress,apache/commons-compress,lookout/commons-compress,mohanaraosv/commons-compress,apache/commons-compress,lookout/commons-compress,mohanaraosv/commons-compress,mohanaraosv/commons-compress,krosenvold/commons-compress,lookout/commons-compress,krosenvold/commons-compress,apache/commons-compress | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.compress.utils;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
/**
* Reads bits from an InputStream.
* @since 1.10
* @NotThreadSafe
*/
public class BitInputStream implements Closeable {
private static final int MAXIMUM_CACHE_SIZE = 31; // bits in int minus sign bit
private static final int[] MASKS = new int[MAXIMUM_CACHE_SIZE + 1];
static {
for (int i = 1; i <= MAXIMUM_CACHE_SIZE; i++) {
MASKS[i] = (MASKS[i - 1] << 1) + 1;
}
}
private final InputStream in;
private final ByteOrder byteOrder;
private int bitsCached = 0;
private int bitsCachedSize = 0;
/**
* Constructor taking an InputStream and its bit arrangement.
* @param in the InputStream
* @param byteOrder the bit arrangement across byte boundaries,
* either BIG_ENDIAN (aaaaabbb bb000000) or LITTLE_ENDIAN (bbbaaaaa 000000bb)
*/
public BitInputStream(final InputStream in, final ByteOrder byteOrder) {
this.in = in;
this.byteOrder = byteOrder;
}
public void close() throws IOException {
in.close();
}
/**
* Clears the cache of bits that have been read from the
* underlying stream but not yet provided via {@link #readBits}.
*/
public void clearBitCache() {
bitsCached = 0;
bitsCachedSize = 0;
}
/**
* Returns at most 31 bits read from the underlying stream.
*
* @param count the number of bits to read, must be a positive
* number not bigger than 31.
* @return the bits concatenated as an integer using the stream's byte order.
* -1 if the end of the underlying stream has been reached before reading
* the requested number of bits
*/
public int readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
throw new IllegalArgumentException("count must not be negative or greater than " + MAXIMUM_CACHE_SIZE);
}
while (bitsCachedSize < count) {
final int nextByte = in.read();
if (nextByte < 0) {
return nextByte;
}
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
bitsCached |= (nextByte << bitsCachedSize);
} else {
bitsCached <<= 8;
bitsCached |= nextByte;
}
bitsCachedSize += 8;
}
final int bitsOut;
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
bitsOut = (bitsCached & MASKS[count]);
bitsCached >>>= count;
} else {
bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
}
bitsCachedSize -= count;
return bitsOut;
}
}
| src/main/java/org/apache/commons/compress/utils/BitInputStream.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.commons.compress.utils;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
/**
* Reads bits from an InputStream.
* @since 1.10
* @NotThreadSafe
*/
public class BitInputStream implements Closeable {
private static final int MAXIMUM_CACHE_SIZE = 31; // bits in int minus sign bit
private static final int[] MASKS = new int[MAXIMUM_CACHE_SIZE + 1];
static {
for (int i = 1; i <= MAXIMUM_CACHE_SIZE; i++) {
MASKS[i] = (MASKS[i - 1] << 1) + 1;
}
}
private final InputStream in;
private final ByteOrder byteOrder;
private int bitsCached = 0;
private int bitsCachedSize = 0;
/**
* Constructor taking an InputStream and its bit arrangement.
* @param in the InputStream
* @param byteOrder the bit arrangement across byte boundaries,
* either BIG_ENDIAN (aaaaabbb bb000000) or LITTLE_ENDIAN (bbbaaaaa 000000bb)
*/
public BitInputStream(final InputStream in, final ByteOrder byteOrder) {
this.in = in;
this.byteOrder = byteOrder;
}
public void close() throws IOException {
in.close();
}
/**
* Clears the cache of bits that have been read from the
* underlying stream but not yet provided via {@link #readBits}.
*/
public void clearBitCache() {
bitsCached = 0;
bitsCachedSize = 0;
}
/**
* Returns at most 31 bits read from the underlying stream.
*
* @param count the number of bits to read, must be a positive
* number not bigger than 31.
* @return the bits concatenated as an integer using the stream's byte order.
* -1 if the end of the underlying stream has been reached before reading
* the requested number of bits
*/
public int readBits(final int count) throws IOException {
if (count < 0 || count > MAXIMUM_CACHE_SIZE) {
throw new IllegalArgumentException("count must not be negative or bigger than " + MAXIMUM_CACHE_SIZE);
}
while (bitsCachedSize < count) {
final int nextByte = in.read();
if (nextByte < 0) {
return nextByte;
}
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
bitsCached |= (nextByte << bitsCachedSize);
} else {
bitsCached <<= 8;
bitsCached |= nextByte;
}
bitsCachedSize += 8;
}
final int bitsOut;
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
bitsOut = (bitsCached & MASKS[count]);
bitsCached >>>= count;
} else {
bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];
}
bitsCachedSize -= count;
return bitsOut;
}
}
| I think a number is greater, not bigger
git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1639573 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/compress/utils/BitInputStream.java | I think a number is greater, not bigger |
|
Java | apache-2.0 | e9342cfdf236aa9562e27fd53ee31ae0ebba2811 | 0 | HubSpot/dropwizard-guice | package com.hubspot.dropwizard.guice;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.google.inject.servlet.ServletModule;
import com.squarespace.jersey2.guice.JerseyGuiceModule;
import com.squarespace.jersey2.guice.JerseyGuiceUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.util.List;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.extension.ServiceLocatorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> {
final Logger logger = LoggerFactory.getLogger(GuiceBundle.class);
private final AutoConfig autoConfig;
private final List<Module> modules;
private final InjectorFactory injectorFactory;
private Injector baseInjector;
private DropwizardEnvironmentModule dropwizardEnvironmentModule;
private Optional<Class<T>> configurationClass;
private Stage stage;
public static class Builder<T extends Configuration> {
private AutoConfig autoConfig;
private List<Module> modules = Lists.newArrayList();
private Optional<Class<T>> configurationClass = Optional.absent();
private InjectorFactory injectorFactory = new InjectorFactoryImpl();
public Builder<T> addModule(Module module) {
Preconditions.checkNotNull(module);
modules.add(module);
return this;
}
public Builder<T> addModules(Module... newModules) {
Preconditions.checkNotNull(modules);
for (Module module : newModules) {
addModule(module);
}
return this;
}
public Builder<T> setConfigClass(Class<T> clazz) {
configurationClass = Optional.of(clazz);
return this;
}
public Builder<T> setInjectorFactory(InjectorFactory factory) {
Preconditions.checkNotNull(factory);
injectorFactory = factory;
return this;
}
public Builder<T> enableAutoConfig(String... basePackages) {
Preconditions.checkArgument(basePackages.length > 0, "at least one package must be specified for AutoConfig");
Preconditions.checkArgument(autoConfig == null, "autoConfig already enabled!");
autoConfig = new AutoConfig(basePackages);
return this;
}
public GuiceBundle<T> build() {
return build(Stage.PRODUCTION);
}
public GuiceBundle<T> build(Stage s) {
return new GuiceBundle<>(s, autoConfig, modules, configurationClass, injectorFactory);
}
}
public static <T extends Configuration> Builder<T> newBuilder() {
return new Builder<>();
}
private GuiceBundle(Stage stage, AutoConfig autoConfig, List<Module> modules, Optional<Class<T>> configurationClass, InjectorFactory injectorFactory) {
Preconditions.checkNotNull(modules);
Preconditions.checkArgument(!modules.isEmpty());
Preconditions.checkNotNull(stage);
this.modules = modules;
this.autoConfig = autoConfig;
this.configurationClass = configurationClass;
this.injectorFactory = injectorFactory;
this.stage = stage;
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
if (configurationClass.isPresent()) {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<>(configurationClass.get());
} else {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<>(Configuration.class);
}
modules.add(dropwizardEnvironmentModule);
modules.add(new ServletModule());
initInjector();
JerseyGuiceUtils.install(new ServiceLocatorGenerator() {
@Override
public ServiceLocator create(String name, ServiceLocator parent) {
if (!name.startsWith("__HK2_Generated_")) {
return null;
}
return baseInjector.createChildInjector(new JerseyGuiceModule(name))
.getInstance(ServiceLocator.class);
}
});
if (autoConfig != null) {
autoConfig.initialize(bootstrap, baseInjector.createChildInjector(new JerseyGuiceModule(JerseyGuiceUtils.newServiceLocator())));
}
}
@SuppressFBWarnings("DM_EXIT")
private void initInjector() {
try {
baseInjector = injectorFactory.create(this.stage,ImmutableList.copyOf(this.modules));
} catch(Exception ie) {
logger.error("Exception occurred when creating Guice Injector - exiting", ie);
System.exit(1);
}
}
@Override
public void run(final T configuration, final Environment environment) {
JerseyUtil.registerGuiceBound(baseInjector, environment.jersey());
JerseyUtil.registerGuiceFilter(environment);
setEnvironment(configuration, environment);
if (autoConfig != null) {
autoConfig.run(environment, baseInjector);
}
}
@SuppressWarnings("unchecked")
private void setEnvironment(final T configuration, final Environment environment) {
dropwizardEnvironmentModule.setEnvironmentData(configuration, environment);
}
public Injector getInjector() {
Preconditions.checkState(baseInjector != null, "injector is only available after com.hubspot.dropwizard.guice.GuiceBundle.initialize() is called");
return baseInjector.createChildInjector(new JerseyGuiceModule(JerseyGuiceUtils.newServiceLocator()));
}
}
| src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java | package com.hubspot.dropwizard.guice;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import com.google.inject.servlet.ServletModule;
import com.squarespace.jersey2.guice.JerseyGuiceModule;
import com.squarespace.jersey2.guice.JerseyGuiceUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.dropwizard.Configuration;
import io.dropwizard.ConfiguredBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.util.List;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.extension.ServiceLocatorGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GuiceBundle<T extends Configuration> implements ConfiguredBundle<T> {
final Logger logger = LoggerFactory.getLogger(GuiceBundle.class);
private final AutoConfig autoConfig;
private final List<Module> modules;
private final InjectorFactory injectorFactory;
private Injector baseInjector;
private DropwizardEnvironmentModule dropwizardEnvironmentModule;
private Optional<Class<T>> configurationClass;
private Stage stage;
public static class Builder<T extends Configuration> {
private AutoConfig autoConfig;
private List<Module> modules = Lists.newArrayList();
private Optional<Class<T>> configurationClass = Optional.absent();
private InjectorFactory injectorFactory = new InjectorFactoryImpl();
public Builder<T> addModule(Module module) {
Preconditions.checkNotNull(module);
modules.add(module);
return this;
}
public Builder<T> setConfigClass(Class<T> clazz) {
configurationClass = Optional.of(clazz);
return this;
}
public Builder<T> setInjectorFactory(InjectorFactory factory) {
Preconditions.checkNotNull(factory);
injectorFactory = factory;
return this;
}
public Builder<T> enableAutoConfig(String... basePackages) {
Preconditions.checkArgument(basePackages.length > 0, "at least one package must be specified for AutoConfig");
Preconditions.checkArgument(autoConfig == null, "autoConfig already enabled!");
autoConfig = new AutoConfig(basePackages);
return this;
}
public GuiceBundle<T> build() {
return build(Stage.PRODUCTION);
}
public GuiceBundle<T> build(Stage s) {
return new GuiceBundle<>(s, autoConfig, modules, configurationClass, injectorFactory);
}
}
public static <T extends Configuration> Builder<T> newBuilder() {
return new Builder<>();
}
private GuiceBundle(Stage stage, AutoConfig autoConfig, List<Module> modules, Optional<Class<T>> configurationClass, InjectorFactory injectorFactory) {
Preconditions.checkNotNull(modules);
Preconditions.checkArgument(!modules.isEmpty());
Preconditions.checkNotNull(stage);
this.modules = modules;
this.autoConfig = autoConfig;
this.configurationClass = configurationClass;
this.injectorFactory = injectorFactory;
this.stage = stage;
}
@Override
public void initialize(Bootstrap<?> bootstrap) {
if (configurationClass.isPresent()) {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<>(configurationClass.get());
} else {
dropwizardEnvironmentModule = new DropwizardEnvironmentModule<>(Configuration.class);
}
modules.add(dropwizardEnvironmentModule);
modules.add(new ServletModule());
initInjector();
JerseyGuiceUtils.install(new ServiceLocatorGenerator() {
@Override
public ServiceLocator create(String name, ServiceLocator parent) {
if (!name.startsWith("__HK2_Generated_")) {
return null;
}
return baseInjector.createChildInjector(new JerseyGuiceModule(name))
.getInstance(ServiceLocator.class);
}
});
if (autoConfig != null) {
autoConfig.initialize(bootstrap, baseInjector.createChildInjector(new JerseyGuiceModule(JerseyGuiceUtils.newServiceLocator())));
}
}
@SuppressFBWarnings("DM_EXIT")
private void initInjector() {
try {
baseInjector = injectorFactory.create(this.stage,ImmutableList.copyOf(this.modules));
} catch(Exception ie) {
logger.error("Exception occurred when creating Guice Injector - exiting", ie);
System.exit(1);
}
}
@Override
public void run(final T configuration, final Environment environment) {
JerseyUtil.registerGuiceBound(baseInjector, environment.jersey());
JerseyUtil.registerGuiceFilter(environment);
setEnvironment(configuration, environment);
if (autoConfig != null) {
autoConfig.run(environment, baseInjector);
}
}
@SuppressWarnings("unchecked")
private void setEnvironment(final T configuration, final Environment environment) {
dropwizardEnvironmentModule.setEnvironmentData(configuration, environment);
}
public Injector getInjector() {
Preconditions.checkState(baseInjector != null, "injector is only available after com.hubspot.dropwizard.guice.GuiceBundle.initialize() is called");
return baseInjector.createChildInjector(new JerseyGuiceModule(JerseyGuiceUtils.newServiceLocator()));
}
}
| addModules(Module... module) API enhancement to add multiple modules in a compact way.
| src/main/java/com/hubspot/dropwizard/guice/GuiceBundle.java | addModules(Module... module) API enhancement to add multiple modules in a compact way. |
|
Java | mit | 4fb4ffc1c844bfc8f43bcf9f7de46c956e8ef949 | 0 | thorstenwagner/TraJ | package de.biomedical_imaging.traJ.simulation;
import java.util.Random;
import javax.vecmath.Point3d;
import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import de.biomedical_imaging.traJ.Trajectory;
/*
* Anomalosu Diffusion according to :
* Anomalous Protein Diffusion in Living Cells as Seen by Fluorescence Correlation Spectroscopy
*
* The spatial increments in x and y direction are choosen via the Weierstrass-Mandelbrot function
*/
public class AnomalousDiffusionWMSimulation extends AbstractSimulator {
private double diffusioncoefficient;
private double timelag;
private int dimension;
private int numberOfSteps;
private double alpha;
public AnomalousDiffusionWMSimulation(double diffusioncoefficient, double timelag, int dimension,int numberOfSteps, double alpha) {
this.diffusioncoefficient = diffusioncoefficient;
this.timelag = timelag;
this.numberOfSteps = numberOfSteps;
this.dimension = dimension;
this.alpha = alpha;
}
@Override
public Trajectory generateTrajectory() {
Trajectory t = new Trajectory(dimension);
t.add(new Point3d(0, 0, 0));
double[] incrx = generateIncrements();
double[] incry = generateIncrements();
/*
* This factor was calculated by regression analysis using R:
* x<-c(100,200,300,400,500,600,700,800)
* y<-c(1.0610,1.030076,1.02126,1.01446,1.012958,1.01055,1.008500,1.007809)
* fit <- lm(log(y)~log(x))
* plot(log(x),log(y))
* abline(fit)
* print(fit)
*/
double fact = 2*Math.sqrt(diffusioncoefficient/(Math.exp(6.7426-0.9704*Math.log(numberOfSteps))))*
Math.sqrt(diffusioncoefficient/Math.exp(-2.327-1.177*Math.log(alpha)));
for(int i = 1; i <= numberOfSteps; i++) {
Point3d pos = new Point3d();
pos.setX(t.get(i-1).x + incrx[i-1]*fact);//)*fact2); Math.sqrt(2*diffusioncoefficient*timelag)
pos.setY(t.get(i-1).y + incry[i-1]*fact);//*fact2);
t.add(pos);
}
return t;
}
public double[] generateIncrements(){
double gamma = Math.sqrt(Math.PI);
double H = alpha/2;
double[] wxs = new double[numberOfSteps];
double[] increments = new double[numberOfSteps];
double[] phasesx = new double[48+8+1];
for(int j = 0; j < phasesx.length; j++){
phasesx[j] = CentralRandomNumberGenerator.getInstance().nextDouble()*2*Math.PI;
}
for(int t = 1; t <= numberOfSteps; t++){
double tStar = 2*Math.PI*t/numberOfSteps;
double wx = 0;
for(int n = -8; n <= 48; n++){
double phasex = phasesx[n+8];
wx += (Math.cos(phasex)-Math.cos(Math.pow(gamma, n) * tStar + phasex))/Math.pow(gamma, n*H);
}
double prevwx = (t-2)>=0?wxs[t-2]:0;
wxs[t-1] = wx;
increments[t-1] = wxs[t-1]-prevwx;
}
return increments;
}
}
| src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java | package de.biomedical_imaging.traJ.simulation;
import java.util.Random;
import javax.vecmath.Point3d;
import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import de.biomedical_imaging.traJ.Trajectory;
/*
* Anomalosu Diffusion according to :
* Anomalous Protein Diffusion in Living Cells as Seen by Fluorescence Correlation Spectroscopy
*
* The spatial increments in x and y direction are choosen via the Weierstrass-Mandelbrot function
*/
public class AnomalousDiffusionWMSimulation extends AbstractSimulator {
private double diffusioncoefficient;
private double timelag;
private int dimension;
private int numberOfSteps;
private double alpha;
public AnomalousDiffusionWMSimulation(double diffusioncoefficient, double timelag, int dimension,int numberOfSteps, double alpha) {
this.diffusioncoefficient = diffusioncoefficient;
this.timelag = timelag;
this.numberOfSteps = numberOfSteps;
this.dimension = dimension;
this.alpha = alpha;
}
@Override
public Trajectory generateTrajectory() {
Trajectory t = new Trajectory(dimension);
t.add(new Point3d(0, 0, 0));
double[] incrx = generateIncrements();
double[] incry = generateIncrements();
/*
* This factor was calculated by regression analysis using R:
* x<-c(100,200,300,400,500,600,700,800)
* y<-c(1.0610,1.030076,1.02126,1.01446,1.012958,1.01055,1.008500,1.007809)
* fit <- lm(log(y)~log(x))
* plot(log(x),log(y))
* abline(fit)
* print(fit)
*/
double fact = Math.sqrt(diffusioncoefficient/(Math.exp(6.7426-0.9704*Math.log(numberOfSteps))));
for(int i = 1; i <= numberOfSteps; i++) {
Point3d pos = new Point3d();
pos.setX(t.get(i-1).x + incrx[i-1]*2*fact);//)*fact2); Math.sqrt(2*diffusioncoefficient*timelag)
pos.setY(t.get(i-1).y + incry[i-1]*2*fact);//*fact2);
t.add(pos);
}
return t;
}
public double[] generateIncrements(){
double gamma = Math.sqrt(Math.PI);
double H = alpha/2;
double[] wxs = new double[numberOfSteps];
double[] increments = new double[numberOfSteps];
double[] phasesx = new double[48+8+1];
for(int j = 0; j < phasesx.length; j++){
phasesx[j] = CentralRandomNumberGenerator.getInstance().nextDouble()*2*Math.PI;
}
for(int t = 1; t <= numberOfSteps; t++){
double tStar = 2*Math.PI*t/numberOfSteps;
double wx = 0;
for(int n = -8; n <= 48; n++){
double phasex = phasesx[n+8];
wx += (Math.cos(phasex)-Math.cos(Math.pow(gamma, n) * tStar + phasex))/Math.pow(gamma, n*H);
}
double prevwx = (t-2)>=0?wxs[t-2]:0;
wxs[t-1] = wx;
increments[t-1] = wxs[t-1]-prevwx;
}
return increments;
}
}
| Changed scaling factor for anomalous diffusion | src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java | Changed scaling factor for anomalous diffusion |
|
Java | mit | 6a23edd9111b745c0abf9d8d385190a493c22db4 | 0 | iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable | package org.broadinstitute.sting.gatk.walkers.indels;
import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;
import java.util.ArrayList;
public class IndelRealignerPerformanceTest extends WalkerTest {
@Test
public void testRealigner() {
WalkerTestSpec spec1 = new WalkerTestSpec(
"-R " + seqLocation + "references/Homo_sapiens_assembly18/v0/Homo_sapiens_assembly18.fasta" +
" -T IndelRealigner" +
" -LOD 5" +
" -maxConsensuses 100" +
" -greedy 100" +
" -D /humgen/gsa-hpprojects/GATK/data/dbsnp_129_hg18.rod" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-5,650,000" +
" --realignReadsWithBadMates" +
" -targetIntervals " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.realigner.intervals",
0,
new ArrayList<String>(0));
executeTest("testIndelRealignerWholeGenome", spec1);
WalkerTestSpec spec2 = new WalkerTestSpec(
"-R " + seqLocation + "references/Homo_sapiens_assembly18/v0/Homo_sapiens_assembly18.fasta" +
" -T IndelRealigner" +
" -LOD 5" +
" -maxConsensuses 100" +
" -greedy 100" +
" -D /humgen/gsa-hpprojects/GATK/data/dbsnp_129_hg18.rod" +
" -I " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.bam" +
" -L chr1:1-150,000,000" +
" --realignReadsWithBadMates" +
" -targetIntervals " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.realigner.intervals",
0,
new ArrayList<String>(0));
executeTest("testIndelRealignerWholeExome", spec2);
}
} | java/test/org/broadinstitute/sting/gatk/walkers/indels/IndelRealignerPerformanceTest.java | package org.broadinstitute.sting.gatk.walkers.indels;
import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;
import java.util.ArrayList;
public class IndelRealignerPerformanceTest extends WalkerTest {
@Test
public void testRealigner() {
WalkerTestSpec spec1 = new WalkerTestSpec(
"-R " + seqLocation + "references/Homo_sapiens_assembly18/v0/Homo_sapiens_assembly18.fasta" +
" -T IndelRealigner" +
" -LOD 5" +
" -maxConsensuses 100" +
" -greedy 100" +
" -D /humgen/gsa-hpprojects/GATK/data/dbsnp_129_hg18.rod" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-5,650,000" +
" -targetIntervals " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.realigner.intervals",
0,
new ArrayList<String>(0));
executeTest("testIndelRealignerWholeGenome", spec1);
WalkerTestSpec spec2 = new WalkerTestSpec(
"-R " + seqLocation + "references/Homo_sapiens_assembly18/v0/Homo_sapiens_assembly18.fasta" +
" -T IndelRealigner" +
" -LOD 5" +
" -maxConsensuses 100" +
" -greedy 100" +
" -D /humgen/gsa-hpprojects/GATK/data/dbsnp_129_hg18.rod" +
" -I " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.bam" +
" -L chr1:1-150,000,000" +
" -targetIntervals " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.realigner.intervals",
0,
new ArrayList<String>(0));
executeTest("testIndelRealignerWholeExome", spec2);
}
} | Fix performance tests
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@3662 348d0f76-0448-11de-a6fe-93d51630548a
| java/test/org/broadinstitute/sting/gatk/walkers/indels/IndelRealignerPerformanceTest.java | Fix performance tests |
|
Java | mit | 9654c3f8cf3103d8463e21c6ee0bc33c0be8ac20 | 0 | OpenAMEE/amee.platform.api | package com.amee.restlet.resource;
import com.amee.restlet.AMEESpringServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
public class ResourceManager {
private final Log log = LogFactory.getLog(getClass());
private GenericResource resource;
public void init(GenericResource resource) {
this.resource = resource;
}
/**
* This is how we tell if the request came via HTTPS as SSL is terminated at the load balancer.
*
* @return true if the current request has come through the secure connector
*/
protected boolean isSecure() {
return getActiveServer().isSecure();
}
protected boolean isOk(JSONObject result) {
return isStatus(result, "OK");
}
protected boolean isNotFound(JSONObject result) {
return isStatus(result, "NOT_FOUND");
}
protected boolean isNotAuthenticated(JSONObject result) {
return isStatus(result, "NOT_AUTHENTICATED");
}
protected boolean isNotAuthorized(JSONObject result) {
return isStatus(result, "NOT_AUTHORIZED");
}
protected boolean isInternalError(JSONObject result) {
return isStatus(result, "INTERNAL_ERROR");
}
protected boolean isInvalid(JSONObject result) {
return isStatus(result, "INVALID");
}
protected boolean isTimedOut(JSONObject result) {
return isStatus(result, "TIMED_OUT");
}
protected boolean isMediaTypeNotSupported(JSONObject result) {
return isStatus(result, "MEDIA_TYPE_NOT_SUPPORTED");
}
protected boolean isStatus(JSONObject result, String status) {
try {
return (result != null) && result.has("status") && result.getString("status").equals(status);
} catch (JSONException e) {
// Swallow.
return false;
}
}
protected Map<String, String> getAttributes() {
Map<String, String> attributes = new HashMap<String, String>();
for (String attributeName : getAttributeNames()) {
if (getRequest().getAttributes().containsKey(attributeName)) {
Object a = getRequest().getAttributes().get(attributeName);
if (a instanceof String) {
// This removes any matrix parameters.
String value = ((String) a).split(";")[0];
try {
value = URLDecoder.decode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.warn("getAttributes() Caught UnsupportedEncodingException: " + e.getMessage());
}
attributes.put(attributeName, value);
} else {
log.warn("getAttributes() Attribute value is not a String: " + attributeName);
}
} else {
log.warn("getAttributes() Attribute value not found: " + attributeName);
}
}
return attributes;
}
protected Map<String, String> getMatrixParameters() {
return getRequest().getResourceRef().getMatrixAsForm().getValuesMap();
}
protected Map<String, String> getQueryParameters() {
return getRequest().getResourceRef().getQueryAsForm().getValuesMap();
}
protected List<String> getAcceptedMediaTypes() {
List<String> acceptedMediaTypes = new ArrayList<String>();
for (Preference<MediaType> p : getRequest().getClientInfo().getAcceptedMediaTypes()) {
acceptedMediaTypes.add(p.getMetadata().toString());
}
return acceptedMediaTypes;
}
public GenericResource getResource() {
return resource;
}
public Request getRequest() {
return resource.getRequest();
}
public Response getResponse() {
return resource.getResponse();
}
public Set<String> getAttributeNames() {
return resource.getAttributeNames();
}
public void setAttributeNames(Set<String> attributeNames) {
resource.setAttributeNames(attributeNames);
}
public AMEESpringServer getActiveServer() {
return (AMEESpringServer) getRequest().getAttributes().get("activeServer");
}
}
| src/main/java/com/amee/restlet/resource/ResourceManager.java | package com.amee.restlet.resource;
import com.amee.restlet.AMEESpringServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import java.util.*;
public class ResourceManager {
private final Log log = LogFactory.getLog(getClass());
private GenericResource resource;
public void init(GenericResource resource) {
this.resource = resource;
}
/**
* This is how we tell if the request came via HTTPS as SSL is terminated at the load balancer.
*
* @return true if the current request has come through the secure connector
*/
protected boolean isSecure() {
return getActiveServer().isSecure();
}
protected boolean isOk(JSONObject result) {
return isStatus(result, "OK");
}
protected boolean isNotFound(JSONObject result) {
return isStatus(result, "NOT_FOUND");
}
protected boolean isNotAuthenticated(JSONObject result) {
return isStatus(result, "NOT_AUTHENTICATED");
}
protected boolean isNotAuthorized(JSONObject result) {
return isStatus(result, "NOT_AUTHORIZED");
}
protected boolean isInternalError(JSONObject result) {
return isStatus(result, "INTERNAL_ERROR");
}
protected boolean isInvalid(JSONObject result) {
return isStatus(result, "INVALID");
}
protected boolean isTimedOut(JSONObject result) {
return isStatus(result, "TIMED_OUT");
}
protected boolean isMediaTypeNotSupported(JSONObject result) {
return isStatus(result, "MEDIA_TYPE_NOT_SUPPORTED");
}
protected boolean isStatus(JSONObject result, String status) {
try {
return (result != null) && result.has("status") && result.getString("status").equals(status);
} catch (JSONException e) {
// Swallow.
return false;
}
}
protected Map<String, String> getAttributes() {
Map<String, String> attributes = new HashMap<String, String>();
for (String attributeName : getAttributeNames()) {
if (getRequest().getAttributes().containsKey(attributeName)) {
Object a = getRequest().getAttributes().get(attributeName);
if (a instanceof String) {
// This removes any matrix parameters.
attributes.put(attributeName, ((String) a).split(";")[0]);
} else {
log.warn("getAttributes() Attribute value is not a String: " + attributeName);
}
} else {
log.warn("getAttributes() Attribute value not found: " + attributeName);
}
}
return attributes;
}
protected Map<String, String> getMatrixParameters() {
return getRequest().getResourceRef().getMatrixAsForm().getValuesMap();
}
protected Map<String, String> getQueryParameters() {
return getRequest().getResourceRef().getQueryAsForm().getValuesMap();
}
protected List<String> getAcceptedMediaTypes() {
List<String> acceptedMediaTypes = new ArrayList<String>();
for (Preference<MediaType> p : getRequest().getClientInfo().getAcceptedMediaTypes()) {
acceptedMediaTypes.add(p.getMetadata().toString());
}
return acceptedMediaTypes;
}
public GenericResource getResource() {
return resource;
}
public Request getRequest() {
return resource.getRequest();
}
public Response getResponse() {
return resource.getResponse();
}
public Set<String> getAttributeNames() {
return resource.getAttributeNames();
}
public void setAttributeNames(Set<String> attributeNames) {
resource.setAttributeNames(attributeNames);
}
public AMEESpringServer getActiveServer() {
return (AMEESpringServer) getRequest().getAttributes().get("activeServer");
}
}
| PL-10693 - URL decode Restlet URL attributes.
| src/main/java/com/amee/restlet/resource/ResourceManager.java | PL-10693 - URL decode Restlet URL attributes. |
|
Java | mit | 75e6b0ebb4e1543976115695f1c6e426f0f266bd | 0 | spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror,spurious/kawa-mirror | // Copyright (c) 2001, 2005 Per M.A. Bothner and Brainfood Inc.
// This is free software; for terms and warranty disclaimer see ./COPYING.
package gnu.lists;
/** A sequence where each element is a character.
*/
public interface CharSeq
extends
/* #ifdef JAVA5 */
// CharSequence,
/* #endif */
Sequence
{
/** Get length of string, in characters.
* Synonym for size(), for compatibility with String and StringBuffer. */
public int length();
public char charAt(int index);
/** Copy characters into a destination buffer.
* Same interface as java.lang.String's getChars. */
public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin);
public void setCharAt(int index, char ch);
/** Set all the elements to a given character. */
public void fill(char value);
public void fill(int fromIndex, int toIndex, char value);
/* #ifdef JAVA5 */
// /** Append a specified subsequence to an <code>Appendable</code>.
// * An allowable implementation is:
// * <code>dest.append(this, start, start+count)</code>.
// * Hence implementors of <code>Appendable</code> should avoid calling
// * <code>writeTo</code> - though they can call <code>getChars</code>.
// */
// public void writeTo(int start, int count, Appendable dest)
// throws java.io.IOException;
// public void writeTo(Appendable dest)
// throws java.io.IOException;
// public CharSeq subSequence(int start, int end);
/* #else */
/**
* Write out (part of) this string.
* @param start index of initial character to write
* @param count number of characters to write
* @param dest where to write the characters
*/
public void writeTo(int start, int count, java.io.Writer dest)
throws java.io.IOException;
public void writeTo(java.io.Writer str) throws java.io.IOException;
/* #endif */
public void consume(int start, int count, Consumer out);
public String toString();
}
| gnu/lists/CharSeq.java | // Copyright (c) 2001, 2005 Per M.A. Bothner and Brainfood Inc.
// This is free software; for terms and warranty disclaimer see ./COPYING.
package gnu.lists;
/** A sequence where each element is a character.
* Note: It appears that JDK 1.4 will have a new interface
* java.lang.CharSequence, with charAt length, subSequence, and toString.
*/
public interface CharSeq
extends
/* #ifdef JAVA5 */
// CharSequence,
/* #endif */
Sequence
{
/** Get length of string, in characters.
* Synonym for size(), for compatibility with String and StringBuffer. */
public int length();
public char charAt(int index);
/** Copy characters into a destination buffer.
* Same interface as java.lang.String's getChars. */
public void getChars (int srcBegin, int srcEnd, char[] dst, int dstBegin);
public void setCharAt(int index, char ch);
/** Set all the elements to a given character. */
public void fill(char value);
public void fill(int fromIndex, int toIndex, char value);
/* #ifdef JAVA5 */
// /** Append a specified subsequence to an <code>Appendable</code>.
// * An allowable implementation is:
// * <code>dest.append(this, start, start+count)</code>.
// * Hence implementors of <code>Appendable</code> should avoid calling
// * <code>writeTo</code> - though they can call <code>getChars</code>.
// */
// public void writeTo(int start, int count, Appendable dest)
// throws java.io.IOException;
// public void writeTo(Appendable dest)
// throws java.io.IOException;
// public CharSeq subSequence(int start, int end);
/* #else */
/**
* Write out (part of) this string.
* @param start index of initial character to write
* @param count number of characters to write
* @param dest where to write the characters
*/
public void writeTo(int start, int count, java.io.Writer dest)
throws java.io.IOException;
public void writeTo(java.io.Writer str) throws java.io.IOException;
/* #endif */
public void consume(int start, int count, Consumer out);
public String toString();
}
| Remove obsolete comment.
git-svn-id: 169764d5f12c41a1cff66b81d896619f3ce5473d@4548 5e0a886f-7f45-49c5-bc19-40643649e37f
| gnu/lists/CharSeq.java | Remove obsolete comment. |
|
Java | mit | 49237588c988b2c6ee3a06522215efd71b48649d | 0 | simple-elf/selenide,simple-elf/selenide,simple-elf/selenide,simple-elf/selenide,codeborne/selenide,codeborne/selenide,codeborne/selenide | package com.codeborne.selenide;
import java.util.logging.Logger;
import static com.codeborne.selenide.Configuration.AssertionMode.STRICT;
import static com.codeborne.selenide.Configuration.SelectorMode.CSS;
import static com.codeborne.selenide.WebDriverRunner.FIREFOX;
public class Configuration {
private static final Logger LOG = Logger.getLogger(Configuration.class.getName());
public static String baseUrl = System.getProperty("selenide.baseUrl", "http://localhost:8080");
public static long timeout = Long.parseLong(System.getProperty("selenide.timeout", "4000"));
public static long pollingInterval = Long.parseLong(System.getProperty("selenide.pollingInterval", "100"));
/**
* If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging.
* Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true".
* <p/>
* Default value: false.
*/
public static boolean holdBrowserOpen = Boolean.getBoolean("selenide.holdBrowserOpen");
/**
* Which browser to use.
* Can be configured either programmatically or by system property "-Dselenide.browser=ie" or "-Dbrowser=ie".
* Supported values: "chrome", "firefox", "ie", "htmlunit", "phantomjs", "opera"
* <p/>
* Default value: "firefox"
*/
public static String browser = System.getProperty("selenide.browser", System.getProperty("browser", FIREFOX));
/**
* URL of remote web driver (in case of using Selenium Grid).
* Can be configured either programmatically or by system property "-Dremote=http://localhost:5678/hub".
*
* Default value: null (Grid is not used).
*/
public static String remote = System.getProperty("remote");
/**
* The browser window is maximized when started.
* Can be configured either programmatically or by system property "-Dselenide.start-maximized=true".
*
* Default value: true
*/
public static boolean startMaximized = Boolean.parseBoolean(System.getProperty("selenide.start-maximized", "true"));
/**
* ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature.
* Use clicking via JavaScript instead common element clicking.
* This solution may be helpful for testing in Internet Explorer.
*
* Default value: false
*/
public static boolean clickViaJs = Boolean.parseBoolean(System.getProperty("selenide.click-via-js", "false"));
/**
* Does Selenide need to take screenshots on failing tests.
*
* Default value: true
*/
public static boolean screenshots = Boolean.parseBoolean(System.getProperty("selenide.screenshots", "true"));
/**
* Folder to store screenshots to.
* Can be configured either programmatically or by system property "-Dselenide.reports=test-result/reports".
*
* Default value: "build/reports/tests" (this is default for Gradle projects)
*/
public static String reportsFolder = System.getProperty("selenide.reports", "build/reports/tests");
/**
* Optional: URL of CI server where reports are published to.
* In case of Jenkins, it is "BUILD_URL/artifact" by default.
*
* If it's given, names of screenshots are printed as
* "http://ci.mycompany.com/job/my-job/446/artifact/build/reports/tests/my_test.png" - it's useful to analyze test
* failures in CI server.
*/
public static String reportsUrl = getReportsUrl();
static String getReportsUrl() {
String reportsUrl = System.getProperty("selenide.reportsUrl");
if (isEmpty(reportsUrl)) {
reportsUrl = getJenkinsReportsUrl();
if (isEmpty(reportsUrl)) {
LOG.config("Variable selenide.reportsUrl not found");
}
} else {
LOG.config("Using variable selenide.reportsUrl=" + reportsUrl);
}
return reportsUrl;
}
private static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
private static String getJenkinsReportsUrl() {
String build_url = System.getProperty("BUILD_URL");
if (!isEmpty(build_url)) {
LOG.config("Using Jenkins BUILD_URL: " + build_url);
return build_url + "artifact/";
}
else {
LOG.config("No BUILD_URL variable found. It's not Jenkins.");
return null;
}
}
/**
* Mock "alert" and "confirm" javascript dialogs.
* Can be configured either programmatically or by system property "-Dselenide.dismissModalDialogs=true".
*
* Default value: false (true for headless browsers like HtmlUnit and PhantomJS because they do not support alert/confirm anyway)
*/
public static boolean dismissModalDialogs = Boolean.parseBoolean(System.getProperty("selenide.dismissModalDialogs", "false"));
/**
* If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function
* (that is quite slow because it sends every character separately).
*
* Tested on Codeborne projects - works well, speed up ~30%.
* Some people reported 150% speedup (because sending characters one-by-one was especially slow via network to Selenium Grid on cloud).
*
* https://github.com/codeborne/selenide/issues/135
*
* Default value: false
*/
public static boolean fastSetValue = Boolean.parseBoolean(System.getProperty("selenide.fastSetValue", "false"));
/**
* EXPERIMENTAL
*
* Choose how Selenide should retrieve web elements: using default CSS or Sizzle (CSS3)
*/
public static SelectorMode selectorMode = CSS;
public static enum SelectorMode {
/**
* Default Selenium behavior
*/
CSS,
/**
* Use Sizzle for CSS selectors.
* It allows powerful CSS3 selectors - ":input", ":not", ":nth", ":first", ":last", ":contains('text')"
*
* For other selectors (XPath, ID etc.) uses default Selenium mechanism.
*/
Sizzle
}
public static enum AssertionMode {STRICT, SOFT;};
public static AssertionMode assertionMode = STRICT;
}
| src/main/java/com/codeborne/selenide/Configuration.java | package com.codeborne.selenide;
import java.util.logging.Logger;
import static com.codeborne.selenide.Configuration.AssertionMode.STRICT;
import static com.codeborne.selenide.Configuration.SelectorMode.CSS;
import static com.codeborne.selenide.WebDriverRunner.FIREFOX;
public class Configuration {
private static final Logger LOG = Logger.getLogger(Configuration.class.getName());
public static String baseUrl = System.getProperty("selenide.baseUrl", "http://localhost:8080");
public static long timeout = Long.parseLong(System.getProperty("selenide.timeout", "4000"));
public static long pollingInterval = Long.parseLong(System.getProperty("selenide.pollingInterval", "100"));
/**
* If holdBrowserOpen is true, browser window stays open after running tests. It may be useful for debugging.
* Can be configured either programmatically or by system property "-Dselenide.holdBrowserOpen=true".
* <p/>
* Default value: false.
*/
public static boolean holdBrowserOpen = Boolean.getBoolean("selenide.holdBrowserOpen");
/**
* Which browser to use.
* Can be configured either programmatically or by system property "-Dselenide.browser=ie" or "-Dbrowser=ie".
* Supported values: "chrome", "firefox", "ie", "htmlunit", "phantomjs", "opera"
* <p/>
* Default value: "firefox"
*/
public static String browser = System.getProperty("selenide.browser", System.getProperty("browser", FIREFOX));
/**
* URL of remote web driver (in case of using Selenium Grid).
* Can be configured either programmatically or by system property "-Dremote=http://localhost:5678/hub".
*
* Default value: null (Grid is not used).
*/
public static String remote = System.getProperty("remote");
/**
* The browser window is maximized when started.
* Can be configured either programmatically or by system property "-Dselenide.start-maximized=true".
*
* Default value: true
*/
public static boolean startMaximized = Boolean.parseBoolean(System.getProperty("selenide.start-maximized", "true"));
/**
* ATTENTION! Automatic WebDriver waiting after click isn't working in case of using this feature.
* Use clicking via JavaScript instead common element clicking.
* This solution may be helpful for testing in Internet Explorer.
*
* Default value: false
*/
public static boolean clickViaJs = Boolean.parseBoolean(System.getProperty("selenide.click-via-js", "false"));
/**
* Does Selenide need to take screenshots on failing tests.
*
* Default value: true
*/
public static boolean screenshots = Boolean.parseBoolean(System.getProperty("selenide.screenshots", "true"));
/**
* Folder to store screenshots to.
* Can be configured either programmatically or by system property "-Dselenide.reports=test-result/reports".
*
* Default value: "build/reports/tests" (this is default for Gradle projects)
*/
public static String reportsFolder = System.getProperty("selenide.reports", "build/reports/tests");
/**
* Optional: URL of CI server where reports are published to.
* In case of Jenkins, it is "BUILD_URL/artifact" by default.
*
* If it's given, names of screenshots are printed as
* "http://ci.mycompany.com/job/my-job/446/artifact/build/reports/tests/my_test.png" - it's useful to analyze test
* failures in CI server.
*/
public static String reportsUrl = getReportsUrl();
static String getReportsUrl() {
String reportsUrl = System.getProperty("selenide.reportsUrl");
if (isEmpty(reportsUrl)) {
reportsUrl = getJenkinsReportsUrl();
if (isEmpty(reportsUrl)) {
LOG.config("Variable selenide.reportsUrl not found");
}
} else {
LOG.config("Using variable selenide.reportsUrl=" + reportsUrl);
}
return reportsUrl;
}
private static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
private static String getJenkinsReportsUrl() {
String build_url = System.getProperty("BUILD_URL");
if (!isEmpty(build_url)) {
LOG.config("Using Jenkins BUILD_URL: " + build_url);
return build_url + "artifact/";
}
else {
LOG.config("No BUILD_URL variable found. It's not Jenkins.");
return null;
}
}
/**
* Mock "alert" and "confirm" javascript dialogs.
* Can be configured either programmatically or by system property "-Dselenide.dismissModalDialogs=true".
*
* Default value: false (true for headless browsers like HtmlUnit and PhantomJS because they do not support alert/confirm anyway)
*/
public static boolean dismissModalDialogs = Boolean.parseBoolean(System.getProperty("selenide.dismissModalDialogs", "false"));
/**
* EXPERIMENTAL
*
* If set to true, sets value by javascript instead of using Selenium built-in "sendKey" function
* (that is quite low because it sends every character separately).
*
* Still not tested well. Waiting for your feedback.
* https://github.com/codeborne/selenide/issues/135
*
* Default value: false
*/
public static boolean fastSetValue = Boolean.parseBoolean(System.getProperty("selenide.fastSetValue", "false"));
/**
* EXPERIMENTAL
*
* Choose how Selenide should retrieve web elements: using default CSS or Sizzle (CSS3)
*/
public static SelectorMode selectorMode = CSS;
public static enum SelectorMode {
/**
* Default Selenium behavior
*/
CSS,
/**
* Use Sizzle for CSS selectors.
* It allows powerful CSS3 selectors - ":input", ":not", ":nth", ":first", ":last", ":contains('text')"
*
* For other selectors (XPath, ID etc.) uses default Selenium mechanism.
*/
Sizzle
}
public static enum AssertionMode {STRICT, SOFT;};
public static AssertionMode assertionMode = STRICT;
}
| "fast setValue" is not experimental anymore
| src/main/java/com/codeborne/selenide/Configuration.java | "fast setValue" is not experimental anymore |
|
Java | mit | 6a18d63fdb3c8d082728f5b52fef70b03a4f68a3 | 0 | Team236/2016-Robot | package org.usfirst.frc.team236.robot;
import org.usfirst.frc.team236.robot.commands.Cock;
import org.usfirst.frc.team236.robot.commands.DriveWithJoysticks;
import org.usfirst.frc.team236.robot.commands.Eject;
import org.usfirst.frc.team236.robot.commands.Intake;
import org.usfirst.frc.team236.robot.commands.IntakeOverride;
import org.usfirst.frc.team236.robot.commands.InvertedDriveWithJoysticks;
import org.usfirst.frc.team236.robot.commands.ShiftDown;
import org.usfirst.frc.team236.robot.commands.ShiftUp;
import org.usfirst.frc.team236.robot.commands.Shoot;
import org.usfirst.frc.team236.robot.commands.arm.ArmWithJoystick;
import org.usfirst.frc.team236.robot.commands.arm.ArmWithPOV;
import org.usfirst.frc.team236.robot.commands.arm.ManualArmDown;
import org.usfirst.frc.team236.robot.commands.arm.ManualArmUp;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
import edu.wpi.first.wpilibj.buttons.JoystickButton;
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a
//// joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
public Joystick leftStick;
public Joystick rightStick;
public Joystick controller;
public Button shiftUp;
public Button shiftDown;
public Button intake;
public Button eject;
public Button intakeoverride;
public Button shoot;
public Button cock;
public Button manualArmUp;
public Button manualArmDown;
public Button armWithJoystick;
public Button invertDrive;
public Button normalDrive;
public Button armWithPOV;
public Button armPIDTest;
public OI() {
leftStick = new Joystick(RobotMap.ControlMap.PORT_STICK_LEFT);
rightStick = new Joystick(RobotMap.ControlMap.PORT_STICK_RIGHT);
controller = new Joystick(RobotMap.ControlMap.PORT_CONTROLLER);
// Right Stick
shiftDown = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_SHIFT_DOWN);
shiftDown.whenPressed(new ShiftDown());
shiftUp = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_SHIFT_UP);
shiftUp.whenPressed(new ShiftUp());
invertDrive = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_INVERT_DRIVE);
invertDrive.whenPressed(new InvertedDriveWithJoysticks());
invertDrive.cancelWhenPressed(new DriveWithJoysticks());
normalDrive = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_NORMAL_DRIVE);
normalDrive.whenPressed(new DriveWithJoysticks());
normalDrive.cancelWhenPressed(new InvertedDriveWithJoysticks());
// Left Stick
shoot = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_SHOOT);
shoot.whenPressed(new Shoot());
eject = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_EJECT);
eject.whileHeld(new Eject());
intake = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_INTAKE);
intake.whileHeld(new Intake());
intakeoverride = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_INTAKE_OVERRIDE);
intakeoverride.whileHeld(new IntakeOverride());
cock = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_COCK);
cock.whenPressed(new Cock());
// Controller
manualArmUp = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_UP);
manualArmUp.whileHeld(new ManualArmUp());
manualArmDown = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_DOWN);
manualArmDown.whileHeld(new ManualArmDown());
armWithJoystick = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_JOYSTICK);
armWithJoystick.whileHeld(new ArmWithJoystick());
armWithPOV = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_WITH_POV);
armWithPOV.whileHeld(new ArmWithPOV());
}
}
| src/org/usfirst/frc/team236/robot/OI.java | package org.usfirst.frc.team236.robot;
import org.usfirst.frc.team236.robot.commands.Cock;
import org.usfirst.frc.team236.robot.commands.DriveWithJoysticks;
import org.usfirst.frc.team236.robot.commands.Eject;
import org.usfirst.frc.team236.robot.commands.Intake;
import org.usfirst.frc.team236.robot.commands.IntakeOverride;
import org.usfirst.frc.team236.robot.commands.InvertedDriveWithJoysticks;
import org.usfirst.frc.team236.robot.commands.ShiftDown;
import org.usfirst.frc.team236.robot.commands.ShiftUp;
import org.usfirst.frc.team236.robot.commands.Shoot;
import org.usfirst.frc.team236.robot.commands.arm.ArmWithJoystick;
import org.usfirst.frc.team236.robot.commands.arm.ArmWithPOV;
import org.usfirst.frc.team236.robot.commands.arm.ManualArmDown;
import org.usfirst.frc.team236.robot.commands.arm.ManualArmUp;
import org.usfirst.frc.team236.robot.commands.arm.SetAnglePID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
import edu.wpi.first.wpilibj.buttons.JoystickButton;
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a
//// joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
public Joystick leftStick;
public Joystick rightStick;
public Joystick controller;
public Button shiftUp;
public Button shiftDown;
public Button intake;
public Button eject;
public Button intakeoverride;
public Button shoot;
public Button cock;
public Button manualArmUp;
public Button manualArmDown;
public Button armWithJoystick;
public Button invertDrive;
public Button normalDrive;
public Button armWithPOV;
public Button armPIDTest;
public OI() {
leftStick = new Joystick(RobotMap.ControlMap.PORT_STICK_LEFT);
rightStick = new Joystick(RobotMap.ControlMap.PORT_STICK_RIGHT);
controller = new Joystick(RobotMap.ControlMap.PORT_CONTROLLER);
// Right Stick
shiftDown = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_SHIFT_DOWN);
shiftDown.whenPressed(new ShiftDown());
shiftUp = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_SHIFT_UP);
shiftUp.whenPressed(new ShiftUp());
invertDrive = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_INVERT_DRIVE);
invertDrive.whenPressed(new InvertedDriveWithJoysticks());
invertDrive.cancelWhenPressed(new DriveWithJoysticks());
normalDrive = new JoystickButton(rightStick, RobotMap.ControlMap.BUTTON_NORMAL_DRIVE);
normalDrive.whenPressed(new DriveWithJoysticks());
normalDrive.cancelWhenPressed(new InvertedDriveWithJoysticks());
// Left Stick
shoot = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_SHOOT);
shoot.whenPressed(new Shoot());
eject = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_EJECT);
eject.whileHeld(new Eject());
intake = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_INTAKE);
intake.whileHeld(new Intake());
intakeoverride = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_INTAKE_OVERRIDE);
intakeoverride.whileHeld(new IntakeOverride());
cock = new JoystickButton(leftStick, RobotMap.ControlMap.BUTTON_COCK);
cock.whenPressed(new Cock());
// Controller
manualArmUp = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_UP);
manualArmUp.whileHeld(new ManualArmUp());
manualArmDown = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_DOWN);
manualArmDown.whileHeld(new ManualArmDown());
armWithJoystick = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_JOYSTICK);
armWithJoystick.whileHeld(new ArmWithJoystick());
armWithPOV = new JoystickButton(controller, RobotMap.ControlMap.BUTTON_ARM_WITH_POV);
armWithPOV.whileHeld(new ArmWithPOV());
armPIDTest = new JoystickButton(controller, 1);
armPIDTest.whileHeld(new SetAnglePID());
}
}
| Removed PID tuning button
| src/org/usfirst/frc/team236/robot/OI.java | Removed PID tuning button |
|
Java | mit | 4795dc94c3beb08e34360d95e447e9ff5f55af99 | 0 | Jason0803/Cocoa-Note,Jason0803/Cocoa-Note,Jason0803/Cocoa-Note | package database;
public interface StringQuery {
/*
* Diary No 시퀀스 생성.
* 컬럼명 : seq_diary_no
* 다이어리 번호 부여방법 : INSERT 구문 사용시 no 컬럼에 seq_diary_no.NEXTVAL 기입
* - K
*/
// ----------------------------------- MemberDAO -------------------------------------- //
String REGISTER_MEMBER =
"INSERT INTO member VALUES(?,?,?,?,?)";
String ISEXIST_MEMBER =
"SELECT id FROM member WHERE id = ?";
String CHECK_VALIDATION =
"SELECT password FROM member WHERE id = ?";
String UPDATE_MEMBER =
"UPDATE member SET password=?, name=?, acc_plan=?, theme=? where id=?";
String FIND_MEMBER_BY_ID =
"SELECT * FROM member where id=?";
// ------------------------------------------------------- DiaryDAO ------------------------------------------------------- //
String GET_ALL_MEMO =
"SELECT * FROM memo WHERE id = ? ORDER BY wrt_date DESC";
String GET_ALL_SCHEDULE =
"SELECT * FROM schedule WHERE id = ? ORDER BY start_date DESC";
String GET_ALL_SHARED_SCHEDULE =
"SELECT * FROM schedule WHERE schedule_no IN (SELECT schedule_no FROM schedule_group WHERE group_member_id = '[email protected]')";
String GET_ALL_NOTE =
"SELECT * FROM note WHERE id = ? ORDER BY curr_date DESC";
String SEARCH_NOTE_BY_KEYWORD =
"SELECT * FROM note WHERE id = ? AND (LOWER(title) LIKE LOWER('%'||?||'%') OR LOWER(content) LIKE (LOWER'%'||?||'%'))";
String SEARCH_MEMO_BY_KEYWORD =
"SELECT * FROM memo WHERE id=? AND LOWER(content) LIKE LOWER('%'||?||'%')";
String SEARCH_SCHEDULE_BY_KEYWORD =
"SELECT * FROM SCHEDULE WHERE id=? AND (LOWER(TITLE) like LOWER('%'||?||'%') OR LOWER(CONTENT) like LOWER('%'||?||'%'))";
String GET_CURR_DIARYNO =
"SELECT last_number FROM user_sequences WHERE sequence_name='SEQ_DIARY_NO'";
String WRITE_MEMO =
"INSERT INTO memo (memo_no, id, content, wrt_date) VALUES(seq_diary_no.nextVal, ?, ?, to_date(?, 'YYYYMMDDHH24MI'))";
String WRITE_NOTE =
"INSERT INTO note (note_no, id, title, content, wrt_date, curr_date) "
+ "VALUES(seq_diary_no.nextVal, ?, ?, ?, to_date(?, 'YYYYMMDDHH24MI'), to_date(?, 'YYYYMMDDHH24MI'))";
String WRITE_SCHEDULE =
"INSERT INTO schedule (schedule_no, id, start_date, end_date, title, content) "
+ "VALUES(seq_diary_no.nextVal, ?, to_date(?, 'YYYYMMDDHH24MI'), to_date(?, 'YYYYMMDDHH24MI'), ?, ?)";
String WRITE_SCHEDULE_GROUP = "INSERT INTO schedule_group (schedule_no, group_member_id) VALUES(?, ?)";
String GET_DAILY_NOTE_BY_ID =
"SELECT * FROM note WHERE id=? AND to_char(wrt_date, 'YYYYMMDD')=?";
String GET_DAILY_SCHEDULE_BY_ID =
"SELECT * FROM schedule WHERE id=? AND to_char(start_date, 'YYYYMMDD')=?";
String GET_NOTE_BY_NO =
"SELECT * FROM note WHERE note_no=?";
String GET_SCHEDULE_BY_NO =
"SELECT * FROM Schedule WHERE Schedule_no=?";
String UPDATE_NOTE =
"UPDATE note SET title = ?, content = ?, curr_date = sysdate WHERE note_no = ?";
String UPDATE_SCHEDULE =
"UPDATE schedule SET title = ?, content = ?, start_date = to_date(?, 'YYYYMMDDHH24MI'), end_date = to_date(?,'YYYYMMDDHH24MI') WHERE schedule_no = ?";
String GET_SHARING_USERS =
"SELECT group_member_id FROM schedule_group WHERE schedule_no = ?";
String SET_SHARING_USERS =
"INSERT INTO schedule_group (schedule_no, group_member_id) VALUES(?,?)";
String DELETE_SCHEDULE_BY_NO =
"DELETE schedule WHERE schedule_no=?";
String DELETE_MEMO_BY_NO =
"DELETE memo WHERE MEMO_NO=?";
String DELETE_NOTE_BY_NO =
"DELETE note WHERE note_no=?";
String GET_CURR_NOTE_NO =
"SELECT note_no FROM note WHERE curr_date = (SELECT MAX(curr_date) FROM note WHERE id=?)";
String DELETE_SCHEDULE_GROUP =
"delete schedule_group where schedule_no=?";
} | src/database/StringQuery.java | package database;
public interface StringQuery {
/*
* Diary No 시퀀스 생성.
* 컬럼명 : seq_diary_no
* 다이어리 번호 부여방법 : INSERT 구문 사용시 no 컬럼에 seq_diary_no.NEXTVAL 기입
* - K
*/
// ----------------------------------- MemberDAO -------------------------------------- //
String REGISTER_MEMBER =
"INSERT INTO member VALUES(?,?,?,?,?)";
String ISEXIST_MEMBER =
"SELECT id FROM member WHERE id = ?";
String CHECK_VALIDATION =
"SELECT password FROM member WHERE id = ?";
String UPDATE_MEMBER =
"UPDATE member SET password=?, name=?, acc_plan=?, theme=? where id=?";
String FIND_MEMBER_BY_ID =
"SELECT * FROM member where id=?";
// ------------------------------------------------------- DiaryDAO ------------------------------------------------------- //
String GET_ALL_MEMO =
"SELECT * FROM memo WHERE id = ? ORDER BY wrt_date DESC";
String GET_ALL_SCHEDULE =
"SELECT * FROM schedule WHERE id = ? ORDER BY start_date DESC";
String GET_ALL_SHARED_SCHEDULE =
"SELECT * FROM schedule WHERE schedule_no IN (SELECT schedule_no FROM schedule_group WHERE group_member_id = '[email protected]')";
String GET_ALL_NOTE =
"SELECT * FROM note WHERE id = ? ORDER BY curr_date DESC";
String SEARCH_NOTE_BY_KEYWORD =
"SELECT * FROM note WHERE id = ? AND (title LIKE '%'||?||'%' OR content LIKE '%'||?||'%')";
String SEARCH_MEMO_BY_KEYWORD =
"SELECT * FROM memo WHERE id=? AND content LIKE '%'||?||'%'";
String SEARCH_SCHEDULE_BY_KEYWORD =
"SELECT * FROM SCHEDULE WHERE id=? AND (TITLE like '%'||?||'%' OR CONTENT like '%'||?||'%')";
String GET_CURR_DIARYNO =
"SELECT last_number FROM user_sequences WHERE sequence_name='SEQ_DIARY_NO'";
String WRITE_MEMO =
"INSERT INTO memo (memo_no, id, content, wrt_date) VALUES(seq_diary_no.nextVal, ?, ?, to_date(?, 'YYYYMMDDHH24MI'))";
String WRITE_NOTE =
"INSERT INTO note (note_no, id, title, content, wrt_date, curr_date) "
+ "VALUES(seq_diary_no.nextVal, ?, ?, ?, to_date(?, 'YYYYMMDDHH24MI'), to_date(?, 'YYYYMMDDHH24MI'))";
String WRITE_SCHEDULE =
"INSERT INTO schedule (schedule_no, id, start_date, end_date, title, content) "
+ "VALUES(seq_diary_no.nextVal, ?, to_date(?, 'YYYYMMDDHH24MI'), to_date(?, 'YYYYMMDDHH24MI'), ?, ?)";
String WRITE_SCHEDULE_GROUP = "INSERT INTO schedule_group (schedule_no, group_member_id) VALUES(?, ?)";
String GET_DAILY_NOTE_BY_ID =
"SELECT * FROM note WHERE id=? AND to_char(wrt_date, 'YYYYMMDD')=?";
String GET_DAILY_SCHEDULE_BY_ID =
"SELECT * FROM schedule WHERE id=? AND to_char(start_date, 'YYYYMMDD')=?";
String GET_NOTE_BY_NO =
"SELECT * FROM note WHERE note_no=?";
String GET_SCHEDULE_BY_NO =
"SELECT * FROM Schedule WHERE Schedule_no=?";
String UPDATE_NOTE =
"UPDATE note SET title = ?, content = ?, curr_date = sysdate WHERE note_no = ?";
String UPDATE_SCHEDULE =
"UPDATE schedule SET title = ?, content = ?, start_date = to_date(?, 'YYYYMMDDHH24MI'), end_date = to_date(?,'YYYYMMDDHH24MI') WHERE schedule_no = ?";
String GET_SHARING_USERS =
"SELECT group_member_id FROM schedule_group WHERE schedule_no = ?";
String SET_SHARING_USERS =
"INSERT INTO schedule_group (schedule_no, group_member_id) VALUES(?,?)";
String DELETE_SCHEDULE_BY_NO =
"DELETE schedule WHERE schedule_no=?";
String DELETE_MEMO_BY_NO =
"DELETE memo WHERE MEMO_NO=?";
String DELETE_NOTE_BY_NO =
"DELETE note WHERE note_no=?";
String GET_CURR_NOTE_NO =
"SELECT note_no FROM note WHERE curr_date = (SELECT MAX(curr_date) FROM note WHERE id=?)";
String DELETE_SCHEDULE_GROUP =
"delete schedule_group where schedule_no=?";
} | #46 : Query : Case Insensitive Search
요요요
하이요
| src/database/StringQuery.java | #46 : Query : Case Insensitive Search |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.