answer
stringlengths
17
10.2M
package com.archimatetool.editor.views.tree.search; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreePath; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.swt.widgets.Display; import com.archimatetool.editor.utils.StringUtils; import com.archimatetool.model.IDocumentable; import com.archimatetool.model.IFolder; import com.archimatetool.model.IFolderContainer; import com.archimatetool.model.INameable; import com.archimatetool.model.IProperties; import com.archimatetool.model.IProperty; /** * Search Filter * * @author Phillip Beauvoir */ public class SearchFilter extends ViewerFilter { private TreeViewer fViewer; private String fSearchText = ""; //$NON-NLS-1$ private TreePath[] fExpanded; private boolean fFilterName; private boolean fFilterDocumentation; private List<EClass> fObjectFilter = new ArrayList<EClass>(); private List<String> fPropertiesFilter = new ArrayList<String>(); private boolean fShowAllFolders = false; public SearchFilter(TreeViewer viewer) { fViewer = viewer; } void setSearchText(String text) { // Fresh text, so store expanded state if(!isFiltering() && text.length() > 0) { saveState(); } fSearchText = text; refresh(); } private void refresh() { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { fViewer.getTree().setRedraw(false); try { // If we do this first fViewer.refresh() is then faster if(!isFiltering()) { restoreState(); } // This has to be called before expandAll fViewer.refresh(); // If we have something to show expand all nodes if(isFiltering()) { fViewer.expandAll(); } else { restoreState(); // Yes, do call this again. } } finally { fViewer.getTree().setRedraw(true); } } }); } public void clear() { if(isFiltering()) { restoreState(); } fSearchText = ""; //$NON-NLS-1$ resetFilters(); fExpanded = null; } public void resetFilters() { reset(); refresh(); } private void reset() { fFilterName = false; fFilterDocumentation = false; fObjectFilter.clear(); fPropertiesFilter.clear(); } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if(!isFiltering()) { return true; } return isElementVisible(parentElement, element); } /** * Query whether element is to be shown (or any children) when filtering * This will also query child elements of element if it's a container * @param element Any element including containers * @return */ private boolean isElementVisible(Object parentElement, Object element) { if(element instanceof IFolderContainer) { for(IFolder folder : ((IFolderContainer)element).getFolders()) { if(isElementVisible(parentElement, folder)) { return true; } } } if(element instanceof IFolder) { for(Object o : ((IFolder)element).getElements()) { if(isElementVisible(parentElement, o)) { return true; } } if(isShowAllFolders()) { return true; } } return matchesFilter(element); } /** * Query whether element matches filter criteria when filtering on node/leaf elements * @param element Any element, children will not be queried. * @return */ public boolean matchesFilter(Object element) { // EObject Type filter - do this first as the master filter if(isObjectFiltered(element)) { return false; } boolean textSearchResult = false; boolean propertyKeyResult = false; // Properties Key filter if(isFilteringPropertyKeys() && element instanceof IProperties) { for(IProperty property : ((IProperties)element).getProperties()) { if(fPropertiesFilter.contains(property.getKey())) { propertyKeyResult = true; if(hasSearchText() && property.getValue().toLowerCase().contains(fSearchText.toLowerCase())) { textSearchResult = true; } } } } // If has search Text and no text found yet if(hasSearchText()) { // Name... if(fFilterName && !textSearchResult && element instanceof INameable) { String name = StringUtils.safeString(((INameable)element).getName()); // Normalise in case of multi-line text name = StringUtils.normaliseNewLineCharacters(name); if(name.toLowerCase().contains(fSearchText.toLowerCase())) { textSearchResult = true; } } // Then Documentation if(fFilterDocumentation && !textSearchResult && element instanceof IDocumentable) { String text = StringUtils.safeString(((IDocumentable)element).getDocumentation()); if(text.toLowerCase().contains(fSearchText.toLowerCase())) { textSearchResult = true; } } } if((hasSearchText())) { return textSearchResult; } if(isFilteringPropertyKeys()) { return propertyKeyResult; } return !isObjectFiltered(element); } private boolean isObjectFiltered(Object element) { return !fObjectFilter.isEmpty() && !fObjectFilter.contains(((EObject)element).eClass()); } public boolean isFiltering() { return hasSearchText() || !fObjectFilter.isEmpty() || !fPropertiesFilter.isEmpty(); } private boolean hasSearchText() { return fSearchText.length() > 0; } private boolean isFilteringPropertyKeys() { return !fPropertiesFilter.isEmpty(); } void setFilterOnName(boolean set) { if(fFilterName != set) { fFilterName = set; if(isFiltering()) { refresh(); } } } void setFilterOnDocumentation(boolean set) { if(fFilterDocumentation != set) { fFilterDocumentation = set; if(isFiltering()) { refresh(); } } } void addObjectFilter(EClass eClass) { // Fresh filter if(!isFiltering()) { saveState(); } fObjectFilter.add(eClass); refresh(); } void removeObjectFilter(EClass eClass) { fObjectFilter.remove(eClass); refresh(); } void addPropertiesFilter(String key) { // Fresh filter if(!isFiltering()) { saveState(); } fPropertiesFilter.add(key); refresh(); } void removePropertiesFilter(String key) { fPropertiesFilter.remove(key); refresh(); } void setShowAllFolders(boolean set) { if(set != fShowAllFolders) { fShowAllFolders = set; refresh(); } } boolean isShowAllFolders() { return fShowAllFolders; } void saveState() { fExpanded = fViewer.getExpandedTreePaths(); } void restoreState() { IStructuredSelection selection = (IStructuredSelection)fViewer.getSelection(); // first if(fExpanded != null) { fViewer.setExpandedTreePaths(fExpanded); } fViewer.setSelection(selection, true); } }
package com.tightdb; import java.nio.ByteBuffer; import java.util.Date; import com.tightdb.TableView.Order; import com.tightdb.internal.CloseMutex; import com.tightdb.typed.TightDB; /* Add isEqual(Table) */ /** * This class is a base class for all TightDB tables. The class supports all low * level methods (define/insert/delete/update) a table has. All the native * communications to the TightDB C++ library are also handled by this class. * * A user who wants to create a table of his choice will automatically inherit * from this class by the tightdb-class generator. * * As an example, let's create a table to keep records of an employee in a * company. * * For this purpose we will create a class named "employee" with an Entity * annotation as follows. * * @DefineTable * public class employee { * String name; * long age; * boolean hired; * byte[] imageData; * } * * The tightdb class generator will generate classes relevant to the employee: * * 1. Employee.java: Represents one employee of the employee table i.e., a single row. Getter/setter * methods are declared from which you will be able to set/get values * for a particular employee. * 2. EmployeeTable.java: Represents the class for storing a collection of employee i.e., a table * of rows. The class is inherited from the TableBase class as described above. * It has all the high level methods to manipulate Employee objects from the table. * 3. EmployeeView.java: Represents view of the employee table i.e., result set of queries. * * */ public class Table implements TableOrView { public static final long INFINITE = -1; protected long nativePtr; protected boolean immutable = false; // test: protected int tableNo; protected boolean DEBUG = false; protected static int TableCount = 0; static { TightDB.loadLibrary(); } /** * Construct a Table base object. It can be used to register columns in this * table. Registering into table is allowed only for empty tables. It * creates a native reference of the object and keeps a reference to it. */ public Table() { // Native methods work will be initialized here. Generated classes will // have nothing to do with the native functions. Generated Java Table // classes will work as a wrapper on top of table. nativePtr = createNative(); if (nativePtr == 0) throw new OutOfMemoryError("Out of native memory."); if (DEBUG) { tableNo = ++TableCount; System.err.println("====== New Tablebase " + tableNo + " : ptr = " + nativePtr); } } protected native long createNative(); protected Table(Object parent, long nativePtr, boolean immutable) { this.immutable = immutable; this.nativePtr = nativePtr; if (DEBUG) { tableNo = ++TableCount; System.err.println("===== New Tablebase(ptr) " + tableNo + " : ptr = " + nativePtr); } } @Override public void finalize() { if (DEBUG) System.err.println("==== FINALIZE " + tableNo + "..."); close(); } public void close() { synchronized (CloseMutex.getInstance()) { if (DEBUG) System.err.println("==== CLOSE " + tableNo + " ptr= " + nativePtr + " remaining " + TableCount); if (nativePtr == 0) return; if (DEBUG) TableCount nativeClose(nativePtr); nativePtr = 0; } } protected native void nativeClose(long nativeTablePtr); /* * Check if the Table is valid. * Whenever a Table/subtable is changed/updated all it's subtables are invalidated. * You can no longer perform any actions on the table, and if done anyway, an exception is thrown. * The only method you can call is 'isValid()'. */ public boolean isValid(){ return nativeIsValid(nativePtr); } protected native boolean nativeIsValid(long nativeTablePtr); private void verifyColumnName(String name) { if (name.length() > 63) { throw new IllegalArgumentException("Column names are currently limited to max 63 characters."); } } /** * Add a column to the table dynamically. * @return Index of the new column. */ public long addColumn (ColumnType type, String name) { verifyColumnName(name); return nativeAddColumn(nativePtr, type.getValue(), name); } protected native long nativeAddColumn(long nativeTablePtr, int type, String name); /** * Remove a column in the table dynamically. */ public void removeColumn(long columnIndex) { nativeRemoveColumn(nativePtr, columnIndex); } protected native void nativeRemoveColumn(long nativeTablePtr, long columnIndex); /** * Rename a column in the table. */ public void renameColumn(long columnIndex, String newName) { verifyColumnName(newName); nativeRenameColumn(nativePtr, columnIndex, newName); } protected native void nativeRenameColumn(long nativeTablePtr, long columnIndex, String name); /** * Updates a table specification from a Table specification structure. * Supported types - refer to @see ColumnType. * * @param columnType * data type of the column @see <code>ColumnType</code> * @param columnName * name of the column. Duplicate column name is not allowed. */ public void updateFromSpec(TableSpec tableSpec) { if (immutable) throwImmutable(); nativeUpdateFromSpec(nativePtr, tableSpec); } protected native void nativeUpdateFromSpec(long nativeTablePtr, TableSpec tableSpec); // Table Size and deletion. AutoGenerated subclasses are nothing to do with this // class. /** * Get the number of entries/rows of this table. * * @return The number of rows. */ public long size() { return nativeSize(nativePtr); } protected native long nativeSize(long nativeTablePtr); /** * Checks whether this table is empty or not. * * @return true if empty, otherwise false. */ public boolean isEmpty() { return size() == 0; } /** * Clears the table i.e., deleting all rows in the table. */ public void clear() { if (immutable) throwImmutable(); nativeClear(nativePtr); } protected native void nativeClear(long nativeTablePtr); // Column Information. /** * Returns the number of columns in the table. * * @return the number of columns. */ public long getColumnCount() { return nativeGetColumnCount(nativePtr); } protected native long nativeGetColumnCount(long nativeTablePtr); public TableSpec getTableSpec(){ return nativeGetTableSpec(nativePtr); } protected native TableSpec nativeGetTableSpec(long nativeTablePtr); /** * Returns the name of a column identified by columnIndex. Notice that the * index is zero based. * * @param columnIndex * the column index * @return the name of the column */ public String getColumnName(long columnIndex) { return nativeGetColumnName(nativePtr, columnIndex); } protected native String nativeGetColumnName(long nativeTablePtr, long columnIndex); /** * Returns the 0-based index of a column based on the name. * * @param name * column name * @return the index, -1 if not found */ public long getColumnIndex(String name) { long columnCount = getColumnCount(); for (int i = 0; i < columnCount; i++) { if (name.equals(getColumnName(i))) { return i; } } return -1; } /** * Get the type of a column identified by the columnIdex. * * @param columnIndex * index of the column. * @return Type of the particular column. */ public ColumnType getColumnType(long columnIndex) { return ColumnType.fromNativeValue(nativeGetColumnType(nativePtr, columnIndex)); } protected native int nativeGetColumnType(long nativeTablePtr, long columnIndex); /** * Removes a row from the specific index. As of now the entry is simply * removed from the table. * * @param rowIndex * the row index (starting with 0) * */ public void remove(long rowIndex) { if (immutable) throwImmutable(); nativeRemove(nativePtr, rowIndex); } protected native void nativeRemove(long nativeTablePtr, long rowIndex); public void removeLast() { if (immutable) throwImmutable(); nativeRemoveLast(nativePtr); } protected native void nativeRemoveLast(long nativeTablePtr); /** * EXPERIMENTAL function */ public void moveLastOver(long rowIndex) { if (immutable) throwImmutable(); nativeMoveLastOver(nativePtr, rowIndex); } protected native void nativeMoveLastOver(long nativeTablePtr, long rowIndex); // Row Handling methods. public long addEmptyRow() { if (immutable) throwImmutable(); return nativeAddEmptyRow(nativePtr, 1); } public long addEmptyRows(long rows) { if (immutable) throwImmutable(); if (rows < 1) throw new IllegalArgumentException("'rows' must be > 0."); return nativeAddEmptyRow(nativePtr, rows); } protected native long nativeAddEmptyRow(long nativeTablePtr, long rows); /** * Appends the specified row to the end of the table * @param values * @return The row index of the appended row */ public long add(Object... values) { long rowIndex = size(); addAt(rowIndex, values); return rowIndex; } /** * Inserts a row at the specified row index. Shifts the row currently at that row index and any subsequent rows down (adds one to their row index). * @param rowIndex * @param values */ public void addAt(long rowIndex, Object... values) { if (immutable) throwImmutable(); // Check index long size = size(); if (rowIndex > size) { throw new IllegalArgumentException("rowIndex " + String.valueOf(rowIndex) + " must be <= table.size() " + String.valueOf(size) + "."); } // Check values types int columns = (int)getColumnCount(); if (columns != values.length) { throw new IllegalArgumentException("The number of value parameters (" + String.valueOf(values.length) + ") does not match the number of columns in the table (" + String.valueOf(columns) + ")."); } ColumnType colTypes[] = new ColumnType[columns]; for (int columnIndex = 0; columnIndex < columns; columnIndex++) { Object value = values[columnIndex]; ColumnType colType = getColumnType(columnIndex); colTypes[columnIndex] = colType; if (!colType.matchObject(value)) { throw new IllegalArgumentException("Invalid argument no " + String.valueOf(1 + columnIndex) + ". Expected a value compatible with column type " + colType + ", but got " + value.getClass() + "."); } } // Insert values for (long columnIndex = 0; columnIndex < columns; columnIndex++) { Object value = values[(int)columnIndex]; switch (colTypes[(int)columnIndex]) { case BOOLEAN: nativeInsertBoolean(nativePtr, columnIndex, rowIndex, (Boolean)value); break; case INTEGER: nativeInsertLong(nativePtr, columnIndex, rowIndex, ((Number)value).longValue()); break; case FLOAT: nativeInsertFloat(nativePtr, columnIndex, rowIndex, ((Float)value).floatValue()); break; case DOUBLE: nativeInsertDouble(nativePtr, columnIndex, rowIndex, ((Double)value).doubleValue()); break; case STRING: nativeInsertString(nativePtr, columnIndex, rowIndex, (String)value); break; case DATE: nativeInsertDate(nativePtr, columnIndex, rowIndex, ((Date)value).getTime()/1000); break; case MIXED: nativeInsertMixed(nativePtr, columnIndex, rowIndex, Mixed.mixedValue(value)); break; case BINARY: if (value instanceof byte[]) nativeInsertByteArray(nativePtr, columnIndex, rowIndex, (byte[])value); else if (value instanceof ByteBuffer) nativeInsertByteBuffer(nativePtr, columnIndex, rowIndex, (ByteBuffer)value); break; case TABLE: nativeInsertSubTable(nativePtr, columnIndex, rowIndex); insertSubtableValues(rowIndex, columnIndex, value); break; default: throw new RuntimeException("Unexpected columnType: " + String.valueOf(colTypes[(int)columnIndex])); } } //Insert done. Use native, no need to check for immutable again here nativeInsertDone(nativePtr); } private void insertSubtableValues(long rowIndex, long columnIndex, Object value) { if (value != null) { // insert rows in subtable recursively Table subtable = getSubTableDuringInsert(columnIndex, rowIndex); int rows = ((Object[])value).length; for (int i=0; i<rows; ++i) { Object rowArr = ((Object[])value)[i]; subtable.addAt(i, (Object[])rowArr); } } } /** * Returns a view sorted by the specified column by the default order * @param columnIndex * @return */ public TableView getSortedView(long columnIndex){ TableView view = this.where().findAll(); view.sort(columnIndex); return view; } /** * Returns a view sorted by the specified column and order * @param columnIndex * @param order * @return */ public TableView getSortedView(long columnIndex, Order order){ TableView view = this.where().findAll(); view.sort(columnIndex, order); return view; } /** * Replaces the row at the specified position with the specified row. * @param rowIndex * @param values */ public void set(long rowIndex, Object... values) { if (immutable) throwImmutable(); // Check index long size = size(); if (rowIndex >= size) { throw new IllegalArgumentException("rowIndex " + String.valueOf(rowIndex) + " must be < table.size() " + String.valueOf(size) + "."); } // Verify number of 'values' int columns = (int)getColumnCount(); if (columns != values.length) { throw new IllegalArgumentException("The number of value parameters (" + String.valueOf(values.length) + ") does not match the number of columns in the table (" + String.valueOf(columns) + ")."); } // Verify type of 'values' ColumnType colTypes[] = new ColumnType[columns]; for (int columnIndex = 0; columnIndex < columns; columnIndex++) { Object value = values[columnIndex]; ColumnType colType = getColumnType(columnIndex); colTypes[columnIndex] = colType; if (!colType.matchObject(value)) { throw new IllegalArgumentException("Invalid argument no " + String.valueOf(1 + columnIndex) + ". Expected a value compatible with column type " + colType + ", but got " + value.getClass() + "."); } } // Now that all values are verified, we can remove the row and insert it again. // TODO: Can be optimized to only set the values (but clear any subtables) remove(rowIndex); addAt(rowIndex, values); } //Instance of the inner class InternalMethods. private InternalMethods internal = new InternalMethods(); //Returns InternalMethods instance with public internal methods. Should only be called by AbstractTable public InternalMethods getInternalMethods(){ return this.internal; } //Holds methods that must be publicly available for AbstractClass. //Should not be called when using the dynamic interface. The methods can be accessed by calling getInternalMethods() in Table class public class InternalMethods{ public void insertLong(long columnIndex, long rowIndex, long value) { if (immutable) throwImmutable(); nativeInsertLong(nativePtr, columnIndex, rowIndex, value); } public void insertDouble(long columnIndex, long rowIndex, double value) { if (immutable) throwImmutable(); nativeInsertDouble(nativePtr, columnIndex, rowIndex, value); } public void insertFloat(long columnIndex, long rowIndex, float value) { if (immutable) throwImmutable(); nativeInsertFloat(nativePtr, columnIndex, rowIndex, value); } public void insertBoolean(long columnIndex, long rowIndex, boolean value) { if (immutable) throwImmutable(); nativeInsertBoolean(nativePtr, columnIndex, rowIndex, value); } public void insertDate(long columnIndex, long rowIndex, Date date) { if (immutable) throwImmutable(); nativeInsertDate(nativePtr, columnIndex, rowIndex, date.getTime()/1000); } public void insertString(long columnIndex, long rowIndex, String value) { if (immutable) throwImmutable(); nativeInsertString(nativePtr, columnIndex, rowIndex, value); } public void insertMixed(long columnIndex, long rowIndex, Mixed data) { if (immutable) throwImmutable(); nativeInsertMixed(nativePtr, columnIndex, rowIndex, data); } /* public void insertBinary(long columnIndex, long rowIndex, ByteBuffer data) { if (immutable) throwImmutable(); //System.err.printf("\ninsertBinary(col %d, row %d, ByteBuffer)\n", columnIndex, rowIndex); //System.err.println("-- HasArray: " + (data.hasArray() ? "yes":"no") + " len= " + data.array().length); if (data.isDirect()) nativeInsertByteBuffer(nativePtr, columnIndex, rowIndex, data); else throw new RuntimeException("Currently ByteBuffer must be allocateDirect()."); // FIXME: support other than allocateDirect } */ public void insertBinary(long columnIndex, long rowIndex, byte[] data) { if (immutable) throwImmutable(); nativeInsertByteArray(nativePtr, columnIndex, rowIndex, data); } public void insertSubTable(long columnIndex, long rowIndex, Object[][] values) { if (immutable) throwImmutable(); nativeInsertSubTable(nativePtr, columnIndex, rowIndex); insertSubtableValues(rowIndex, columnIndex, values); } public void insertDone() { if (immutable) throwImmutable(); nativeInsertDone(nativePtr); } } protected native void nativeInsertFloat(long nativeTablePtr, long columnIndex, long rowIndex, float value); protected native void nativeInsertDouble(long nativeTablePtr, long columnIndex, long rowIndex, double value); protected native void nativeInsertLong(long nativeTablePtr, long columnIndex, long rowIndex, long value); protected native void nativeInsertBoolean(long nativeTablePtr, long columnIndex, long rowIndex, boolean value); protected native void nativeInsertDate(long nativePtr, long columnIndex, long rowIndex, long dateTimeValue); protected native void nativeInsertString(long nativeTablePtr, long columnIndex, long rowIndex, String value); protected native void nativeInsertMixed(long nativeTablePtr, long columnIndex, long rowIndex, Mixed mixed); protected native void nativeInsertByteBuffer(long nativeTablePtr, long columnIndex, long rowIndex, ByteBuffer data); protected native void nativeInsertByteArray(long nativePtr, long columnIndex, long rowIndex, byte[] data); protected native void nativeInsertSubTable(long nativeTablePtr, long columnIndex, long rowIndex); protected native void nativeInsertDone(long nativeTablePtr); // Getters public long getLong(long columnIndex, long rowIndex) { return nativeGetLong(nativePtr, columnIndex, rowIndex); } protected native long nativeGetLong(long nativeTablePtr, long columnIndex, long rowIndex); public boolean getBoolean(long columnIndex, long rowIndex) { return nativeGetBoolean(nativePtr, columnIndex, rowIndex); } protected native boolean nativeGetBoolean(long nativeTablePtr, long columnIndex, long rowIndex); public float getFloat(long columnIndex, long rowIndex) { return nativeGetFloat(nativePtr, columnIndex, rowIndex); } protected native float nativeGetFloat(long nativeTablePtr, long columnIndex, long rowIndex); public double getDouble(long columnIndex, long rowIndex) { return nativeGetDouble(nativePtr, columnIndex, rowIndex); } protected native double nativeGetDouble(long nativeTablePtr, long columnIndex, long rowIndex); public Date getDate(long columnIndex, long rowIndex) { return new Date(nativeGetDateTime(nativePtr, columnIndex, rowIndex)*1000); } protected native long nativeGetDateTime(long nativeTablePtr, long columnIndex, long rowIndex); /** * Get the value of a (string )cell. * * @param columnIndex * 0 based index value of the column * @param rowIndex * 0 based index of the row. * @return value of the particular cell */ public String getString(long columnIndex, long rowIndex) { return nativeGetString(nativePtr, columnIndex, rowIndex); } protected native String nativeGetString(long nativePtr, long columnIndex, long rowIndex); /** * Get the value of a (binary) cell. * * @param columnIndex * 0 based index value of the cell column * @param rowIndex * 0 based index value of the cell row * @return value of the particular cell. */ /* public ByteBuffer getBinaryByteBuffer(long columnIndex, long rowIndex) { return nativeGetByteBuffer(nativePtr, columnIndex, rowIndex); } protected native ByteBuffer nativeGetByteBuffer(long nativeTablePtr, long columnIndex, long rowIndex); */ public byte[] getBinaryByteArray(long columnIndex, long rowIndex) { return nativeGetByteArray(nativePtr, columnIndex, rowIndex); } protected native byte[] nativeGetByteArray(long nativePtr, long columnIndex, long rowIndex); public Mixed getMixed(long columnIndex, long rowIndex) { return nativeGetMixed(nativePtr, columnIndex, rowIndex); } public ColumnType getMixedType(long columnIndex, long rowIndex) { return ColumnType.fromNativeValue(nativeGetMixedType(nativePtr, columnIndex, rowIndex)); } protected native int nativeGetMixedType(long nativePtr, long columnIndex, long rowIndex); protected native Mixed nativeGetMixed(long nativeTablePtr, long columnIndex, long rowIndex); /** * * Note: The subtable returned will have to be closed again after use. * You can let javas garbage collector handle that or better yet call close() * after use. * * @param columnIndex column index of the cell * @param rowIndex row index of the cell * @return TableBase the subtable at the requested cell */ public Table getSubTable(long columnIndex, long rowIndex) { return new Table(this, nativeGetSubTable(nativePtr, columnIndex, rowIndex), immutable); } protected native long nativeGetSubTable(long nativeTablePtr, long columnIndex, long rowIndex); // Below version will allow to getSubTable when number of available rows are not updated yet - // which happens before an insertDone(). private Table getSubTableDuringInsert(long columnIndex, long rowIndex) { return new Table(this, nativeGetSubTableDuringInsert(nativePtr, columnIndex, rowIndex), immutable); } private native long nativeGetSubTableDuringInsert(long nativeTablePtr, long columnIndex, long rowIndex); public long getSubTableSize(long columnIndex, long rowIndex) { return nativeGetSubTableSize(nativePtr, columnIndex, rowIndex); } protected native long nativeGetSubTableSize(long nativeTablePtr, long columnIndex, long rowIndex); public void clearSubTable(long columnIndex, long rowIndex) { if (immutable) throwImmutable(); nativeClearSubTable(nativePtr, columnIndex, rowIndex); } protected native void nativeClearSubTable(long nativeTablePtr, long columnIndex, long rowIndex); // Setters public void setLong(long columnIndex, long rowIndex, long value) { if (immutable) throwImmutable(); nativeSetLong(nativePtr, columnIndex, rowIndex, value); } protected native void nativeSetLong(long nativeTablePtr, long columnIndex, long rowIndex, long value); public void setBoolean(long columnIndex, long rowIndex, boolean value) { if (immutable) throwImmutable(); nativeSetBoolean(nativePtr, columnIndex, rowIndex, value); } protected native void nativeSetBoolean(long nativeTablePtr, long columnIndex, long rowIndex, boolean value); public void setFloat(long columnIndex, long rowIndex, float value) { if (immutable) throwImmutable(); nativeSetFloat(nativePtr, columnIndex, rowIndex, value); } protected native void nativeSetFloat(long nativeTablePtr, long columnIndex, long rowIndex, float value); public void setDouble(long columnIndex, long rowIndex, double value) { if (immutable) throwImmutable(); nativeSetDouble(nativePtr, columnIndex, rowIndex, value); } protected native void nativeSetDouble(long nativeTablePtr, long columnIndex, long rowIndex, double value); public void setDate(long columnIndex, long rowIndex, Date date) { if (immutable) throwImmutable(); nativeSetDate(nativePtr, columnIndex, rowIndex, date.getTime()/1000); } protected native void nativeSetDate(long nativeTablePtr, long columnIndex, long rowIndex, long dateTimeValue); public void setString(long columnIndex, long rowIndex, String value) { if (immutable) throwImmutable(); nativeSetString(nativePtr, columnIndex, rowIndex, value); } protected native void nativeSetString(long nativeTablePtr, long columnIndex, long rowIndex, String value); /** * Sets the value for a (binary) cell. * * @param columnIndex * column index of the cell * @param rowIndex * row index of the cell * @param data * the ByteBuffer must be allocated with ByteBuffer.allocateDirect(len) */ /* public void setBinaryByteBuffer(long columnIndex, long rowIndex, ByteBuffer data) { if (immutable) throwImmutable(); if (data == null) throw new NullPointerException("Null array"); if (data.isDirect()) nativeSetByteBuffer(nativePtr, columnIndex, rowIndex, data); else throw new RuntimeException("Currently ByteBuffer must be allocateDirect()."); // FIXME: support other than allocateDirect } protected native void nativeSetByteBuffer(long nativeTablePtr, long columnIndex, long rowIndex, ByteBuffer data); */ public void setBinaryByteArray(long columnIndex, long rowIndex, byte[] data) { if (immutable) throwImmutable(); if (data == null) throw new NullPointerException("Null Array"); nativeSetByteArray(nativePtr, columnIndex, rowIndex, data); } protected native void nativeSetByteArray(long nativePtr, long columnIndex, long rowIndex, byte[] data); /** * Sets the value for a (mixed typed) cell. * * @param columnIndex * column index of the cell * @param rowIndex * row index of the cell * @param data */ public void setMixed(long columnIndex, long rowIndex, Mixed data) { if (immutable) throwImmutable(); if (data == null) throw new NullPointerException(); nativeSetMixed(nativePtr, columnIndex, rowIndex, data); } protected native void nativeSetMixed(long nativeTablePtr, long columnIndex, long rowIndex, Mixed data); /** * Add the value for to all cells in the column. * * @param columnIndex column index of the cell * @param value */ //!!!TODO: New. Support in highlevel API public void adjust(long columnIndex, long value) { if (immutable) throwImmutable(); nativeAddInt(nativePtr, columnIndex, value); } protected native void nativeAddInt(long nativeViewPtr, long columnIndex, long value); public void setIndex(long columnIndex) { if (immutable) throwImmutable(); if (getColumnType(columnIndex) != ColumnType.STRING) throw new IllegalArgumentException("Index is only supported on string columns."); nativeSetIndex(nativePtr, columnIndex); } protected native void nativeSetIndex(long nativePtr, long columnIndex); public boolean hasIndex(long columnIndex) { return nativeHasIndex(nativePtr, columnIndex); } protected native boolean nativeHasIndex(long nativePtr, long columnIndex); // Aggregate functions // Integers public long sum(long columnIndex) { return nativeSum(nativePtr, columnIndex); } protected native long nativeSum(long nativePtr, long columnIndex); public long maximum(long columnIndex) { return nativeMaximum(nativePtr, columnIndex); } protected native long nativeMaximum(long nativePtr, long columnIndex); public long minimum(long columnIndex) { return nativeMinimum(nativePtr, columnIndex); } protected native long nativeMinimum(long nativePtr, long columnnIndex); public double average(long columnIndex) { return nativeAverage(nativePtr, columnIndex); } protected native double nativeAverage(long nativePtr, long columnIndex); // Floats public double sumFloat(long columnIndex) { return nativeSumFloat(nativePtr, columnIndex); } protected native double nativeSumFloat(long nativePtr, long columnIndex); public float maximumFloat(long columnIndex) { return nativeMaximumFloat(nativePtr, columnIndex); } protected native float nativeMaximumFloat(long nativePtr, long columnIndex); public float minimumFloat(long columnIndex) { return nativeMinimumFloat(nativePtr, columnIndex); } protected native float nativeMinimumFloat(long nativePtr, long columnnIndex); public double averageFloat(long columnIndex) { return nativeAverageFloat(nativePtr, columnIndex); } protected native double nativeAverageFloat(long nativePtr, long columnIndex); // Doubles public double sumDouble(long columnIndex) { return nativeSumDouble(nativePtr, columnIndex); } protected native double nativeSumDouble(long nativePtr, long columnIndex); public double maximumDouble(long columnIndex) { return nativeMaximumDouble(nativePtr, columnIndex); } protected native double nativeMaximumDouble(long nativePtr, long columnIndex); public double minimumDouble(long columnIndex) { return nativeMinimumDouble(nativePtr, columnIndex); } protected native double nativeMinimumDouble(long nativePtr, long columnnIndex); public double averageDouble(long columnIndex) { return nativeAverageDouble(nativePtr, columnIndex); } protected native double nativeAverageDouble(long nativePtr, long columnIndex); // Count public long count(long columnIndex, long value) { return nativeCountLong(nativePtr, columnIndex, value); } protected native long nativeCountLong(long nativePtr, long columnIndex, long value); public long count(long columnIndex, float value) { return nativeCountFloat(nativePtr, columnIndex, value); } protected native long nativeCountFloat(long nativePtr, long columnIndex, float value); public long count(long columnIndex, double value) { return nativeCountDouble(nativePtr, columnIndex, value); } protected native long nativeCountDouble(long nativePtr, long columnIndex, double value); public long count(long columnIndex, String value) { return nativeCountString(nativePtr, columnIndex, value); } protected native long nativeCountString(long nativePtr, long columnIndex, String value); // Searching methods. public TableQuery where() { return new TableQuery(nativeWhere(nativePtr), immutable); } protected native long nativeWhere(long nativeTablePtr); public long findFirstLong(long columnIndex, long value) { return nativeFindFirstInt(nativePtr, columnIndex, value); } protected native long nativeFindFirstInt(long nativeTablePtr, long columnIndex, long value); public long findFirstBoolean(long columnIndex, boolean value) { return nativeFindFirstBool(nativePtr, columnIndex, value); } protected native long nativeFindFirstBool(long nativePtr, long columnIndex, boolean value); public long findFirstFloat(long columnIndex, float value) { return nativeFindFirstFloat(nativePtr, columnIndex, value); } protected native long nativeFindFirstFloat(long nativePtr, long columnIndex, float value); public long findFirstDouble(long columnIndex, double value) { return nativeFindFirstDouble(nativePtr, columnIndex, value); } protected native long nativeFindFirstDouble(long nativePtr, long columnIndex, double value); public long findFirstDate(long columnIndex, Date date) { return nativeFindFirstDate(nativePtr, columnIndex, date.getTime()/1000); } protected native long nativeFindFirstDate(long nativeTablePtr, long columnIndex, long dateTimeValue); public long findFirstString(long columnIndex, String value) { return nativeFindFirstString(nativePtr, columnIndex, value); } protected native long nativeFindFirstString(long nativeTablePtr, long columnIndex, String value); public TableView findAllLong(long columnIndex, long value) { return new TableView(nativeFindAllInt(nativePtr, columnIndex, value), immutable); } protected native long nativeFindAllInt(long nativePtr, long columnIndex, long value); public TableView findAllBoolean(long columnIndex, boolean value) { return new TableView(nativeFindAllBool(nativePtr, columnIndex, value), immutable); } protected native long nativeFindAllBool(long nativePtr, long columnIndex, boolean value); public TableView findAllFloat(long columnIndex, float value) { return new TableView(nativeFindAllFloat(nativePtr, columnIndex, value), immutable); } protected native long nativeFindAllFloat(long nativePtr, long columnIndex, float value); public TableView findAllDouble(long columnIndex, double value) { return new TableView(nativeFindAllDouble(nativePtr, columnIndex, value), immutable); } protected native long nativeFindAllDouble(long nativePtr, long columnIndex, double value); public TableView findAllDate(long columnIndex, Date date) { return new TableView(nativeFindAllDate(nativePtr, columnIndex, date.getTime()/1000), immutable); } protected native long nativeFindAllDate(long nativePtr, long columnIndex, long dateTimeValue); public TableView findAllString(long columnIndex, String value) { return new TableView(nativeFindAllString(nativePtr, columnIndex, value), immutable); } protected native long nativeFindAllString(long nativePtr, long columnIndex, String value); // Requires that the first column is a string column with index public long lookup(String value) { if (!this.hasIndex(0) || this.getColumnType(0) != ColumnType.STRING) throw new RuntimeException("lookup() requires index on column 0 which must be a String column."); return nativeLookup(nativePtr, value); } protected native long nativeLookup(long nativeTablePtr, String value); // Experimental feature public long lowerBoundLong(long columnIndex, long value) { return nativeLowerBoundInt(nativePtr, columnIndex, value); } public long upperBoundLong(long columnIndex, long value) { return nativeUpperBoundInt(nativePtr, columnIndex, value); } protected native long nativeLowerBoundInt(long nativePtr, long columnIndex, long value); protected native long nativeUpperBoundInt(long nativePtr, long columnIndex, long value); public TableView distinct(long columnIndex) { return new TableView(nativeDistinct(nativePtr, columnIndex), immutable); } protected native long nativeDistinct(long nativePtr, long columnIndex); // Optimize public void optimize() { if (immutable) throwImmutable(); nativeOptimize(nativePtr); } protected native void nativeOptimize(long nativeTablePtr); public String toJson() { return nativeToJson(nativePtr); } protected native String nativeToJson(long nativeTablePtr); public String toString() { return nativeToString(nativePtr, INFINITE); } public String toString(long maxRows) { return nativeToString(nativePtr, maxRows); } protected native String nativeToString(long nativeTablePtr, long maxRows); public String rowToString(long rowIndex) { return nativeRowToString(nativePtr, rowIndex); } protected native String nativeRowToString(long nativeTablePtr, long rowIndex); private void throwImmutable() { throw new IllegalStateException("Mutable method call during read transaction."); } }
package fi.vincit.multiusertest.util; import fi.vincit.multiusertest.annotation.MultiUserConfigClass; import fi.vincit.multiusertest.test.MultiUserConfig; import fi.vincit.multiusertest.test.UserRoleIT; import org.junit.Before; import org.junit.internal.runners.statements.RunBefores; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import org.junit.runners.model.TestClass; import java.lang.reflect.Field; import java.util.List; import java.util.Objects; /** * Helper class for delegating calls from JUnit runner. * Does some required method filtering and helps executing * Before methods in correct order. */ public class RunnerDelegate { private final UserIdentifier producerIdentifier; private final UserIdentifier userIdentifier; private final TestMethodFilter shouldRunChecker; public RunnerDelegate(UserIdentifier producerIdentifier, UserIdentifier consumerIdentifier) { Objects.requireNonNull(producerIdentifier); Objects.requireNonNull(consumerIdentifier); this.producerIdentifier = producerIdentifier; this.userIdentifier = consumerIdentifier; this.shouldRunChecker = new TestMethodFilter(producerIdentifier, consumerIdentifier); } // Only for testing RunnerDelegate(UserIdentifier producerIdentifier, UserIdentifier userIdentifier, TestMethodFilter shouldRunChecker) { Objects.requireNonNull(producerIdentifier); Objects.requireNonNull(userIdentifier); Objects.requireNonNull(shouldRunChecker); this.producerIdentifier = producerIdentifier; this.userIdentifier = userIdentifier; this.shouldRunChecker = shouldRunChecker; } public List<FrameworkMethod> filterMethods(List<FrameworkMethod> methods) { List<FrameworkMethod> filteredMethods = shouldRunChecker.filter(methods); if (!filteredMethods.isEmpty()) { return filteredMethods; } else { return methods; } } public boolean isIgnored(FrameworkMethod child, boolean isIgnoredByParent) { return !shouldRunChecker.shouldRun(child) || isIgnoredByParent; } public String testName(FrameworkMethod method) { return String.format("%s", method.getName()); } public String getName(TestClass testClass) { return String.format("%s", getIdentifierDescription()); } private String getIdentifierDescription() { return String.format("producer={%s}, consumer={%s}", producerIdentifier, userIdentifier); } public Object createTest(Object testInstance) { if (testInstance instanceof UserRoleIT) { UserRoleIT roleItInstance = (UserRoleIT) testInstance; roleItInstance.setUsers(producerIdentifier, userIdentifier); return roleItInstance; } else { return testInstance; } } private MultiUserConfig getConfigComponent(Object testInstance) { Optional<MultiUserConfig> config = Optional.empty(); try { for (Field field : testInstance.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(MultiUserConfigClass.class)) { field.setAccessible(true); config = Optional.ofNullable((MultiUserConfig) field.get(testInstance)); field.setAccessible(false); break; } } if (config.isPresent()) { return config.get(); } else { throw new IllegalStateException("MultiUserConfigClass not found on " + testInstance.getClass().getSimpleName()); } } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } public Statement withBefores(final TestClass testClass, final Object target, final Statement statement) { List<FrameworkMethod> befores = testClass.getAnnotatedMethods( Before.class); final Statement runLoginBeforeTestMethod = new Statement() { @Override public void evaluate() throws Throwable { preEvaluateConfig(); statement.evaluate(); } private void preEvaluateConfig() { UserRoleIT userRoleIt = null; if (target instanceof UserRoleIT) { userRoleIt = (UserRoleIT) target; } else { userRoleIt = getConfigComponent(target); userRoleIt.setUsers(producerIdentifier, userIdentifier); } userRoleIt.logInAs(LoginRole.PRODUCER); } }; return befores.isEmpty() ? runLoginBeforeTestMethod : new RunBefores(runLoginBeforeTestMethod, befores, target); } }
package com.yahoo.search.dispatch.searchcluster; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.yahoo.container.handler.VipStatus; import com.yahoo.net.HostName; import com.yahoo.prelude.Pong; import com.yahoo.search.cluster.ClusterMonitor; import com.yahoo.search.cluster.NodeManager; import com.yahoo.search.result.ErrorMessage; import com.yahoo.vespa.config.search.DispatchConfig; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalInt; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * A model of a search cluster we might want to dispatch queries to. * * @author bratseth */ public class SearchCluster implements NodeManager<Node> { private static final Logger log = Logger.getLogger(SearchCluster.class.getName()); private final DispatchConfig dispatchConfig; private final int size; private final String clusterId; private final ImmutableMap<Integer, Group> groups; private final ImmutableMultimap<String, Node> nodesByHost; private final ImmutableList<Group> orderedGroups; private final ClusterMonitor<Node> clusterMonitor; private final VipStatus vipStatus; private PingFactory pingFactory; /** * A search node on this local machine having the entire corpus, which we therefore * should prefer to dispatch directly to, or empty if there is no such local search node. * If there is one, we also maintain the VIP status of this container based on the availability * of the corpus on this local node (up + has coverage), such that this node is taken out of rotation * if it only queries this cluster when the local node cannot be used, to avoid unnecessary * cross-node network traffic. */ private final Optional<Node> localCorpusDispatchTarget; public SearchCluster(String clusterId, DispatchConfig dispatchConfig, int containerClusterSize, VipStatus vipStatus) { this.clusterId = clusterId; this.dispatchConfig = dispatchConfig; this.vipStatus = vipStatus; List<Node> nodes = toNodes(dispatchConfig); this.size = nodes.size(); // Create groups ImmutableMap.Builder<Integer, Group> groupsBuilder = new ImmutableMap.Builder<>(); for (Map.Entry<Integer, List<Node>> group : nodes.stream().collect(Collectors.groupingBy(Node::group)).entrySet()) { Group g = new Group(group.getKey(), group.getValue()); groupsBuilder.put(group.getKey(), g); } this.groups = groupsBuilder.build(); LinkedHashMap<Integer, Group> groupIntroductionOrder = new LinkedHashMap<>(); nodes.forEach(node -> groupIntroductionOrder.put(node.group(), groups.get(node.group))); this.orderedGroups = ImmutableList.<Group>builder().addAll(groupIntroductionOrder.values()).build(); // Index nodes by host ImmutableMultimap.Builder<String, Node> nodesByHostBuilder = new ImmutableMultimap.Builder<>(); for (Node node : nodes) nodesByHostBuilder.put(node.hostname(), node); this.nodesByHost = nodesByHostBuilder.build(); this.localCorpusDispatchTarget = findLocalCorpusDispatchTarget(HostName.getLocalhost(), size, containerClusterSize, nodesByHost, groups); this.clusterMonitor = new ClusterMonitor<>(this); } public void startClusterMonitoring(PingFactory pingFactory) { this.pingFactory = pingFactory; for (var group : orderedGroups) { for (var node : group.nodes()) clusterMonitor.add(node, true); } } private static Optional<Node> findLocalCorpusDispatchTarget(String selfHostname, int searchClusterSize, int containerClusterSize, ImmutableMultimap<String, Node> nodesByHost, ImmutableMap<Integer, Group> groups) { // A search node in the search cluster in question is configured on the same host as the currently running container. // It has all the data <==> No other nodes in the search cluster have the same group id as this node. // That local search node responds. // The search cluster to be searched has at least as many nodes as the container cluster we're running in. ImmutableCollection<Node> localSearchNodes = nodesByHost.get(selfHostname); // Only use direct dispatch if we have exactly 1 search node on the same machine: if (localSearchNodes.size() != 1) return Optional.empty(); Node localSearchNode = localSearchNodes.iterator().next(); Group localSearchGroup = groups.get(localSearchNode.group()); // Only use direct dispatch if the local search node has the entire corpus if (localSearchGroup.nodes().size() != 1) return Optional.empty(); // Only use direct dispatch if this container cluster has at least as many nodes as the search cluster // to avoid load skew/preserve fanout in the case where a subset of the search nodes are also containers. // This disregards the case where the search and container clusters are partially overlapping. // Such configurations produce skewed load in any case. if (containerClusterSize < searchClusterSize) return Optional.empty(); return Optional.of(localSearchNode); } private static ImmutableList<Node> toNodes(DispatchConfig dispatchConfig) { ImmutableList.Builder<Node> nodesBuilder = new ImmutableList.Builder<>(); Predicate<DispatchConfig.Node> filter; if (dispatchConfig.useLocalNode()) { final String hostName = HostName.getLocalhost(); filter = node -> node.host().equals(hostName); } else { filter = node -> true; } for (DispatchConfig.Node node : dispatchConfig.node()) { if (filter.test(node)) { nodesBuilder.add(new Node(node.key(), node.host(), node.fs4port(), node.group())); } } return nodesBuilder.build(); } public DispatchConfig dispatchConfig() { return dispatchConfig; } /** Returns the number of nodes in this cluster (across all groups) */ public int size() { return size; } /** Returns the groups of this cluster as an immutable map indexed by group id */ public ImmutableMap<Integer, Group> groups() { return groups; } /** Returns the groups of this cluster as an immutable list in introduction order */ public ImmutableList<Group> orderedGroups() { return orderedGroups; } /** Returns the n'th (zero-indexed) group in the cluster if possible */ public Optional<Group> group(int n) { if (orderedGroups.size() > n) { return Optional.of(orderedGroups.get(n)); } else { return Optional.empty(); } } /** Returns the number of nodes per group - size()/groups.size() */ public int groupSize() { if (groups.size() == 0) return size(); return size() / groups.size(); } public int groupsWithSufficientCoverage() { int covered = 0; for (Group g : orderedGroups) { if (g.hasSufficientCoverage()) { covered++; } } return covered; } /** * Returns the single, local node we should dispatch queries directly to, * or empty if we should not dispatch directly. */ public Optional<Node> localCorpusDispatchTarget() { if ( localCorpusDispatchTarget.isEmpty()) return Optional.empty(); // Only use direct dispatch if the local group has sufficient coverage Group localSearchGroup = groups.get(localCorpusDispatchTarget.get().group()); if ( ! localSearchGroup.hasSufficientCoverage()) return Optional.empty(); // Only use direct dispatch if the local search node is not down if ( localCorpusDispatchTarget.get().isWorking() == Boolean.FALSE) return Optional.empty(); return localCorpusDispatchTarget; } /** Called by the cluster monitor when node state changes to working */ @Override public void working(Node node) { node.setWorking(true); updateVipStatusOnNodeChange(node, true); } /** Called by the cluster monitor when node state changes to failed */ @Override public void failed(Node node) { node.setWorking(false); updateVipStatusOnNodeChange(node, true); } private void updateSufficientCoverage(Group group, boolean sufficientCoverage) { if (sufficientCoverage == group.hasSufficientCoverage()) return; // no change group.setHasSufficientCoverage(sufficientCoverage); updateVipStatusOnCoverageChange(group, sufficientCoverage); } private void updateVipStatusOnNodeChange(Node node, boolean nodeIsWorking) { if (localCorpusDispatchTarget.isEmpty()) { // consider entire cluster if (hasInformationAboutAllNodes()) setInRotationOnlyIf(hasWorkingNodes()); } else if (usesLocalCorpusIn(node)) { // follow the status of this node setInRotationOnlyIf(nodeIsWorking); } } private void updateVipStatusOnCoverageChange(Group group, boolean sufficientCoverage) { if ( localCorpusDispatchTarget.isEmpty()) { // consider entire cluster // VIP status does not depend on coverage } else if (usesLocalCorpusIn(group)) { // follow the status of this group setInRotationOnlyIf(sufficientCoverage); } } private void setInRotationOnlyIf(boolean inRotation) { if (inRotation) vipStatus.addToRotation(clusterId); else vipStatus.removeFromRotation(clusterId); } private boolean hasInformationAboutAllNodes() { return nodesByHost.values().stream().allMatch(node -> node.isWorking() != null); } private boolean hasWorkingNodes() { return nodesByHost.values().stream().anyMatch(node -> node.isWorking() != Boolean.FALSE ); } private boolean usesLocalCorpusIn(Node node) { return localCorpusDispatchTarget.isPresent() && localCorpusDispatchTarget.get().equals(node); } private boolean usesLocalCorpusIn(Group group) { return localCorpusDispatchTarget.isPresent() && localCorpusDispatchTarget.get().group() == group.id(); } /** Used by the cluster monitor to manage node status */ @Override public void ping(Node node, Executor executor) { if (pingFactory == null) return; // not initialized yet FutureTask<Pong> futurePong = new FutureTask<>(pingFactory.createPinger(node, clusterMonitor)); executor.execute(futurePong); Pong pong = getPong(futurePong, node); futurePong.cancel(true); if (pong.badResponse()) { clusterMonitor.failed(node, pong.getError(0)); } else { if (pong.activeDocuments().isPresent()) { node.setActiveDocuments(pong.activeDocuments().get()); } clusterMonitor.responded(node); } } private void pingIterationCompletedSingleGroup() { Group group = groups.values().iterator().next(); group.aggregateActiveDocuments(); // With just one group sufficient coverage may not be the same as full coverage, as the // group will always be marked sufficient for use. updateSufficientCoverage(group, true); boolean fullCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), group.getActiveDocuments(), group.getActiveDocuments()); trackGroupCoverageChanges(0, group, fullCoverage, group.getActiveDocuments()); } private void pingIterationCompletedMultipleGroups() { int numGroups = orderedGroups.size(); // Update active documents per group and use it to decide if the group should be active long[] activeDocumentsInGroup = new long[numGroups]; long sumOfActiveDocuments = 0; for(int i = 0; i < numGroups; i++) { Group group = orderedGroups.get(i); group.aggregateActiveDocuments(); activeDocumentsInGroup[i] = group.getActiveDocuments(); sumOfActiveDocuments += activeDocumentsInGroup[i]; } boolean anyGroupsSufficientCoverage = false; for (int i = 0; i < numGroups; i++) { Group group = orderedGroups.get(i); long activeDocuments = activeDocumentsInGroup[i]; long averageDocumentsInOtherGroups = (sumOfActiveDocuments - activeDocuments) / (numGroups - 1); boolean sufficientCoverage = isGroupCoverageSufficient(group.workingNodes(), group.nodes().size(), activeDocuments, averageDocumentsInOtherGroups); anyGroupsSufficientCoverage = anyGroupsSufficientCoverage || sufficientCoverage; updateSufficientCoverage(group, sufficientCoverage); trackGroupCoverageChanges(i, group, sufficientCoverage, averageDocumentsInOtherGroups); } } /** * Update statistics after a round of issuing pings. * Note that this doesn't wait for pings to return, so it will typically accumulate data from * last rounds pinging, or potentially (although unlikely) some combination of new and old data. */ @Override public void pingIterationCompleted() { int numGroups = orderedGroups.size(); if (numGroups == 1) { pingIterationCompletedSingleGroup(); } else { pingIterationCompletedMultipleGroups(); } } private boolean isGroupCoverageSufficient(int workingNodes, int nodesInGroup, long activeDocuments, long averageDocumentsInOtherGroups) { boolean sufficientCoverage = true; if (averageDocumentsInOtherGroups > 0) { double coverage = 100.0 * (double) activeDocuments / averageDocumentsInOtherGroups; sufficientCoverage = coverage >= dispatchConfig.minActivedocsPercentage(); } if (sufficientCoverage) { sufficientCoverage = isGroupNodeCoverageSufficient(workingNodes, nodesInGroup); } return sufficientCoverage; } private boolean isGroupNodeCoverageSufficient(int workingNodes, int nodesInGroup) { int nodesAllowedDown = dispatchConfig.maxNodesDownPerGroup() + (int) (((double) nodesInGroup * (100.0 - dispatchConfig.minGroupCoverage())) / 100.0); return workingNodes + nodesAllowedDown >= nodesInGroup; } private Pong getPong(FutureTask<Pong> futurePong, Node node) { try { return futurePong.get(clusterMonitor.getConfiguration().getFailLimit(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.log(Level.WARNING, "Exception pinging " + node, e); return new Pong(ErrorMessage.createUnspecifiedError("Ping was interrupted: " + node)); } catch (ExecutionException e) { log.log(Level.WARNING, "Exception pinging " + node, e); return new Pong(ErrorMessage.createUnspecifiedError("Execution was interrupted: " + node)); } catch (TimeoutException e) { return new Pong(ErrorMessage.createNoAnswerWhenPingingNode("Ping thread timed out")); } } /** * Calculate whether a subset of nodes in a group has enough coverage */ public boolean isPartialGroupCoverageSufficient(OptionalInt knownGroupId, List<Node> nodes) { if (orderedGroups.size() == 1) { boolean sufficient = nodes.size() >= groupSize() - dispatchConfig.maxNodesDownPerGroup(); return sufficient; } if (knownGroupId.isEmpty()) { return false; } int groupId = knownGroupId.getAsInt(); Group group = groups.get(groupId); if (group == null) { return false; } int nodesInGroup = group.nodes().size(); long sumOfActiveDocuments = 0; int otherGroups = 0; for (Group g : orderedGroups) { if (g.id() != groupId) { sumOfActiveDocuments += g.getActiveDocuments(); otherGroups++; } } long activeDocuments = 0; for (Node n : nodes) { activeDocuments += n.getActiveDocuments(); } long averageDocumentsInOtherGroups = sumOfActiveDocuments / otherGroups; boolean sufficient = isGroupCoverageSufficient(nodes.size(), nodesInGroup, activeDocuments, averageDocumentsInOtherGroups); return sufficient; } private void trackGroupCoverageChanges(int index, Group group, boolean fullCoverage, long averageDocuments) { boolean changed = group.isFullCoverageStatusChanged(fullCoverage); if (changed) { int requiredNodes = groupSize() - dispatchConfig.maxNodesDownPerGroup(); if (fullCoverage) { log.info(() -> String.format("Group %d is now good again (%d/%d active docs, coverage %d/%d)", index, group.getActiveDocuments(), averageDocuments, group.workingNodes(), groupSize())); } else { log.warning(() -> String.format("Coverage of group %d is only %d/%d (requires %d)", index, group.workingNodes(), groupSize(), requiredNodes)); } } } }
package org.apereo.cas.logout; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.authentication.principal.WebApplicationService; import org.apereo.cas.ticket.TicketGrantingTicket; import org.apereo.cas.util.CompressionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * This logout manager handles the Single Log Out process. * * @author Jerome Leleu * @since 4.0.0 */ public class DefaultLogoutManager implements LogoutManager { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLogoutManager.class); private final boolean singleLogoutCallbacksDisabled; private final LogoutMessageCreator logoutMessageBuilder; private final SingleLogoutServiceMessageHandler singleLogoutServiceMessageHandler; private final LogoutExecutionPlan logoutExecutionPlan; /** * Build the logout manager. * * @param logoutMessageBuilder the builder to construct logout messages. * @param singleLogoutServiceMessageHandler who actually perform the logout request * @param singleLogoutCallbacksDisabled Set if the logout is disabled. * @param logoutExecutionPlan the logout execution plan */ public DefaultLogoutManager(final LogoutMessageCreator logoutMessageBuilder, final SingleLogoutServiceMessageHandler singleLogoutServiceMessageHandler, final boolean singleLogoutCallbacksDisabled, final LogoutExecutionPlan logoutExecutionPlan) { this.logoutMessageBuilder = logoutMessageBuilder; this.singleLogoutServiceMessageHandler = singleLogoutServiceMessageHandler; this.singleLogoutCallbacksDisabled = singleLogoutCallbacksDisabled; this.logoutExecutionPlan = logoutExecutionPlan; } /** * Perform a back channel logout for a given ticket granting ticket and returns all the logout requests. * * @param ticket a given ticket granting ticket. * @return all logout requests. */ @Override public List<LogoutRequest> performLogout(final TicketGrantingTicket ticket) { LOGGER.info("Performing logout operations for [{}]", ticket.getId()); if (this.singleLogoutCallbacksDisabled) { LOGGER.info("Single logout callbacks are disabled"); return new ArrayList<>(0); } final List<LogoutRequest> logoutRequests = performLogoutForTicket(ticket); this.logoutExecutionPlan.getLogoutHandlers().forEach(h -> { LOGGER.debug("Invoking logout handler [{}] to process ticket [{}]", h.getClass().getSimpleName(), ticket.getId()); h.handle(ticket); }); LOGGER.info("[{}] logout requests were processed", logoutRequests.size()); return logoutRequests; } private List<LogoutRequest> performLogoutForTicket(final TicketGrantingTicket ticketToBeLoggedOut) { return Stream.concat(Stream.of(ticketToBeLoggedOut), ticketToBeLoggedOut.getProxyGrantingTickets().stream()) .map(ticket -> ticket.getServices().entrySet()) .flatMap(Set::stream) .filter(entry -> entry.getValue() instanceof WebApplicationService) .map(entry -> { final Service service = entry.getValue(); LOGGER.debug("Handling single logout callback for [{}]", service); return this.singleLogoutServiceMessageHandler.handle((WebApplicationService) service, entry.getKey()); }) .filter(Objects::nonNull) .collect(Collectors.toList()); } /** * Create a logout message for front channel logout. * * @param logoutRequest the logout request. * @return a front SAML logout message. */ @Override public String createFrontChannelLogoutMessage(final LogoutRequest logoutRequest) { final String logoutMessage = this.logoutMessageBuilder.create(logoutRequest); LOGGER.trace("Attempting to deflate the logout message [{}]", logoutMessage); return CompressionUtils.deflate(logoutMessage); } }
package org.eclipse.hono.util; import java.net.HttpURLConnection; /** * A container for the result returned by a Hono API that implements the request response pattern. * * @param <T> denotes the concrete type of the payload that is part of the result */ public class RequestResponseResult<T> { private final int status; private final T payload; /** * Creates a new result for a status code and payload. * * @param status The code indicating the outcome of processing the request. * @param payload The payload to convey to the sender of the request. */ protected RequestResponseResult(final int status, final T payload) { this.status = status; this.payload = payload; } /** * Gets the status code indicating the outcome of the request. * * @return The code. */ public final int getStatus() { return status; } /** * Gets the payload to convey to the sender of the request. * * @return The payload. */ public final T getPayload() { return payload; } /** * Checks if this result's status is <em>OK</em>. * * @return {@code true} if status == 200. */ public final boolean isOk() { return HttpURLConnection.HTTP_OK == status; } /** * Checks if this result's status code represents * an error. * * @return {@code true} if the result contains an error code. */ public final boolean isError() { return status >= HttpURLConnection.HTTP_BAD_REQUEST && status < 600; } }
package org.csstudio.remote.management; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; import org.eclipse.core.runtime.Platform; /** * <p> * Dispatches the results returned by management commands to receivers that can * process them. * </p> * * <p> * When a result is dispatched, the dispatcher first tries to dispatch it to one * of the preset receivers. Thus, the preset receivers can be used by * administration tools to ensure that certain kinds of results (such as error * messages) are always dispatched to a known receiver provided by the * administration tool. If none of the preset receivers can handle the result, * the dispatcher will then look for a suitable receiver that was provided as an * extension; and finally, if none of the extensions can handle the result, will * dispatch it to a default receiver. * </p> * * @author Joerg Rathlev */ public class ResultDispatcher { private static final String EXTENSION_POINT_ID = "org.csstudio.remote.managementCommandResultReceivers"; private final Map<String, IResultReceiver> _presetReceivers; private final Map<String, IResultReceiver> _extensionReceivers; private final IResultReceiver _defaultReceiver; /** * Creates a new result dispatcher. * * @param defaultReceiver * the default receiver. Results for which no preset of extension * receiver is found will be dispatched to the default receiver. */ public ResultDispatcher(IResultReceiver defaultReceiver) { if (defaultReceiver == null) { throw new NullPointerException("defaultReceiver must not be null"); } _presetReceivers = new HashMap<String, IResultReceiver>(); _extensionReceivers = new HashMap<String, IResultReceiver>(); _defaultReceiver = defaultReceiver; readExtensionPoint(); } /** * Adds a preset receiver to this dispatcher. * * @param resultType * the type of results that this dispatcher will dispatch to the * receiver. * @param receiver * the receiver. */ public void addPresetReceiver(String resultType, IResultReceiver receiver) { if (resultType == null || receiver == null) { throw new NullPointerException("resultType and receiver must not be null"); } _presetReceivers.put(resultType, receiver); } /** * Dispatches a command result to a receiver. * * @param result * a command result. */ public void dispatch(CommandResult result) { IResultReceiver receiver = findReceiver(result.getType()); receiver.processResult(result); } /** * Returns the receiver for the specified result type. * * @param resultType * the result type. * @return the receiver. */ private IResultReceiver findReceiver(String resultType) { IResultReceiver receiver; receiver = _presetReceivers.get(resultType); if (receiver == null) { receiver = _extensionReceivers.get(resultType); if (receiver == null) { receiver = _defaultReceiver; } } return receiver; } /** * Reads the receivers registered via the * <code>managementCommandResultReceivers</code> extension point and adds * them to the extension receivers. */ private void readExtensionPoint() { IExtension[] extensions = Platform.getExtensionRegistry() .getExtensionPoint(EXTENSION_POINT_ID).getExtensions(); for (IExtension extension : extensions) { IConfigurationElement[] configElements = extension.getConfigurationElements(); for (IConfigurationElement configElement : configElements) { if ("receiver".equals(configElement.getName())) { readReceiverContribution(configElement); } } } } /** * Reads a single receiver configuration element. * * @param configElement * the configuration element. */ private void readReceiverContribution(IConfigurationElement configElement) { try { String type = configElement.getAttribute("resultType"); IResultReceiver receiver = (IResultReceiver) configElement.createExecutableExtension("class"); _extensionReceivers.put(type, receiver); } catch (CoreException e) { // TODO: error handling } } }
package com.xeiam.datasets.higgsboson.business; /** * @author timmolter */ public class HiggsBoson { private int EventId; private float DER_mass_MMC; private float DER_mass_transverse_met_lep; private float DER_mass_vis; private float DER_pt_h; private float DER_deltaeta_jet_jet; private float DER_mass_jet_jet; private float DER_prodeta_jet_jet; private float DER_deltar_tau_lep; private float DER_pt_tot; private float DER_sum_pt; private float DER_pt_ratio_lep_tau; private float DER_met_phi_centrality; private float DER_lep_eta_centrality; private float PRI_tau_pt; private float PRI_tau_eta; private float PRI_tau_phi; private float PRI_lep_pt; private float PRI_lep_eta; private float PRI_lep_phi; private float PRI_met; private float PRI_met_phi; private float PRI_met_sumet; private float PRI_jet_num; private float PRI_jet_leading_pt; private float PRI_jet_leading_eta; private float PRI_jet_leading_phi; private float PRI_jet_subleading_pt; private float PRI_jet_subleading_eta; private float PRI_jet_subleading_phi; private float PRI_jet_all_pt; private float Weight; private String Label; public int getEventId() { return EventId; } public void setEventId(int eventId) { EventId = eventId; } public float getDER_mass_MMC() { return DER_mass_MMC; } public void setDER_mass_MMC(float dER_mass_MMC) { DER_mass_MMC = dER_mass_MMC; } public float getDER_mass_transverse_met_lep() { return DER_mass_transverse_met_lep; } public void setDER_mass_transverse_met_lep(float dER_mass_transverse_met_lep) { DER_mass_transverse_met_lep = dER_mass_transverse_met_lep; } public float getDER_mass_vis() { return DER_mass_vis; } public void setDER_mass_vis(float dER_mass_vis) { DER_mass_vis = dER_mass_vis; } public float getDER_pt_h() { return DER_pt_h; } public void setDER_pt_h(float dER_pt_h) { DER_pt_h = dER_pt_h; } public float getDER_deltaeta_jet_jet() { return DER_deltaeta_jet_jet; } public void setDER_deltaeta_jet_jet(float dER_deltaeta_jet_jet) { DER_deltaeta_jet_jet = dER_deltaeta_jet_jet; } public float getDER_mass_jet_jet() { return DER_mass_jet_jet; } public void setDER_mass_jet_jet(float dER_mass_jet_jet) { DER_mass_jet_jet = dER_mass_jet_jet; } public float getDER_prodeta_jet_jet() { return DER_prodeta_jet_jet; } public void setDER_prodeta_jet_jet(float dER_prodeta_jet_jet) { DER_prodeta_jet_jet = dER_prodeta_jet_jet; } public float getDER_deltar_tau_lep() { return DER_deltar_tau_lep; } public void setDER_deltar_tau_lep(float dER_deltar_tau_lep) { DER_deltar_tau_lep = dER_deltar_tau_lep; } public float getDER_pt_tot() { return DER_pt_tot; } public void setDER_pt_tot(float dER_pt_tot) { DER_pt_tot = dER_pt_tot; } public float getDER_sum_pt() { return DER_sum_pt; } public void setDER_sum_pt(float dER_sum_pt) { DER_sum_pt = dER_sum_pt; } public float getDER_pt_ratio_lep_tau() { return DER_pt_ratio_lep_tau; } public void setDER_pt_ratio_lep_tau(float dER_pt_ratio_lep_tau) { DER_pt_ratio_lep_tau = dER_pt_ratio_lep_tau; } public float getDER_met_phi_centrality() { return DER_met_phi_centrality; } public void setDER_met_phi_centrality(float dER_met_phi_centrality) { DER_met_phi_centrality = dER_met_phi_centrality; } public float getDER_lep_eta_centrality() { return DER_lep_eta_centrality; } public void setDER_lep_eta_centrality(float dER_lep_eta_centrality) { DER_lep_eta_centrality = dER_lep_eta_centrality; } public float getPRI_tau_pt() { return PRI_tau_pt; } public void setPRI_tau_pt(float pRI_tau_pt) { PRI_tau_pt = pRI_tau_pt; } public float getPRI_tau_eta() { return PRI_tau_eta; } public void setPRI_tau_eta(float pRI_tau_eta) { PRI_tau_eta = pRI_tau_eta; } public float getPRI_tau_phi() { return PRI_tau_phi; } public void setPRI_tau_phi(float pRI_tau_phi) { PRI_tau_phi = pRI_tau_phi; } public float getPRI_lep_pt() { return PRI_lep_pt; } public void setPRI_lep_pt(float pRI_lep_pt) { PRI_lep_pt = pRI_lep_pt; } public float getPRI_lep_eta() { return PRI_lep_eta; } public void setPRI_lep_eta(float pRI_lep_eta) { PRI_lep_eta = pRI_lep_eta; } public float getPRI_lep_phi() { return PRI_lep_phi; } public void setPRI_lep_phi(float pRI_lep_phi) { PRI_lep_phi = pRI_lep_phi; } public float getPRI_met() { return PRI_met; } public void setPRI_met(float pRI_met) { PRI_met = pRI_met; } public float getPRI_met_phi() { return PRI_met_phi; } public void setPRI_met_phi(float pRI_met_phi) { PRI_met_phi = pRI_met_phi; } public float getPRI_met_sumet() { return PRI_met_sumet; } public void setPRI_met_sumet(float pRI_met_sumet) { PRI_met_sumet = pRI_met_sumet; } public float getPRI_jet_num() { return PRI_jet_num; } public void setPRI_jet_num(float pRI_jet_num) { PRI_jet_num = pRI_jet_num; } public float getPRI_jet_leading_pt() { return PRI_jet_leading_pt; } public void setPRI_jet_leading_pt(float pRI_jet_leading_pt) { PRI_jet_leading_pt = pRI_jet_leading_pt; } public float getPRI_jet_leading_eta() { return PRI_jet_leading_eta; } public void setPRI_jet_leading_eta(float pRI_jet_leading_eta) { PRI_jet_leading_eta = pRI_jet_leading_eta; } public float getPRI_jet_leading_phi() { return PRI_jet_leading_phi; } public void setPRI_jet_leading_phi(float pRI_jet_leading_phi) { PRI_jet_leading_phi = pRI_jet_leading_phi; } public float getPRI_jet_subleading_pt() { return PRI_jet_subleading_pt; } public void setPRI_jet_subleading_pt(float pRI_jet_subleading_pt) { PRI_jet_subleading_pt = pRI_jet_subleading_pt; } public float getPRI_jet_subleading_eta() { return PRI_jet_subleading_eta; } public void setPRI_jet_subleading_eta(float pRI_jet_subleading_eta) { PRI_jet_subleading_eta = pRI_jet_subleading_eta; } public float getPRI_jet_subleading_phi() { return PRI_jet_subleading_phi; } public void setPRI_jet_subleading_phi(float pRI_jet_subleading_phi) { PRI_jet_subleading_phi = pRI_jet_subleading_phi; } public float getPRI_jet_all_pt() { return PRI_jet_all_pt; } public void setPRI_jet_all_pt(float pRI_jet_all_pt) { PRI_jet_all_pt = pRI_jet_all_pt; } public float getWeight() { return Weight; } public void setWeight(float weight) { Weight = weight; } public String getLabel() { return Label; } public void setLabel(String label) { Label = label; } @Override public String toString() { return "HiggsBoson [EventId=" + EventId + ", DER_mass_MMC=" + DER_mass_MMC + ", DER_mass_transverse_met_lep=" + DER_mass_transverse_met_lep + ", DER_mass_vis=" + DER_mass_vis + ", DER_pt_h=" + DER_pt_h + ", DER_deltaeta_jet_jet=" + DER_deltaeta_jet_jet + ", DER_mass_jet_jet=" + DER_mass_jet_jet + ", DER_prodeta_jet_jet=" + DER_prodeta_jet_jet + ", DER_deltar_tau_lep=" + DER_deltar_tau_lep + ", DER_pt_tot=" + DER_pt_tot + ", DER_sum_pt=" + DER_sum_pt + ", DER_pt_ratio_lep_tau=" + DER_pt_ratio_lep_tau + ", DER_met_phi_centrality=" + DER_met_phi_centrality + ", DER_lep_eta_centrality=" + DER_lep_eta_centrality + ", PRI_tau_pt=" + PRI_tau_pt + ", PRI_tau_eta=" + PRI_tau_eta + ", PRI_tau_phi=" + PRI_tau_phi + ", PRI_lep_pt=" + PRI_lep_pt + ", PRI_lep_eta=" + PRI_lep_eta + ", PRI_lep_phi=" + PRI_lep_phi + ", PRI_met=" + PRI_met + ", PRI_met_phi=" + PRI_met_phi + ", PRI_met_sumet=" + PRI_met_sumet + ", PRI_jet_num=" + PRI_jet_num + ", PRI_jet_leading_pt=" + PRI_jet_leading_pt + ", PRI_jet_leading_eta=" + PRI_jet_leading_eta + ", PRI_jet_leading_phi=" + PRI_jet_leading_phi + ", PRI_jet_subleading_pt=" + PRI_jet_subleading_pt + ", PRI_jet_subleading_eta=" + PRI_jet_subleading_eta + ", PRI_jet_subleading_phi=" + PRI_jet_subleading_phi + ", PRI_jet_all_pt=" + PRI_jet_all_pt + ", Weight=" + Weight + ", Label=" + Label + "]"; } }
package org.deegree.cs.transformations; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; import javax.vecmath.Point3d; import org.deegree.cs.CRSCodeType; import org.deegree.cs.CRSIdentifiable; import org.deegree.cs.CoordinateTransformer; import org.deegree.cs.components.Axis; import org.deegree.cs.coordinatesystems.CompoundCRS; import org.deegree.cs.coordinatesystems.CoordinateSystem; import org.deegree.cs.coordinatesystems.GeocentricCRS; import org.deegree.cs.coordinatesystems.GeographicCRS; import org.deegree.cs.coordinatesystems.ProjectedCRS; import org.deegree.cs.exceptions.TransformationException; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TransformationAccuracyTest implements CRSDefines { static { datum_6289.setToWGS84( wgs_1672 ); datum_6258.setToWGS84( wgs_1188 ); datum_6314.setToWGS84( wgs_1777 ); datum_6171.setToWGS84( wgs_1188 ); } private static Logger LOG = LoggerFactory.getLogger( TransformationAccuracyTest.class ); /** * Creates a {@link CoordinateTransformer} for the given coordinate system. * * @param targetCrs * to which incoming coordinates will be transformed. * @return the transformer which is able to transform coordinates to the given crs.. */ private CoordinateTransformer getGeotransformer( CoordinateSystem targetCrs ) { assertNotNull( targetCrs ); return new CoordinateTransformer( targetCrs ); } /** * Creates an epsilon string with following layout axis.getName: origPoint - resultPoint = epsilon Unit.getName(). * * @param sourceCoordinate * on the given axis * @param targetCoordinate * on the given axis * @param allowedEpsilon * defined by test. * @param axis * of the coordinates * @return a String representation. */ private String createEpsilonString( boolean failure, double sourceCoordinate, double targetCoordinate, double allowedEpsilon, Axis axis ) { double epsilon = sourceCoordinate - targetCoordinate; StringBuilder sb = new StringBuilder( 400 ); sb.append( axis.getName() ).append( " (result - orig = error [allowedError]): " ); sb.append( sourceCoordinate ).append( " - " ).append( targetCoordinate ); sb.append( " = " ).append( epsilon ).append( axis.getUnits() ); sb.append( " [" ).append( allowedEpsilon ).append( axis.getUnits() ).append( "]" ); if ( failure ) { sb.append( " [FAILURE]" ); } return sb.toString(); } /** * Transforms the given coordinates in the sourceCRS to the given targetCRS and checks if they lie within the given * epsilon range to the reference point. If successful the transformed will be logged. * * @param sourcePoint * to transform * @param targetPoint * to which the result shall be checked. * @param epsilons * for each axis * @param sourceCRS * of the origPoint * @param targetCRS * of the targetPoint. * @return the string containing the success string. * @throws TransformationException * @throws AssertionError * if one of the axis of the transformed point do not lie within the given epsilon range. */ private String doAccuracyTest( Point3d sourcePoint, Point3d targetPoint, Point3d epsilons, CoordinateSystem sourceCRS, CoordinateSystem targetCRS ) throws TransformationException { assertNotNull( sourceCRS ); assertNotNull( targetCRS ); assertNotNull( sourcePoint ); assertNotNull( targetPoint ); assertNotNull( epsilons ); CoordinateTransformer transformer = getGeotransformer( targetCRS ); List<Point3d> tmp = new ArrayList<Point3d>( 1 ); tmp.add( new Point3d( sourcePoint ) ); Point3d result = transformer.transform( sourceCRS, tmp ).get( 0 ); assertNotNull( result ); boolean xFail = Math.abs( result.getX() - targetPoint.x ) > epsilons.x; String xString = createEpsilonString( xFail, result.getX(), targetPoint.x, epsilons.x, targetCRS.getAxis()[0] ); boolean yFail = Math.abs( result.getY() - targetPoint.y ) > epsilons.y; String yString = createEpsilonString( yFail, result.getY(), targetPoint.y, epsilons.y, targetCRS.getAxis()[1] ); // Z-Axis if available boolean zFail = false; String zString = null; if ( targetCRS.getDimension() == 3 ) { zFail = Math.abs( result.getZ() - targetPoint.z ) > epsilons.z; zString = createEpsilonString( zFail, result.getZ(), targetPoint.z, epsilons.z, targetCRS.getAxis()[2] ); } else if ( targetCRS.getDimension() == 2 && sourceCRS.getDimension() == 2 && !Double.isNaN( sourcePoint.getZ() ) ) { // 3rd coordinate should be passed double epsilon = result.getZ() - targetPoint.z; zFail = Math.abs( epsilon ) > 0; StringBuilder sb = new StringBuilder( 400 ); sb.append( "passed z (result - orig = error [allowedError]): " ); sb.append( result.getZ() ).append( " - " ).append( targetPoint.z ); sb.append( " = " ).append( epsilon ); sb.append( " [" ).append( 0 ).append( "]" ); if ( zFail ) { sb.append( " [FAILURE]" ); } zString = sb.toString(); } StringBuilder sb = new StringBuilder(); if ( xFail || yFail || zFail ) { sb.append( "[FAILED] " ); } else { sb.append( "[SUCCESS] " ); } sb.append( "Transformation (" ).append( sourceCRS.getCode().toString() ); sb.append( " -> " ).append( targetCRS.getCode().toString() ).append( ")\n" ); sb.append( xString ); sb.append( "\n" ).append( yString ); if ( zString != null ) { sb.append( "\n" ).append( zString ); } if ( xFail || yFail || zFail ) { throw new AssertionError( sb.toString() ); } return sb.toString(); } /** * Do an forward and inverse accuracy test. * * @param sourceCRS * @param targetCRS * @param source * @param target * @param forwardEpsilon * @param inverseEpsilon * @throws TransformationException */ private void doForwardAndInverse( CoordinateSystem sourceCRS, CoordinateSystem targetCRS, Point3d source, Point3d target, Point3d forwardEpsilon, Point3d inverseEpsilon ) throws TransformationException { StringBuilder output = new StringBuilder(); output.append( "Transforming forward/inverse -> projected with id: '" ); output.append( sourceCRS.getCode().toString() ); output.append( "' and projected with id: '" ); output.append( targetCRS.getCode().toString() ); output.append( "'.\n" ); // forward transform. boolean forwardSuccess = true; try { output.append( "Forward transformation: " ); output.append( doAccuracyTest( source, target, forwardEpsilon, sourceCRS, targetCRS ) ); } catch ( AssertionError ae ) { output.append( ae.getLocalizedMessage() ); forwardSuccess = false; } // inverse transform. boolean inverseSuccess = true; try { output.append( "\nInverse transformation: " ); output.append( doAccuracyTest( target, source, inverseEpsilon, targetCRS, sourceCRS ) ); } catch ( AssertionError ae ) { output.append( ae.getLocalizedMessage() ); inverseSuccess = false; } LOG.debug( output.toString() ); assertEquals( true, forwardSuccess ); assertEquals( true, inverseSuccess ); } /** * Test the forward/inverse transformation from a compound_projected crs (EPSG:28992) to another compound_projected * crs (EPSG:25832) * * @throws TransformationException */ @Test public void testCompoundToCompound() throws TransformationException { // Source crs espg:28992 CompoundCRS sourceCRS = new CompoundCRS( heightAxis, projected_28992, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( projected_28992.getCode().getOriginal() + "_compound" ) } ) ); // Target crs espg:25832 CompoundCRS targetCRS = new CompoundCRS( heightAxis, projected_25832, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( projected_25832.getCode().getOriginal() + "_compound" ) } ) ); Point3d sourcePoint = new Point3d( 121397.572, 487325.817, 6.029 ); Point3d targetPoint = new Point3d( 220513.823, 5810438.891, 49 ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the transformation from a compound_projected crs (EPSG:28992_compound) to a geographic crs (EPSG:4258) * coordinate system . * * @throws TransformationException */ @Test public void testCompoundToGeographic() throws TransformationException { // Source crs espg:28992 CompoundCRS sourceCRS = new CompoundCRS( heightAxis, projected_28992, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( projected_28992.getCode().getOriginal() + "_compound" ) } ) ); // Target crs espg:4258 GeographicCRS targetCRS = geographic_4258; Point3d sourcePoint = new Point3d( 236694.856, 583952.500, 1.307 ); Point3d targetPoint = new Point3d( 6.610765, 53.235916, 42 ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, new Point3d( METER_EPSILON, 0.17, 0.6 ) ); } /** * Test the transformation from a compound_projected crs (EPSG:28992_compound) to a geographic crs (EPSG:4258) * coordinate system . * * @throws TransformationException */ @Test public void testCompoundToGeographicEqualOnEllips() throws TransformationException { // urn:x-ogc:def:crs:EPSG:4979 // urn:x-ogc:def:crs:EPSG:4326 // EPSG:4326 CompoundCRS sourceCRS = new CompoundCRS( heightAxis, GeographicCRS.WGS84_YX, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( "urn:x-ogc:def:crs:EPSG:4979" ) } ) ); // Target crs espg:4258 GeographicCRS targetCRS = GeographicCRS.WGS84_YX; // taken from wfs cite 1.1.0 test Point3d sourcePoint = new Point3d( 46.074, 9.799, 600.2 ); Point3d targetPoint = new Point3d( 46.074, 9.799, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_D ); } /** * Test the transformation from a compound_projected crs (EPSG:28992_compound) to a geographic crs (EPSG:4258) * coordinate system . * * @throws TransformationException */ @Test public void testCompoundToGeographicEqualOnEllipsNotOnAxis() throws TransformationException { // urn:x-ogc:def:crs:EPSG:4979 // urn:x-ogc:def:crs:EPSG:4326 // EPSG:4326 CompoundCRS sourceCRS = new CompoundCRS( heightAxis, GeographicCRS.WGS84_YX, 600.2, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( "urn:x-ogc:def:crs:EPSG:4979" ) } ) ); // Target crs espg:4258 GeographicCRS targetCRS = GeographicCRS.WGS84; // taken from wfs cite 1.1.0 test Point3d sourcePoint = new Point3d( 46.074, 9.799, 600.2 ); Point3d targetPoint = new Point3d( 9.799, 46.074, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_D ); } /** * Test the forward/inverse transformation from a compound_projected crs (EPSG:31467) to a geocentric crs * (EPSG:4964) * * @throws TransformationException */ @Test public void testCompoundToGeocentric() throws TransformationException { // source crs epsg:31467 CompoundCRS sourceCRS = new CompoundCRS( heightAxis, projected_31467, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( projected_31467.getCode().getOriginal() + "_compound" ) } ) ); // Target crs EPSG:4964 GeocentricCRS targetCRS = geocentric_4964; // do the testing Point3d sourcePoint = new Point3d( 3532465.57, 5301523.49, 817 ); Point3d targetPoint = new Point3d( 4230602.192492622, 702858.4858986374, 4706428.360722791 ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the forward/inverse transformation from a compound_geographic crs (EPSG:4326) to a projected crs * (EPSG:31467) * * @throws TransformationException */ @Test public void testCompoundToProjected() throws TransformationException { // Source WGS:84_compound CompoundCRS sourceCRS = new CompoundCRS( heightAxis, GeographicCRS.WGS84, 20, new CRSIdentifiable( new CRSCodeType[] { new CRSCodeType( GeographicCRS.WGS84.getCode().getOriginal() + "_compound" ) } ) ); // Target EPSG:31467 ProjectedCRS targetCRS = projected_31467; // kind regards to vodafone for supplying reference points. Point3d sourcePoint = new Point3d( 9.432778, 47.851111, 870.6 ); Point3d targetPoint = new Point3d( 3532465.57, 5301523.49, 817 ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_D ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:28992) to another projected crs (EPSG:25832) * * @throws TransformationException */ @Test public void testProjectedToProjected() throws TransformationException { // Source crs espg:28992 ProjectedCRS sourceCRS = projected_28992; // Target crs espg:25832 ProjectedCRS targetCRS = projected_25832; Point3d sourcePoint = new Point3d( 191968.31999475454, 326455.285005203, Double.NaN ); Point3d targetPoint = new Point3d( 283065.845, 5646206.125, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:28992) to another projected crs (EPSG:25832) * * @throws TransformationException */ @Test public void testProjectedToProjectedWithLatLonGeoAxis() throws TransformationException { // Source crs espg:28992 ProjectedCRS sourceCRS = projected_28992_lat_lon; // Target crs espg:25832 ProjectedCRS targetCRS = projected_25832_lat_lon; Point3d sourcePoint = new Point3d( 191968.31999475454, 326455.285005203, Double.NaN ); Point3d targetPoint = new Point3d( 283065.845, 5646206.125, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:28992) to another projected crs (EPSG:25832) * * @throws TransformationException */ @Test public void testProjectedToProjectedWithYX() throws TransformationException { // Source crs espg:28992 ProjectedCRS sourceCRS = projected_28992_yx; // Target crs espg:25832 ProjectedCRS targetCRS = projected_25832; Point3d sourcePoint = new Point3d( 326455.285005203, 191968.31999475454, Double.NaN ); Point3d targetPoint = new Point3d( 283065.845, 5646206.125, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:31467) to a geographic crs (EPSG:4258) * * @throws TransformationException */ @Test public void testProjectedToGeographic() throws TransformationException { // Source crs espg:31467 ProjectedCRS sourceCRS = projected_31467; // Target crs espg:4258 GeographicCRS targetCRS = geographic_4258; // with kind regards to vodafone for supplying reference points Point3d sourcePoint = new Point3d( 3532465.57, 5301523.49, Double.NaN ); Point3d targetPoint = new Point3d( 9.432778, 47.851111, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:31467) with yx axis order to a geographic crs * (EPSG:4258). * * @throws TransformationException */ @Test public void testProjectedWithYXToGeographic() throws TransformationException { // Source crs espg:31467 ProjectedCRS sourceCRS = projected_31467_yx; // Target crs espg:4258 GeographicCRS targetCRS = geographic_4258; // with kind regards to vodafone for supplying reference points Point3d sourcePoint = new Point3d( 5301523.49, 3532465.57, Double.NaN ); Point3d targetPoint = new Point3d( 9.432778, 47.851111, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:31467) based on a lat/lon geographic crs to a * geographic crs (EPSG:4258). * * @throws TransformationException */ @Test public void testProjectedOnGeoLatLonToGeographic() throws TransformationException { // Source crs espg:31467 ProjectedCRS sourceCRS = projected_31467_lat_lon; // Target crs espg:4258 GeographicCRS targetCRS = geographic_4258; // with kind regards to vodafone for supplying reference points Point3d sourcePoint = new Point3d( 3532465.57, 5301523.49, Double.NaN ); Point3d targetPoint = new Point3d( 9.432778, 47.851111, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:31467) to a geographic crs (EPSG:4258) which * has lat/lon axis * * @throws TransformationException */ @Test public void testProjectedToGeographicLatLon() throws TransformationException { // Source crs espg:31467 ProjectedCRS sourceCRS = projected_31467; // Target crs espg:4258 GeographicCRS targetCRS = geographic_4258_lat_lon; // with kind regards to vodafone for supplying reference points Point3d sourcePoint = new Point3d( 3532465.57, 5301523.49, Double.NaN ); Point3d targetPoint = new Point3d( 47.851111, 9.432778, Double.NaN ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_M ); } /** * Test the forward/inverse transformation from a projected crs (EPSG:28992) to a geocentric crs (EPSG:4964) * * @throws TransformationException */ @Test public void testProjectedToGeocentric() throws TransformationException { ProjectedCRS sourceCRS = projected_28992; // Target crs EPSG:4964 GeocentricCRS targetCRS = geocentric_4964; // do the testing created reference points with deegree (not a fine test!!) Point3d sourcePoint = new Point3d( 191968.31999475454, 326455.285005203, Double.NaN ); Point3d targetPoint = new Point3d( 4006964.9993508584, 414997.8479008863, 4928439.8089122595 ); doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_M ); } /** * Test the forward/inverse transformation from a geographic crs (EPSG:4314) to another geographic crs (EPSG:4258) * * @throws TransformationException */ @Test public void testGeographicToGeographic() throws TransformationException { // source crs epsg:4314 GeographicCRS sourceCRS = geographic_4314; // target crs epsg:4258 GeographicCRS targetCRS = geographic_4258; // with kind regards to vodafone for supplying reference points. Point3d sourcePoint = new Point3d( 8.83319047, 54.90017335, Double.NaN ); Point3d targetPoint = new Point3d( 8.83213115, 54.89846442, Double.NaN ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_D ); } /** * Test the forward/inverse transformation from a geographic crs (EPSG:4314) lat/lon to another geographic crs * (EPSG:4258) lon/lat * * @throws TransformationException */ @Test public void testGeographicLatLonToGeographic() throws TransformationException { // source crs epsg:4314 GeographicCRS sourceCRS = geographic_4314_lat_lon; // target crs epsg:4258 GeographicCRS targetCRS = geographic_4258; // with kind regards to vodafone for supplying reference points. Point3d sourcePoint = new Point3d( 54.90017335, 8.83319047, Double.NaN ); Point3d targetPoint = new Point3d( 8.83213115, 54.89846442, Double.NaN ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_D ); } /** * Test the forward/inverse transformation from a geographic crs (EPSG:4314) lat/lon to another geographic crs * (EPSG:4258) lat/lon * * @throws TransformationException */ @Test public void testGeographicLatLonToGeographicLatLon() throws TransformationException { // source crs epsg:4314 GeographicCRS sourceCRS = geographic_4314_lat_lon; // target crs epsg:4258 GeographicCRS targetCRS = geographic_4258_lat_lon; // with kind regards to vodafone for supplying reference points. Point3d sourcePoint = new Point3d( 54.90017335, 8.83319047, Double.NaN ); Point3d targetPoint = new Point3d( 54.89846442, 8.83213115, Double.NaN ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_D ); } /** * Test the forward/inverse transformation from a geographic crs (EPSG:4314) to a geocentric crs (EPSG:4964) * * @throws TransformationException * * @throws TransformationException */ @Test public void testGeographicToGeocentric() throws TransformationException { // source crs epsg:4314 GeographicCRS sourceCRS = geographic_4314; // target crs epsg:4964 GeocentricCRS targetCRS = geocentric_4964; // created with deegree not a fine reference Point3d sourcePoint = new Point3d( 8.83319047, 54.90017335, Double.NaN ); Point3d targetPoint = new Point3d( 3632280.522352362, 564392.6943947134, 5194921.3092999635 ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_D ); } /** * Test the forward/inverse transformation from a geocentric (dummy based on bessel) to another geocentric crs * (EPSG:4964 based on etrs89) * * @throws TransformationException */ @Test public void testGeocentricToGeocentric() throws TransformationException { // source crs is a dummy based on the epsg:4314 == bessel datum. GeocentricCRS sourceCRS = geocentric_dummy; // target crs epsg:4964 etrs89 based GeocentricCRS targetCRS = geocentric_4964; // created with deegree not a fine reference Point3d sourcePoint = new Point3d( 3631650.239831989, 564363.5250884632, 5194468.545970947 ); Point3d targetPoint = new Point3d( 3632280.522352362, 564392.6943947134, 5194921.3092999635 ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_M, EPSILON_D ); } @Test public void test2DTo2Dwith3rdCoordinate() throws TransformationException { // source crs is epsg:31467 ProjectedCRS sourceCRS = projected_31467; // target crs is epsg:4326 GeographicCRS targetCRS = GeographicCRS.WGS84; // created with deegree not a fine reference Point3d sourcePoint = new Point3d( 3532465.57, 5301523.49, 42 ); Point3d targetPoint = new Point3d( 9.432778, 47.851111, 42 ); // do the testing doForwardAndInverse( sourceCRS, targetCRS, sourcePoint, targetPoint, EPSILON_D, EPSILON_M ); } }
package org.lemurproject.galago.core.parse; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.lemurproject.galago.tupleflow.Parameters; import org.lemurproject.galago.tupleflow.Utility; import org.xerial.snappy.SnappyInputStream; import org.xerial.snappy.SnappyOutputStream; public class Document implements Serializable { // document id - this values are serialized public int identifier = -1; // document data - these values are serialized public String name; public Map<String, String> metadata; public String text; public List<String> terms; public List<Tag> tags; // other data - used to generate an identifier; these values can not be serialized! public int fileId = -1; public int totalFileCount = -1; public Document() { metadata = new HashMap(); } public Document(String identifier, String text) { this(); this.name = identifier; this.text = text; } public Document(Document d) { this.identifier = d.identifier; this.name = d.name; this.metadata = new HashMap(d.metadata); this.text = d.text; this.terms = new ArrayList(d.terms); this.tags = new ArrayList(d.tags); this.fileId = d.fileId; this.totalFileCount = d.totalFileCount; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Identifier: ").append(name).append("\n"); if (metadata != null) { sb.append("Metadata: \n"); for (Map.Entry<String, String> entry : metadata.entrySet()) { sb.append("<"); sb.append(entry.getKey()).append(",").append(entry.getValue()); sb.append("> "); } } if (terms != null) { sb.append("Term vector: \n"); for (String s : terms) { sb.append(s).append(" "); } } sb.append("\n"); if (text != null) { sb.append("Text :").append(text); } return sb.toString(); } public static byte[] serialize(Parameters p, Document doc) throws IOException { ByteArrayOutputStream array = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(new SnappyOutputStream(array)); boolean metadata = p.get("corpusMetadata", true); boolean text = p.get("corpusText", true); boolean terms = p.get("corpusTerms", true); boolean tags = p.get("corpusTags", true); // options output.writeBoolean(metadata); output.writeBoolean(text); output.writeBoolean(terms); output.writeBoolean(tags); // identifier output.writeInt(doc.identifier); // name byte[] bytes = Utility.fromString(doc.name); output.writeInt(bytes.length); output.write(bytes); if (metadata) { // metadata if (doc.metadata == null) { output.writeInt(0); } else { output.writeInt(doc.metadata.size()); for (String key : doc.metadata.keySet()) { bytes = Utility.fromString(key); output.writeInt(bytes.length); output.write(bytes); bytes = Utility.fromString(doc.metadata.get(key)); output.writeInt(bytes.length); output.write(bytes); } } } if (text) { // text if (doc.text == null) { output.writeInt(0); } else { bytes = Utility.fromString(doc.text); output.writeInt(bytes.length); output.write(bytes); } } if (terms) { // terms if (doc.terms == null) { output.writeInt(0); } else { output.writeInt(doc.terms.size()); for (String term : doc.terms) { bytes = Utility.fromString(term); output.writeInt(bytes.length); output.write(bytes); } } } if (tags) { // tags if (doc.tags == null) { output.writeInt(0); } else { output.writeInt(doc.tags.size()); for (Tag tag : doc.tags) { bytes = Utility.fromString(tag.name); output.writeInt(bytes.length); output.write(bytes); output.writeInt(tag.begin); output.writeInt(tag.end); output.writeInt(tag.attributes.size()); for (String key : tag.attributes.keySet()) { bytes = Utility.fromString(key); output.writeInt(bytes.length); output.write(bytes); bytes = Utility.fromString(tag.attributes.get(key)); output.writeInt(bytes.length); output.write(bytes); } } } } output.close(); return array.toByteArray(); } public static Document deserialize(byte[] data) throws IOException { ByteArrayInputStream stream = new ByteArrayInputStream(data); return deserialize(new DataInputStream(stream)); } public static Document deserialize(DataInputStream stream) throws IOException { DataInputStream input = new DataInputStream(new SnappyInputStream(stream)); Document d = new Document(); // options boolean metadata = input.readBoolean(); boolean text = input.readBoolean(); boolean terms = input.readBoolean(); boolean tags = input.readBoolean(); // identifier d.identifier = input.readInt(); // name byte[] docNameBytes = new byte[input.readInt()]; input.readFully(docNameBytes); d.name = Utility.toString(docNameBytes); if (metadata) { // metadata int metadataCount = input.readInt(); d.metadata = new HashMap(metadataCount); for (int i = 0; i < metadataCount; i++) { byte[] keyBytes = new byte[input.readInt()]; input.readFully(keyBytes); String key = Utility.toString(keyBytes); byte[] valueBytes = new byte[input.readInt()]; input.readFully(valueBytes); String value = Utility.toString(valueBytes); d.metadata.put(key, value); } } if (text) { // text byte[] textBytes = new byte[input.readInt()]; input.readFully(textBytes); d.text = Utility.toString(textBytes); } if (terms) { // terms int termCount = input.readInt(); d.terms = new ArrayList(termCount); for (int i = 0; i < termCount; i++) { byte[] termBytes = new byte[input.readInt()]; input.readFully(termBytes); d.terms.add(Utility.toString(termBytes)); } } if (tags) { // tags int tagCount = input.readInt(); d.tags = new ArrayList(tagCount); for (int i = 0; i < tagCount; i++) { byte[] tagNameBytes = new byte[input.readInt()]; input.readFully(tagNameBytes); String tagName = Utility.toString(tagNameBytes); int tagBegin = input.readInt(); int tagEnd = input.readInt(); HashMap<String, String> attributes = new HashMap(); int attrCount = input.readInt(); for (int j = 0; j < attrCount; j++) { byte[] keyBytes = new byte[input.readInt()]; input.readFully(keyBytes); String key = Utility.toString(keyBytes); byte[] valueBytes = new byte[input.readInt()]; input.readFully(valueBytes); String value = Utility.toString(valueBytes); attributes.put(key, value); } Tag t = new Tag(tagName, attributes, tagBegin, tagEnd); d.tags.add(t); } } input.close(); return d; } }
package org.mskcc.cbio.oncokb.validation; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.mskcc.cbio.oncokb.model.Alteration; import org.mskcc.cbio.oncokb.model.Evidence; import org.mskcc.cbio.oncokb.model.Gene; import org.mskcc.cbio.oncokb.model.MutationEffect; import org.mskcc.cbio.oncokb.model.Oncogenicity; import org.mskcc.cbio.oncokb.util.AlterationUtils; import org.mskcc.cbio.oncokb.util.EvidenceUtils; import org.mskcc.cbio.oncokb.util.GeneUtils; /** * * @author jiaojiao */ public class validation { public static void main(String[] args) throws IOException { Map<Gene, Set<Evidence>> allGeneBasedEvidences = EvidenceUtils.getAllGeneBasedEvidences(); Set<Gene> genes = GeneUtils.getAllGenes(); Integer count = 0; String result1 = "", result2 = "", result3 = ""; Integer length1 = 0, length2 = 0, length3 = 0; ArrayList<String> specialAlterations = new ArrayList<>(Arrays.asList("Inactivating Mutations", "Activating Mutations", "Fusions", "Inactivating", "Wildtype", "Amplification", "Fusions")); for (Gene gene : genes) { Set<Evidence> evidences = allGeneBasedEvidences.get(gene); Set<Alteration> VUSAlterations = AlterationUtils.findVUSFromEvidences(evidences); Map<Alteration, ArrayList<Alteration>> relevantAlterationsMapping = new HashMap<Alteration, ArrayList<Alteration>>(); Map<Alteration, String> oncogenicityMapping = new HashMap<Alteration, String>(); Map<Alteration, String> mutationEffectMapping = new HashMap<Alteration, String>(); Set<Alteration> allVariants = new HashSet<Alteration>(); Set<Alteration> allAlts = new HashSet<Alteration>(); for (Evidence evidenceItem : evidences) { allVariants = evidenceItem.getAlterations(); allAlts.addAll(allVariants); for (Alteration alterationItem : allVariants) { relevantAlterationsMapping.put(alterationItem, (ArrayList<Alteration>) AlterationUtils.getRelevantAlterations(gene, alterationItem.getAlteration(), null, null, null)); if (evidenceItem.getEvidenceType().toString().equals("ONCOGENIC")) { oncogenicityMapping.put(alterationItem, evidenceItem.getKnownEffect()); } if (evidenceItem.getEvidenceType().toString().equals("MUTATION_EFFECT")) { mutationEffectMapping.put(alterationItem, evidenceItem.getKnownEffect()); } } } for (Alteration alt : allAlts) { ArrayList<Alteration> relevantAlts = relevantAlterationsMapping.get(alt); for (Alteration relevantAlt : relevantAlts) { if (oncogenicityMapping.containsKey(alt) && oncogenicityMapping.containsKey(relevantAlt) && !oncogenicityMapping.get(alt).equals(oncogenicityMapping.get(relevantAlt)) || mutationEffectMapping.containsKey(alt) && mutationEffectMapping.containsKey(relevantAlt) && !mutationEffectMapping.get(alt).equals(mutationEffectMapping.get(relevantAlt))) { result1 += alt.toString() + "\n"; length1++; break; } } if (oncogenicityMapping.containsKey(alt) && oncogenicityMapping.get(alt).equals(Oncogenicity.UNKNOWN.getOncogenic()) && mutationEffectMapping.containsKey(alt) && mutationEffectMapping.get(alt).equals(MutationEffect.UNKNOWN.getMutation_effect())) { Integer relevantsSize = relevantAlts.size(); Integer relevantCount = 0; for (Alteration relevantAlt : relevantAlts) { relevantCount++; if (relevantCount == relevantsSize - 1 && oncogenicityMapping.containsKey(alt) && oncogenicityMapping.get(relevantAlt).equals(Oncogenicity.UNKNOWN.getOncogenic()) && mutationEffectMapping.containsKey(alt) && mutationEffectMapping.get(relevantAlt).equals(MutationEffect.UNKNOWN.getMutation_effect())) { result2 += relevantAlt.toString() + "\n"; length2++; } } } if (!oncogenicityMapping.containsKey(alt) && !mutationEffectMapping.containsKey(alt) && !VUSAlterations.contains(alt) && !specialAlterations.contains(alt.getAlteration())) { result3 += alt.toString() + "\n"; length3++; } } count++; System.out.println("Processing " + gene.getHugoSymbol() + " " + 100 * count / genes.size() + "% finished"); } String output = "Rule 1 check result: There are " + Integer.toString(length1) + " variants whose oncogenicty or mutation effect is different with its relevant variants.\n"; output += result1; output += "******************************************************************************************\n"; output += "Rule 2 check result: There are " + Integer.toString(length2) + " variants that has unknown oncogenic and unknown mutation effect, and same for all its relevant variants.\n"; output += result2; output += "******************************************************************************************\n"; output += "Rule 3 check result: There are " + Integer.toString(length3) + " variants that don't have oncogenic and mutation effect, and not in the VUS list.\n"; output += result3; try { File file = new File("validation-result.txt"); //if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fileWritter = new FileWriter(file.getName()); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(output); bufferWritter.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.yahoo.vespa.hosted.dockerapi; import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.Capability; import com.github.dockerjava.api.model.Ulimit; import java.net.Inet6Address; import java.net.InetAddress; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; class CreateContainerCommandImpl implements Docker.CreateContainerCommand { private final DockerClient docker; private final DockerImage dockerImage; private final ContainerResources containerResources; private final ContainerName containerName; private final String hostName; private final Map<String, String> labels = new HashMap<>(); private final List<String> environmentAssignments = new ArrayList<>(); private final List<String> volumeBindSpecs = new ArrayList<>(); private final List<Ulimit> ulimits = new ArrayList<>(); private final Set<Capability> addCapabilities = new HashSet<>(); private final Set<Capability> dropCapabilities = new HashSet<>(); private Optional<String> networkMode = Optional.empty(); private Optional<String> ipv4Address = Optional.empty(); private Optional<String> ipv6Address = Optional.empty(); private Optional<String[]> entrypoint = Optional.empty(); private boolean privileged = false; CreateContainerCommandImpl(DockerClient docker, DockerImage dockerImage, ContainerResources containerResources, ContainerName containerName, String hostName) { this.docker = docker; this.dockerImage = dockerImage; this.containerResources = containerResources; this.containerName = containerName; this.hostName = hostName; } @Override public Docker.CreateContainerCommand withLabel(String name, String value) { assert !name.contains("="); labels.put(name, value); return this; } public Docker.CreateContainerCommand withManagedBy(String manager) { return withLabel(DockerImpl.LABEL_NAME_MANAGEDBY, manager); } @Override public Docker.CreateContainerCommand withAddCapability(String capabilityName) { addCapabilities.add(Capability.valueOf(capabilityName)); return this; } @Override public Docker.CreateContainerCommand withDropCapability(String capabilityName) { dropCapabilities.add(Capability.valueOf(capabilityName)); return this; } @Override public Docker.CreateContainerCommand withPrivileged(boolean privileged) { this.privileged = privileged; return this; } @Override public Docker.CreateContainerCommand withUlimit(String name, int softLimit, int hardLimit) { ulimits.add(new Ulimit(name, softLimit, hardLimit)); return this; } @Override public Docker.CreateContainerCommand withEntrypoint(String... entrypoint) { if (entrypoint.length < 1) throw new IllegalArgumentException("Entrypoint must contain at least 1 element"); this.entrypoint = Optional.of(entrypoint); return this; } @Override public Docker.CreateContainerCommand withEnvironment(String name, String value) { assert name.indexOf('=') == -1; environmentAssignments.add(name + "=" + value); return this; } @Override public Docker.CreateContainerCommand withVolume(String path, String volumePath) { assert path.indexOf(':') == -1; volumeBindSpecs.add(path + ":" + volumePath); return this; } @Override public Docker.CreateContainerCommand withNetworkMode(String mode) { networkMode = Optional.of(mode); return this; } @Override public Docker.CreateContainerCommand withIpAddress(InetAddress address) { if (address instanceof Inet6Address) { ipv6Address = Optional.of(address.getHostAddress()); } else { ipv4Address = Optional.of(address.getHostAddress()); } return this; } @Override public void create() { try { createCreateContainerCmd().exec(); } catch (RuntimeException e) { throw new DockerException("Failed to create container " + containerName.asString(), e); } } private CreateContainerCmd createCreateContainerCmd() { List<Bind> volumeBinds = volumeBindSpecs.stream().map(Bind::parse).collect(Collectors.toList()); final CreateContainerCmd containerCmd = docker .createContainerCmd(dockerImage.asString()) .withCpuShares(containerResources.cpuShares) .withMemory(containerResources.memoryBytes) .withName(containerName.asString()) .withHostName(hostName) .withLabels(labels) .withEnv(environmentAssignments) .withBinds(volumeBinds) .withUlimits(ulimits) .withCapAdd(new ArrayList<>(addCapabilities)) .withCapDrop(new ArrayList<>(dropCapabilities)) .withPrivileged(privileged); networkMode .filter(mode -> ! mode.toLowerCase().equals("host")) .ifPresent(mode -> containerCmd.withMacAddress(generateMACAddress(hostName, ipv4Address, ipv6Address))); networkMode.ifPresent(containerCmd::withNetworkMode); ipv4Address.ifPresent(containerCmd::withIpv4Address); ipv6Address.ifPresent(containerCmd::withIpv6Address); entrypoint.ifPresent(containerCmd::withEntrypoint); return containerCmd; } /** Maps ("--env", {"A", "B", "C"}) to "--env A --env B --env C" */ private String toRepeatedOption(String option, List<String> optionValues) { return optionValues.stream() .map(optionValue -> option + " " + optionValue) .collect(Collectors.joining(" ")); } private String toOptionalOption(String option, Optional<String> value) { return value.map(o -> option + " " + o).orElse(""); } private String toFlagOption(String option, boolean value) { return value ? option : ""; } /** Make toString() print the equivalent arguments to 'docker run' */ @Override public String toString() { List<String> labelList = labels.entrySet().stream() .map(entry -> entry.getKey() + "=" + entry.getValue()).collect(Collectors.toList()); List<String> ulimitList = ulimits.stream() .map(ulimit -> ulimit.getName() + "=" + ulimit.getSoft() + ":" + ulimit.getHard()) .collect(Collectors.toList()); List<String> addCapabilitiesList = addCapabilities.stream().map(Enum<Capability>::toString).sorted().collect(Collectors.toList()); List<String> dropCapabilitiesList = dropCapabilities.stream().map(Enum<Capability>::toString).sorted().collect(Collectors.toList()); Optional<String> entrypointExecuteable = entrypoint.map(args -> args[0]); String entrypointArgs = entrypoint.map(Stream::of).orElseGet(Stream::empty) .skip(1) .collect(Collectors.joining(" ")); return String.join(" ", "--name " + containerName.asString(), "--hostname " + hostName, "--cpu-shares " + containerResources.cpuShares, "--memory " + containerResources.memoryBytes, toRepeatedOption("--label", labelList), toRepeatedOption("--ulimit", ulimitList), toRepeatedOption("--env", environmentAssignments), toRepeatedOption("--volume", volumeBindSpecs), toRepeatedOption("--cap-add", addCapabilitiesList), toRepeatedOption("--cap-drop", dropCapabilitiesList), toOptionalOption("--net", networkMode), toOptionalOption("--ip", ipv4Address), toOptionalOption("--ip6", ipv6Address), toOptionalOption("--entrypoint", entrypointExecuteable), toFlagOption("--privileged", privileged), dockerImage.asString(), entrypointArgs); } /** * Generates a pseudo-random MAC address based on the hostname, IPv4- and IPv6-address. */ static String generateMACAddress(String hostname, Optional<String> ipv4Address, Optional<String> ipv6Address) { final String seed = hostname + ipv4Address.orElse("") + ipv6Address.orElse(""); Random rand = getPRNG(seed); byte[] macAddr = new byte[6]; rand.nextBytes(macAddr); // Set second-last bit (locally administered MAC address), unset last bit (unicast) macAddr[0] = (byte) ((macAddr[0] | 2) & 254); return IntStream.range(0, macAddr.length) .mapToObj(i -> String.format("%02x", macAddr[i])) .collect(Collectors.joining(":")); } private static Random getPRNG(String seed) { try { SecureRandom rand = SecureRandom.getInstance("SHA1PRNG"); rand.setSeed(seed.getBytes()); return rand; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to get pseudo-random number generator", e); } } }
package com.alibaba.dubbo.governance.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.governance.service.RouteService; import com.alibaba.dubbo.governance.sync.util.Pair; import com.alibaba.dubbo.governance.sync.util.SyncUtils; import com.alibaba.dubbo.registry.common.domain.Route; /** * IbatisRouteService * * @author william.liangf */ public class RouteServiceImpl extends AbstractService implements RouteService { public void createRoute(Route route) { registryService.register(route.toUrl()); } public void updateRoute(Route route) { Long id = route.getId(); if(id == null) { throw new IllegalStateException("no route id"); } URL oldRoute = findRouteUrl(id); if(oldRoute == null) { throw new IllegalStateException("Route was changed!"); } registryService.unregister(oldRoute); registryService.register(route.toUrl()); } public void deleteRoute(Long id) { URL oldRoute = findRouteUrl(id); if(oldRoute == null) { throw new IllegalStateException("Route was changed!"); } registryService.unregister(oldRoute); } public void enableRoute(Long id) { if(id == null) { throw new IllegalStateException("no route id"); } URL oldRoute = findRouteUrl(id); if(oldRoute == null) { throw new IllegalStateException("Route was changed!"); } if(oldRoute.getParameter("enabled", true)) { return; } registryService.unregister(oldRoute); URL newRoute= oldRoute.addParameter("enabled", true); registryService.register(newRoute); } public void disableRoute(Long id) { if(id == null) { throw new IllegalStateException("no route id"); } URL oldRoute = findRouteUrl(id); if(oldRoute == null) { throw new IllegalStateException("Route was changed!"); } if(!oldRoute.getParameter("enabled", true)) { return; } URL newRoute = oldRoute.addParameter("enabled", false); registryService.unregister(oldRoute); registryService.register(newRoute); } public List<Route> findAll() { return SyncUtils.url2RouteList(findAllUrl()); } private Map<Long, URL> findAllUrl() { Map<String, String> filter = new HashMap<String, String>(); filter.put(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY); return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public Route findRoute(Long id) { return SyncUtils.url2Route(findRouteUrlPair(id)); } public Pair<Long, URL> findRouteUrlPair(Long id) { return SyncUtils.filterFromCategory(getRegistryCache(), Constants.ROUTERS_CATEGORY, id); } private URL findRouteUrl(Long id){ return findRoute(id).toUrl(); } private Map<Long, URL> findRouteUrl(String service, String address, boolean force) { Map<String, String> filter = new HashMap<String, String>(); filter.put(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY); if (service != null && service.length() > 0) { filter.put(SyncUtils.SERVICE_FILTER_KEY, service); } if (address != null && address.length() > 0) { filter.put(SyncUtils.ADDRESS_FILTER_KEY, address); } if (force) { filter.put("force", "true"); } return SyncUtils.filterFromCategory(getRegistryCache(), filter); } public List<Route> findByService(String serviceName) { return SyncUtils.url2RouteList(findRouteUrl(serviceName, null, false)); } public List<Route> findByAddress(String address) { return SyncUtils.url2RouteList(findRouteUrl(null, address, false)); } public List<Route> findByServiceAndAddress(String service, String address) { return SyncUtils.url2RouteList(findRouteUrl(service, address, false)); } public List<Route> findForceRouteByService(String service) { return SyncUtils.url2RouteList(findRouteUrl(service, null, true)); } public List<Route> findForceRouteByAddress(String address) { return SyncUtils.url2RouteList(findRouteUrl(null, address, true)); } public List<Route> findForceRouteByServiceAndAddress(String service, String address) { return SyncUtils.url2RouteList(findRouteUrl(service, address, true)); } public List<Route> findAllForceRoute() { return SyncUtils.url2RouteList(findRouteUrl(null, null, true)); } }
package se.l4.dust.core.internal.template.dom; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import se.l4.dust.api.TemplateException; import se.l4.dust.api.annotation.AfterRender; import se.l4.dust.api.annotation.PrepareRender; import se.l4.dust.api.annotation.Template; import se.l4.dust.api.annotation.TemplateParam; import se.l4.dust.api.conversion.TypeConverter; import se.l4.dust.api.template.RenderingContext; import se.l4.dust.api.template.TemplateCache; import se.l4.dust.api.template.dom.Content; import se.l4.dust.api.template.dom.DocType; import se.l4.dust.api.template.dom.Element; import se.l4.dust.api.template.dom.ParsedTemplate; import se.l4.dust.api.template.dom.WrappedElement; import se.l4.dust.api.template.spi.TemplateOutputStream; import se.l4.dust.core.internal.template.components.EmittableComponent; import com.google.inject.Binding; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Stage; import com.google.inject.TypeLiteral; /** * Component based on a class. * * @author Andreas Holstenson * */ public class ClassTemplateComponent extends EmittableComponent { private final TypeConverter converter; private final Class<?> type; private final Injector injector; private final TemplateCache cache; private final boolean development; private final MethodInvocation[] prepareRender; private final MethodInvocation[] setMethods; private final MethodInvocation[] afterRender; private final Provider<Object> instance; public ClassTemplateComponent( String name, Injector injector, TemplateCache cache, TypeConverter converter, Class<?> type) { this(name, injector.getInstance(Stage.class) == Stage.DEVELOPMENT, injector, cache, converter, type, null, null, null); } private ClassTemplateComponent( String name, boolean development, Injector injector, TemplateCache cache, TypeConverter converter, Class<?> type, MethodInvocation[] prepareRender, MethodInvocation[] setMethods, MethodInvocation[] afterRender) { super(name, type); this.development = development; instance = createInstance(development, injector, type); this.converter = converter; this.cache = cache; this.type = type; this.injector = injector; this.prepareRender = prepareRender == null && ! development ? createMethodInvocations(type) : prepareRender; this.setMethods = setMethods == null && ! development ? createSetMethodInvocations(type) : setMethods; this.afterRender = afterRender == null && ! development ? createAfterRenderInvocations(type) : afterRender; } /** * Create a provider for use either in production or development. The * development injector will always call {@link Injector#getInstance(Class)} * to make sure that any class changes are applied. * * @param development * @param injector * @param type * @return */ private static Provider<Object> createInstance(boolean development, final Injector injector, final Class<?> type) { if(development) { return new Provider<Object>() { @Override public Object get() { return injector.getInstance(type); } }; } else { return (Provider) injector.getProvider(type); } } @Override public Content copy() { return new ClassTemplateComponent(getName(), development, injector, cache, converter, type, prepareRender, setMethods, afterRender) .copyAttributes(this); } private MethodInvocation[] createMethodInvocations(Class<?> type) { List<MethodInvocation> invocations = new ArrayList<MethodInvocation>(); while(type != Object.class && type != null) { for(Method m : type.getDeclaredMethods()) { if(m.isAnnotationPresent(PrepareRender.class)) { invocations.add(new MethodInvocation(m)); } } type = type.getSuperclass(); } return invocations.toArray(new MethodInvocation[invocations.size()]); } private MethodInvocation[] createAfterRenderInvocations(Class<?> type) { List<MethodInvocation> invocations = new ArrayList<MethodInvocation>(); while(type != Object.class && type != null) { for(Method m : type.getDeclaredMethods()) { if(m.isAnnotationPresent(AfterRender.class)) { invocations.add(new MethodInvocation(m)); } } type = type.getSuperclass(); } return invocations.toArray(new MethodInvocation[invocations.size()]); } private MethodInvocation[] createSetMethodInvocations(Class<?> type) { List<MethodInvocation> invocations = new ArrayList<MethodInvocation>(); while(type != Object.class && type != null) { for(Method m : type.getDeclaredMethods()) { if(m.isAnnotationPresent(PrepareRender.class)) { // Skip rendering methods continue; } Annotation[][] annotations = m.getParameterAnnotations(); _annotations: for(int i=0, n=annotations.length; i<n; i++) { for(Annotation a : annotations[i]) { if(a instanceof TemplateParam) { invocations.add(new MethodInvocation(m)); break _annotations; } } } } type = type.getSuperclass(); } return invocations.toArray(new MethodInvocation[invocations.size()]); } @Override public void emit(Emitter emitter, RenderingContext ctx, TemplateOutputStream out) throws IOException { Object o = instance.get(); Object data = emitter.getObject(); Object root; // Run all set methods MethodInvocation[] setMethods = development ? createSetMethodInvocations(type) : this.setMethods; for(MethodInvocation m : setMethods) { if(m.valid()) { m.invoke(ctx, data, o); } } // Run all methods for prepare render MethodInvocation[] methods = development ? createMethodInvocations(type) : this.prepareRender; if(methods.length == 0) { // No processing needed root = o; } else { // Find the best method to invoke MethodInvocation bestMethod = null; if(methods.length == 1) { bestMethod = methods[0]; } else { int bestScore = 0; boolean hasExact = false; for(MethodInvocation i : methods) { int score = i.score(); if(score > bestScore || (! hasExact && score == i.maxScore())) { bestMethod = i; bestScore = score; hasExact = score == i.maxScore(); } } } // Actually invoke the method root = bestMethod.invoke(ctx, data, o); if(root == null) { root = o; } } if(root instanceof Element) { emitter.emit(out, (Element) root); } else { // Process the template of the component ParsedTemplate template = cache.getTemplate(ctx, root.getClass(), (Template) null); // Switch to new context Integer old = emitter.switchData(template.getRawId(), root); Content content = getRawContents()[0]; Element element = content instanceof Element ? (Element) content : (content instanceof WrappedElement ? ((WrappedElement) content).getElement() : null); Integer oldComponent = emitter.switchComponent(template.getRawId(), element); DocType docType = template.getDocType(); if(docType != null) { out.docType(docType.getName(), docType.getPublicId(), docType.getSystemId()); } Element templateRoot = template.getRoot(); emitter.emit(out, templateRoot); // Switch context back emitter.switchData(old); emitter.switchComponent(oldComponent); } // Run all methods for after render methods = development ? createAfterRenderInvocations(type) : this.afterRender; if(methods.length > 0) { // Find the best method to invoke for(MethodInvocation i : methods) { if(development && ! i.valid()) { throw new IllegalArgumentException("Invalid @" + AfterRender.class.getSimpleName() + ", can't invoke method:" + i.method); } i.invoke(ctx, data, o); } } } private class MethodInvocation { private final Method method; private final Argument[] arguments; public MethodInvocation(Method m) { this.method = m; Argument[] result = new Argument[m.getParameterTypes().length]; for(int i=0, n=result.length; i<n; i++) { result[i] = new Argument(m, i); } arguments = result; } /** * Score the invocation. * * @return */ public int score() { int score = 0; for(Argument arg : arguments) { if(arg.canBeInjected()) { score++; } } return score; } public int maxScore() { return arguments.length; } public boolean valid() { if(arguments.length == 0) return true; for(Argument arg : arguments) { if(! arg.canBeInjected()) { return false; } } return true; } public Object invoke(RenderingContext ctx, Object root, Object self) { Object[] data = null; try { data = new Object[arguments.length]; for(int i=0, n=arguments.length; i<n; i++) { Object value = arguments[i].getValue(ctx, root); value = converter.convert(value, arguments[i].typeClass); data[i] = value; } return method.invoke(self, data); } catch(InvocationTargetException e) { Throwable e2 = e.getCause(); if(e2 instanceof RuntimeException) { throw (RuntimeException) e2; } throw new TemplateException("Unable to invoke method " + method + "; " + e2.getMessage() + "\nArguments were: " + Arrays.toString(data), e2); } catch(Exception e) { throw new TemplateException("Unable to invoke method " + method + "; " + e.getMessage() + "\nArguments were: " + Arrays.toString(data), e); } } } private class Argument { private final Method method; private final Type type; private final Annotation[] annotations; private final String attribute; private final Class<?> typeClass; private final Binding binding; public Argument(Method m, int index) { method = m; annotations = m.getParameterAnnotations()[index]; type = m.getGenericParameterTypes()[index]; typeClass = m.getParameterTypes()[index]; attribute = findAttribute(m, annotations); binding = attribute == null ? findBinding() : null; } private Binding findBinding() { TypeLiteral literal = TypeLiteral.get(type); for(Binding b : (List<Binding>) injector.findBindingsByType(literal)) { Key key = b.getKey(); if(key.getAnnotation() != null) { for(Annotation a : annotations) { if(key.getAnnotation().equals(a)) { return b; } } } if(key.getAnnotation() == null) { return b; } } return null; } private String findAttribute(Method m, Annotation[] annotations) { for(Annotation a : annotations) { if(a instanceof TemplateParam) { return ((TemplateParam) a).value(); } } return null; } public boolean canBeInjected() { if(binding != null) { // Bindings can always be handled return true; } else if(attribute != null) { // If the attribute exists we can be injected return getAttributeValue(attribute) != null; } else { // Assume that we can be injected // FIXME: Actually check with the context return true; } } public Object getValue(RenderingContext ctx, Object root) { if(attribute != null) { Attribute attr = getAttribute(attribute); if(attr == null) { throw new TemplateException("Attribute '" +attribute+ "' is missing in template file for method " + method); } return attr.getValue(ctx, root); } else if(binding != null) { return binding.getProvider().get(); } else { return ctx.resolveObject(method, type, annotations, root); } } } }
package org.sbolstandard.core2; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sbolstandard.core2.ComponentInstance.AccessType; import org.sbolstandard.core2.SequenceConstraint.RestrictionType; import static org.sbolstandard.core2.URIcompliance.*; /** * @author Zhen Zhang * @author Tramy Nguyen * @author Nicholas Roehner * @author Matthew Pocock * @author Goksel Misirli * @author Chris Myers * @version 2.0-beta */ public class ComponentDefinition extends TopLevel { private Set<URI> types; private Set<URI> roles; private Set<URI> sequences; private HashMap<URI, Component> components; private HashMap<URI, SequenceAnnotation> sequenceAnnotations; private HashMap<URI, SequenceConstraint> sequenceConstraints; public static final URI DNA = URI.create("http://www.biopax.org/release/biopax-level3.owl#DnaRegion"); public static final URI RNA = URI.create("ttp://www.biopax.org/release/biopax-level3.owl#RnaRegion"); public static final URI PROTEIN = URI.create("http://www.biopax.org/release/biopax-level3.owl#Protein"); public static final URI SMALL_MOLECULE = URI.create("http://www.biopax.org/release/biopax-level3.owl#SmallMolecule"); ComponentDefinition(URI identity, Set<URI> types) { super(identity); this.types = new HashSet<>(); setTypes(types); this.roles = new HashSet<>(); this.sequences = new HashSet<>(); this.components = new HashMap<>(); this.sequenceAnnotations = new HashMap<>(); this.sequenceConstraints = new HashMap<>(); } private ComponentDefinition(ComponentDefinition componentDefinition) { super(componentDefinition); Set<URI> types = new HashSet<>(); for (URI type : componentDefinition.getTypes()) { types.add(URI.create(type.toString())); } setTypes(types); if (!componentDefinition.getRoles().isEmpty()) { Set<URI> roles = new HashSet<>(); for (URI role : componentDefinition.getRoles()) { roles.add(URI.create(role.toString())); } this.setRoles(roles); } if (!componentDefinition.getComponents().isEmpty()) { List<Component> subComponents = new ArrayList<>(); for (Component subComponent : componentDefinition.getComponents()) { subComponents.add(subComponent.deepCopy()); } this.setComponents(subComponents); } if (!componentDefinition.getSequenceConstraints().isEmpty()) { List<SequenceConstraint> sequenceConstraints = new ArrayList<>(); for (SequenceConstraint sequenceConstraint : componentDefinition.getSequenceConstraints()) { sequenceConstraints.add(sequenceConstraint.deepCopy()); } this.setSequenceConstraints(sequenceConstraints); } if (!componentDefinition.getSequenceAnnotations().isEmpty()) { List<SequenceAnnotation> sequenceAnnotations = new ArrayList<>(); for (SequenceAnnotation sequenceAnnotation : componentDefinition.getSequenceAnnotations()) { sequenceAnnotations.add(sequenceAnnotation.deepCopy()); } this.setSequenceAnnotations(sequenceAnnotations); } this.setSequenceURIs(componentDefinition.getSequenceURIs()); } /** * Adds the specified element to the set <code>type</code> if it is not already present. * @return <code>true</code> if this set did not already contain the specified element. */ public boolean addType(URI typeURI) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return types.add(typeURI); } /** * Removes the specified element from the set <code>type</code> if it is present. * @return <code>true</code> if this set contained the specified element */ public boolean removeType(URI typeURI) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); if (types.size()==1 && types.contains(typeURI)) { throw new IllegalArgumentException("Component definition " + this.getIdentity() + " must have at least one type."); } return types.remove(typeURI); } /** * Sets the field variable <code>type</code> to the specified element. */ public void setTypes(Set<URI> types) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); if (types==null || types.size()==0) { throw new IllegalArgumentException("Component definition " + this.getIdentity() + " must have at least one type."); } clearTypes(); for (URI type : types) { addType(type); } } /** * Returns the field variable <code>type</code>. * @return the set of URIs for <code>type</code>. */ public Set<URI> getTypes() { Set<URI> result = new HashSet<>(); result.addAll(types); return result; } /** * Returns true if the set <code>type</code> contains the specified element. * @return <code>true</code> if this set contains the specified element. */ public boolean containsType(URI typeURI) { return types.contains(typeURI); } /** * Removes all entries of the list of <code>type</code> instances owned by this instance. * The list will be empty after this call returns. */ void clearTypes() { types.clear(); } /** * Adds the specified element to the set <code>roles</code> if it is not already present. * @return <code>true</code> if this set did not already contain the specified element. */ public boolean addRole(URI roleURI) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return roles.add(roleURI); } /** * Removes the specified element from the set <code>roles</code> if it is present. * @return <code>true</code> if this set contained the specified element */ public boolean removeRole(URI roleURI) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return roles.remove(roleURI); } /** * Sets the field variable <code>roles</code> to the specified element. */ public void setRoles(Set<URI> roles) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); clearRoles(); if (roles==null) return; for (URI role : roles) { addRole(role); } } /** * Returns the field variable <code>roles</code>. * @return the set of URIs for <code>roles</code>. */ public Set<URI> getRoles() { Set<URI> result = new HashSet<>(); result.addAll(roles); return result; } /** * Returns true if the set <code>roles</code> contains the specified element. * @return <code>true</code> if this set contains the specified element. */ public boolean containsRole(URI rolesURI) { return roles.contains(rolesURI); } /** * Removes all entries of the list of <code>roles</code> instances owned by this instance. * The list will be empty after this call returns. */ public void clearRoles() { if (sbolDocument!=null) sbolDocument.checkReadOnly(); roles.clear(); } public boolean addSequence(Sequence sequence) { return this.addSequenceURI(sequence.identity); } public boolean addSequenceURI(URI sequenceUri) { return sequences.add(sequenceUri); } public void addSequence(String sequence,String version) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); URI sequenceURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(), TopLevel.sequence, sequence, version); addSequenceURI(sequenceURI); } /** * Returns the URIs of the referenced {@link Sequence} instance. * @return the URIs of the referenced {@link Sequence} instance. */ public Set<URI> getSequenceURIs() { return sequences; } public Set<Sequence> getSequences() { if (sbolDocument==null) return null; Set<Sequence> resolved = new HashSet<>(); for(URI su : sequences) { Sequence seq = sbolDocument.getSequence(su); if(seq != null) { resolved.add(seq); } } return resolved; } public void setSequenceURIs(Set<URI> seqURIs) { sequences.clear(); sequences.addAll(seqURIs); } public void clearSequences() { sequences.clear(); } public boolean containsSequence(Sequence sequence) { return containsSequenceURI(sequence.getIdentity()); } public boolean containsSequenceURI(URI sequenceUri) { return sequences.contains(sequenceUri); } // /** // * Test if any {@link SequenceAnnotation} instance exists. // * @return <code>true</code> if at least one such instance exists. // */ // public boolean isSetSequenceAnnotations() { // if (sequenceAnnotations.isEmpty()) // return false; // else // return true; /** * Calls the SequenceAnnotation constructor to create a new instance using the specified parameters, * then adds to the list of SequenceAnnotation instances owned by this instance. * @return the created SequenceAnnotation instance. */ SequenceAnnotation createSequenceAnnotation(URI identity, Location location) { SequenceAnnotation sequenceAnnotation = new SequenceAnnotation(identity, location); addSequenceAnnotation(sequenceAnnotation); return sequenceAnnotation; } public SequenceAnnotation createSequenceAnnotation(String displayId, Location location) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); String URIprefix = this.getPersistentIdentity().toString(); String version = this.getVersion(); URI newSequenceAnnotationURI = createCompliantURI(URIprefix, displayId, version); if (!isChildURIcompliant(this.getIdentity(), newSequenceAnnotationURI)) throw new IllegalArgumentException("Child uri `" + newSequenceAnnotationURI + "'is not compliant in parent `" + this.getIdentity() + "' for " + URIprefix + " " + displayId + " " + version); SequenceAnnotation sa = createSequenceAnnotation(newSequenceAnnotationURI, location); sa.setPersistentIdentity(createCompliantURI(URIprefix, displayId, "")); sa.setDisplayId(displayId); sa.setVersion(version); return sa; } public SequenceAnnotation createSequenceAnnotation(String displayId) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return createSequenceAnnotation(displayId,(OrientationType)null); } public SequenceAnnotation createSequenceAnnotation(String displayId,OrientationType orientation) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); String URIprefix = this.getPersistentIdentity().toString()+"/"+displayId; String version = this.getVersion(); GenericLocation location = new GenericLocation(createCompliantURI(URIprefix,"generic",version)); if (orientation!=null) location.setOrientation(orientation); location.setPersistentIdentity(URI.create(URIprefix+"/generic")); location.setDisplayId("generic"); location.setVersion(this.getVersion()); return createSequenceAnnotation(displayId, location); } public SequenceAnnotation createSequenceAnnotation(String displayId, int at) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return createSequenceAnnotation(displayId,at,null); } public SequenceAnnotation createSequenceAnnotation(String displayId, int at,OrientationType orientation) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); String URIprefix = this.getPersistentIdentity().toString()+"/"+displayId; String version = this.getVersion(); Cut location = new Cut(createCompliantURI(URIprefix,"cut",version),at); if (orientation!=null) location.setOrientation(orientation); location.setPersistentIdentity(URI.create(URIprefix+"/cut")); location.setDisplayId("cut"); location.setVersion(this.getVersion()); return createSequenceAnnotation(displayId, location); } public SequenceAnnotation createSequenceAnnotation(String displayId, int start, int end) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return createSequenceAnnotation(displayId,start,end,null); } public SequenceAnnotation createSequenceAnnotation(String displayId, int start, int end,OrientationType orientation) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); String URIprefix = this.getPersistentIdentity().toString()+"/"+displayId; String version = this.getVersion(); Range location = new Range(createCompliantURI(URIprefix,"range",version),start,end); if (orientation!=null) location.setOrientation(orientation); location.setPersistentIdentity(URI.create(URIprefix+"/range")); location.setDisplayId("range"); location.setVersion(this.getVersion()); return createSequenceAnnotation(displayId, location); } /** * Adds the specified instance to the list of sequenceAnnotations. */ void addSequenceAnnotation(SequenceAnnotation sequenceAnnotation) { addChildSafely(sequenceAnnotation, sequenceAnnotations, "sequenceAnnotation", components, sequenceConstraints); sequenceAnnotation.setSBOLDocument(this.sbolDocument); sequenceAnnotation.setComponentDefinition(this); } /** * Removes the sequence annotation from the list of sequence annotations, if present. * @param sequenceAnnotation object to be removed. * @return true if the sequenceAnnotation is present and removed. */ public boolean removeSequenceAnnotation(SequenceAnnotation sequenceAnnotation) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return removeChildSafely(sequenceAnnotation, sequenceAnnotations); } /** * Returns the instance matching the specified URI from the list of structuralAnnotations if present. * @return the matching instance if present, or <code>null</code> if not present. */ public SequenceAnnotation getSequenceAnnotation(URI sequenceAnnotationURI) { return sequenceAnnotations.get(sequenceAnnotationURI); } /** * Returns the list of structuralAnnotation instances owned by this instance. * @return the list of structuralAnnotation instances owned by this instance. */ public Set<SequenceAnnotation> getSequenceAnnotations() { // return (List<SequenceAnnotation>) structuralAnnotations.values(); Set<SequenceAnnotation> sequenceAnnotations = new HashSet<>(); sequenceAnnotations.addAll(this.sequenceAnnotations.values()); return sequenceAnnotations; } /** * Removes all entries of the list of sequence annotations owned by this instance. The list will be empty after this call returns. */ public void clearSequenceAnnotations() { if (sbolDocument!=null) sbolDocument.checkReadOnly(); Object[] valueSetArray = sequenceAnnotations.values().toArray(); for (Object sequenceAnnotation : valueSetArray) { removeSequenceAnnotation((SequenceAnnotation)sequenceAnnotation); } } /** * Clears the existing list of structuralAnnotation instances, then appends all of the elements in the specified collection to the end of this list. */ void setSequenceAnnotations( List<SequenceAnnotation> sequenceAnnotations) { clearSequenceAnnotations(); for (SequenceAnnotation sequenceAnnotation : sequenceAnnotations) { addSequenceAnnotation(sequenceAnnotation); } } // /** // * Test if the optional field variable <code>structuralInstantiations</code> is set. // * @return <code>true</code> if the field variable is not an empty list // */ // public boolean isSetSubComponents() { // if (subComponents.isEmpty()) // return false; // else // return true; /** * Calls the StructuralInstantiation constructor to create a new instance using the specified parameters, * then adds to the list of StructuralInstantiation instances owned by this instance. * @return the created StructuralInstantiation instance. */ Component createComponent(URI identity, AccessType access, URI componentDefinitionURI) { Component subComponent = new Component(identity, access, componentDefinitionURI); addComponent(subComponent); return subComponent; } public Component createComponent(String displayId, AccessType access, String componentDefinition, String version) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); URI componentDefinitionURI = URIcompliance.createCompliantURI(sbolDocument.getDefaultURIprefix(), TopLevel.componentDefinition, componentDefinition, version); return createComponent(displayId,access,componentDefinitionURI); } public Component createComponent(String displayId, AccessType access, URI componentDefinitionURI) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); if (sbolDocument != null && sbolDocument.isComplete()) { if (sbolDocument.getComponentDefinition(componentDefinitionURI)==null) { throw new IllegalArgumentException("Component definition '" + componentDefinitionURI + "' does not exist."); } } String URIprefix = this.getPersistentIdentity().toString(); String version = this.getVersion(); Component c = createComponent(createCompliantURI(URIprefix, displayId, version), access, componentDefinitionURI); c.setPersistentIdentity(createCompliantURI(URIprefix, displayId, "")); c.setDisplayId(displayId); c.setVersion(version); return c; } /** * Adds the specified instance to the list of components. */ void addComponent(Component component) { addChildSafely(component, components, "component", sequenceAnnotations, sequenceConstraints); component.setSBOLDocument(this.sbolDocument); } /** * Removes the component from the list of components, if present. * @param component object to be removed. * @return true if the component is present and removed. */ public boolean removeComponent(Component component) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return removeChildSafely(component, components); } /** * Returns the instance matching the specified URI from the list of structuralInstantiations if present. * @return the matching instance if present, or <code>null</code> if not present. */ public Component getComponent(URI subComponentURI) { return components.get(subComponentURI); } /** * Returns the list of {@link Component} instances owned by this instance. * @return the list of {@link Component} instances owned by this instance. */ public Set<Component> getComponents() { Set<Component> structuralInstantiations = new HashSet<>(); structuralInstantiations.addAll(this.components.values()); return structuralInstantiations; } /** * Removes all entries of the list of components owned by this instance. The list will be empty after this call returns. */ public void clearComponents() { if (sbolDocument!=null) sbolDocument.checkReadOnly(); Object[] valueSetArray = components.values().toArray(); for (Object component : valueSetArray) { removeComponent((Component)component); } } /** * Clears the existing list of structuralInstantiation instances, then appends all of the elements in the specified collection to the end of this list. */ void setComponents(List<Component> components) { clearComponents(); for (Component component : components) { addComponent(component); } } // /** // * Test if the optional field variable <code>sequenceConstraints</code> is set. // * @return <code>true</code> if the field variable is not an empty list // */ // public boolean isSetSequenceConstraints() { // if (sequenceConstraints.isEmpty()) // return false; // else // return true; /** * Calls the StructuralConstraint constructor to create a new instance using the specified parameters, * then adds to the list of StructuralConstraint instances owned by this instance. * @return the created StructuralConstraint instance. */ SequenceConstraint createSequenceConstraint(URI identity, RestrictionType restriction, URI subject, URI object) { SequenceConstraint sequenceConstraint = new SequenceConstraint(identity, restriction, subject, object); addSequenceConstraint(sequenceConstraint); return sequenceConstraint; } public SequenceConstraint createSequenceConstraint(String displayId, RestrictionType restriction, String subject, String object) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); URI subjectURI = URIcompliance.createCompliantURI(this.getPersistentIdentity().toString(), subject, this.getVersion()); URI objectURI = URIcompliance.createCompliantURI(this.getPersistentIdentity().toString(), object, this.getVersion()); return createSequenceConstraint(displayId,restriction,subjectURI,objectURI); } public SequenceConstraint createSequenceConstraint(String displayId, RestrictionType restriction, URI subject, URI object) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); String URIprefix = this.getPersistentIdentity().toString(); String version = this.getVersion(); SequenceConstraint sc = createSequenceConstraint(createCompliantURI(URIprefix, displayId, version), restriction, subject, object); sc.setPersistentIdentity(createCompliantURI(URIprefix, displayId, "")); sc.setDisplayId(displayId); sc.setVersion(version); return sc; } /** * Adds the specified instance to the list of sequenceConstraints. */ void addSequenceConstraint(SequenceConstraint sequenceConstraint) { sequenceConstraint.setSBOLDocument(this.sbolDocument); sequenceConstraint.setComponentDefinition(this); if (sbolDocument != null && sbolDocument.isComplete()) { if (sequenceConstraint.getSubject()==null) { throw new IllegalArgumentException("Component '" + sequenceConstraint.getSubjectURI() + "' does not exist."); } } if (sbolDocument != null && sbolDocument.isComplete()) { if (sequenceConstraint.getObject()==null) { throw new IllegalArgumentException("Component '" + sequenceConstraint.getObjectURI() + "' does not exist."); } } addChildSafely(sequenceConstraint, sequenceConstraints, "sequenceConstraint", components, sequenceAnnotations); } /** * Removes the sequence constraint from the list of sequence constraints, if present. * @param sequenceConstraint object to be removed. * @return true if the sequenceConstraint is present and removed. */ public boolean removeSequenceConstraint(SequenceConstraint sequenceConstraint) { if (sbolDocument!=null) sbolDocument.checkReadOnly(); return removeChildSafely(sequenceConstraint,sequenceConstraints); } /** * Returns the instance matching the specified URI from the list of sequence constraints if present. * @return the matching instance if present, or <code>null</code> if not present. */ public SequenceConstraint getSequenceConstraint(URI sequenceConstraintURI) { return sequenceConstraints.get(sequenceConstraintURI); } /** * Returns the list of {@link SequenceConstraint} instances owned by this instance. * @return the list of {@link SequenceConstraint} instances owned by this instance. */ public Set<SequenceConstraint> getSequenceConstraints() { Set<SequenceConstraint> sequenceConstraints = new HashSet<>(); sequenceConstraints.addAll(this.sequenceConstraints.values()); return sequenceConstraints; } /** * Removes all entries of the list of sequence constraints owned by this instance. The list will be empty after this call returns. */ public void clearSequenceConstraints() { if (sbolDocument!=null) sbolDocument.checkReadOnly(); Object[] valueSetArray = sequenceConstraints.values().toArray(); for (Object sequenceConstraint : valueSetArray) { removeSequenceConstraint((SequenceConstraint)sequenceConstraint); } } /** * Clears the existing list of structuralConstraint instances, then appends all of the elements in the specified collection to the end of this list. */ void setSequenceConstraints( List<SequenceConstraint> sequenceConstraints) { clearSequenceConstraints(); for (SequenceConstraint sequenceConstraint : sequenceConstraints) { addSequenceConstraint(sequenceConstraint); } } /* (non-Javadoc) * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateCompliantURI(java.lang.String, java.lang.String, java.lang.String) */ protected boolean checkDescendantsURIcompliance() { // codereview: this method is spagetti. if (!isURIcompliant(this.getIdentity(), 0)) { // ComponentDefinition to be copied has non-compliant URI. return false; } boolean allDescendantsCompliant = true; if (!this.getSequenceConstraints().isEmpty()) { for (SequenceConstraint sequenceConstraint : this.getSequenceConstraints()) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(this.getIdentity(), sequenceConstraint.getIdentity()); // SequenceConstraint does not have any child classes. No need to check further. if (!allDescendantsCompliant) { // Current sequence constraint has non-compliant URI. return allDescendantsCompliant; } } } if (!this.getComponents().isEmpty()) { for (Component component : this.getComponents()) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(this.getIdentity(), component.getIdentity()); if (!allDescendantsCompliant) { // Current component has non-compliant URI. return allDescendantsCompliant; } if (!component.getMapsTos().isEmpty()) { // Check compliance of Component's children for (MapsTo mapsTo : component.getMapsTos()) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(component.getIdentity(), mapsTo.getIdentity()); if (!allDescendantsCompliant) { // Current mapsTo has non-compliant URI. return allDescendantsCompliant; } } } } } if (!this.getSequenceAnnotations().isEmpty()) { for (SequenceAnnotation sequenceAnnotation : this.getSequenceAnnotations()) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(this.getIdentity(), sequenceAnnotation.getIdentity()); if (!allDescendantsCompliant) { // Current sequence annotation has non-compliant URI. return allDescendantsCompliant; } Location location = sequenceAnnotation.getLocation(); if (location instanceof Range) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(sequenceAnnotation.getIdentity(), location.getIdentity()); if (!allDescendantsCompliant) { // Current range has non-compliant URI. return allDescendantsCompliant; } } if (location instanceof Cut) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(sequenceAnnotation.getIdentity(), location.getIdentity()); if (!allDescendantsCompliant) { // Current cut has non-compliant URI. return allDescendantsCompliant; } } if (location instanceof GenericLocation) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(sequenceAnnotation.getIdentity(), location.getIdentity()); if (!allDescendantsCompliant) { // Current generic location has non-compliant URI. return allDescendantsCompliant; } } if (location instanceof MultiRange) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(sequenceAnnotation.getIdentity(), location.getIdentity()); if (!allDescendantsCompliant) { // Current generic location has non-compliant URI. return allDescendantsCompliant; } if (!((MultiRange) location).getRanges().isEmpty()) { for (Range range : ((MultiRange) location).getRanges()) { allDescendantsCompliant = allDescendantsCompliant && isChildURIcompliant(location.getIdentity(), range.getIdentity()); if (!allDescendantsCompliant) { // Current location has non-compliant URI. return allDescendantsCompliant; } } } } } } // All descendants of this ComponentDefinition object have compliant URIs. return allDescendantsCompliant; } protected boolean isComplete() { if (sbolDocument==null) return false; if (sequences.isEmpty()) { return false; } for (Component component : getComponents()) { if (component.getDefinition()==null) return false; } return true; } /** * Provide a deep copy of this object. */ protected ComponentDefinition deepCopy() { return new ComponentDefinition(this); } /* (non-Javadoc) * @see org.sbolstandard.core2.abstract_classes.TopLevel#copy(java.lang.String, java.lang.String, java.lang.String) */ ComponentDefinition copy(String URIprefix, String displayId, String version) { if (this.checkDescendantsURIcompliance() && isURIprefixCompliant(URIprefix) && isDisplayIdCompliant(displayId) && isVersionCompliant(version)) { ComponentDefinition cloned = this.deepCopy(); cloned.setWasDerivedFrom(this.getIdentity()); cloned.setPersistentIdentity(URI.create(URIprefix + '/' + displayId)); cloned.setDisplayId(displayId); cloned.setVersion(version); URI newIdentity = URI.create(URIprefix + '/' + displayId + '/' + version); cloned.setIdentity(newIdentity); // Update all children's URIs if (!cloned.getSequenceConstraints().isEmpty()) { for (SequenceConstraint sequenceConstraint : cloned.getSequenceConstraints()) { sequenceConstraint.updateCompliantURI(URIprefix, displayId, version); } } if (!cloned.getSequenceAnnotations().isEmpty()) { for (SequenceAnnotation SequenceAnnotation : cloned.getSequenceAnnotations()) { SequenceAnnotation.updateCompliantURI(URIprefix, displayId, version); } } if (!cloned.getComponents().isEmpty()) { for (Component component : cloned.getComponents()) { component.updateCompliantURI(URIprefix, displayId, version); } } return cloned; } else { return null; } } // /** // * Get a deep copy of the object first, and set its major version to the specified value, and minor version to "0". // * @param newVersion // * @return the copied {@link ComponentDefinition} instance with the specified major version. // */ // public ComponentDefinition newVersion(String newVersion) { // ComponentDefinition cloned = (ComponentDefinition) super.newVersion(newVersion); // cloned.updateVersion(newVersion); // return cloned; // /* (non-Javadoc) // * @see org.sbolstandard.core2.abstract_classes.TopLevel#updateVersion(java.lang.String) // */ // protected void updateVersion(String newVersion) { // super.updateVersion(newVersion); // if (isTopLevelURIcompliant(this.getIdentity())) { // // TODO Change all of its children's versions in their URIs. @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((roles == null) ? 0 : roles.hashCode()); result = prime * result + ((sequence == null) ? 0 : sequence.hashCode()); result = prime * result + ((sequenceAnnotations == null) ? 0 : sequenceAnnotations.hashCode()); result = prime * result + ((sequenceConstraints == null) ? 0 : sequenceConstraints.hashCode()); result = prime * result + ((components == null) ? 0 : components.hashCode()); result = prime * result + ((types == null) ? 0 : types.hashCode()); return result; } /* (non-Javadoc) * @see org.sbolstandard.core2.abstract_classes.Documented#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; ComponentDefinition other = (ComponentDefinition) obj; if (roles == null) { if (other.roles != null) return false; } else if (!roles.equals(other.roles)) return false; if (sequence == null) { if (other.sequence != null) return false; } else if (!sequence.equals(other.sequence)) return false; if (sequenceAnnotations == null) { if (other.sequenceAnnotations != null) return false; } else if (!sequenceAnnotations.equals(other.sequenceAnnotations)) return false; if (sequenceConstraints == null) { if (other.sequenceConstraints != null) return false; } else if (!sequenceConstraints.equals(other.sequenceConstraints)) return false; if (components == null) { if (other.components != null) return false; } else if (!components.equals(other.components)) return false; if (types == null) { if (other.types != null) return false; } else if (!types.equals(other.types)) return false; return true; } }
package org.easyframework.report.view; import org.easyframework.report.viewmodel.HtmlCheckBox; import org.easyframework.report.viewmodel.HtmlCheckBoxList; import org.easyframework.report.viewmodel.HtmlComboBox; import org.easyframework.report.viewmodel.HtmlDateBox; import org.easyframework.report.viewmodel.HtmlSelectOption; import org.easyframework.report.viewmodel.HtmlTextBox; /** * Bootstrapper * */ public class BootstrapQueryFormView extends AbstractQueryParamFormView implements QueryParamFormView { @Override protected String getDateBoxText(HtmlDateBox dateBox) { StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label>%s:</label>", dateBox.getText())); htmlText.append("<label class=\"input\">"); htmlText.append("<i class=\"icon-append fa fa-calendar\"></i> "); htmlText.append(String.format("<input class=\"hasDatepicker\" type=\"text\" id=\"%s\" name=\"%s\" value=\"%s\" readonly />", dateBox.getName(), dateBox.getName(), dateBox.getValue())); htmlText.append("</label>"); htmlText.append("</div>"); return htmlText.toString(); } @Override protected String getTexBoxText(HtmlTextBox textBox) { StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label>%s:</label>", textBox.getText())); htmlText.append("<label class=\"input\">"); htmlText.append(String.format("<input type=\"text\" name=\"%s\" value=\"%s\" placeholder=\"%s\"/>", textBox.getName(), textBox.getValue(), textBox.getDefaultText())); htmlText.append("</label>"); htmlText.append("</div>"); return htmlText.toString(); } @Override protected String getCheckBoxText(HtmlCheckBox checkBox) { String checked = checkBox.isChecked() ? "" : "checked=\"checked\""; StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label class=\"checkbox\">%s", checkBox.getText())); htmlText.append(String.format("<input class=\"checkbox-item\" type=\"checkbox\" name=\"%s\" value=\"%s\" %s />", checkBox.getName(), checkBox.getValue(), checked)); htmlText.append("<i></i></label>"); htmlText.append("</div>"); return htmlText.toString(); } @Override protected String getComboBoxText(HtmlComboBox comboBox) { if (comboBox.isAutoComplete()) { return this.getAutoCompleteComboBoxText(comboBox); } String multiple = comboBox.isMultipled() ? "multiple" : ""; StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label>%s:</label>", comboBox.getText())); htmlText.append(String.format("<select class=\"form-control input-sm\" id=\"%1$s\" name=\"%1$s\" %2$s>", comboBox.getName(), multiple)); for (HtmlSelectOption option : comboBox.getValue()) { String selected = option.isSelected() ? "selected=\"selected\"" : ""; htmlText.append(String.format("<option value=\"%s\" %s>%s</option>", option.getValue(), selected, option.getText())); } htmlText.append("</select>"); htmlText.append("</div> "); return htmlText.toString(); } @Override protected String getCheckboxListText(HtmlCheckBoxList checkBoxList) { boolean isCheckedAll = true; StringBuilder htmlText = new StringBuilder(""); for (HtmlCheckBox checkBox : checkBoxList.getValue()) { if (!checkBox.isChecked()) isCheckedAll = false; String checked = checkBox.isChecked() ? "checked=\"checked\"" : ""; htmlText.append(String.format("<label class=\"checkbox\">%s", checkBox.getText())); htmlText.append(String.format("<input class=\"checkbox-item\" type=\"checkbox\" name=\"%s\" value=\"%s\" %s />", checkBoxList.getName(), checkBox.getName(), checked)); htmlText.append("<i></i></label>"); } htmlText.append("<label class=\"checkbox\"> "); htmlText.append(String.format("<input type=\"checkbox\" name=\"checkAllStatColumn\" id=\"checkAllStatColumn\" %s /><i></i></label>", isCheckedAll ? "checked=\"checked\"" : "")); return htmlText.toString(); } private String getAutoCompleteComboBoxText(HtmlComboBox comboBox) { // option1000jquery select2 // bootstrap // jquery select2 option if (comboBox.getValue().size() <= 1000) { return this.getSelect2AutoCompleteComboBoxText(comboBox); } StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label>%s:</label>", comboBox.getText())); htmlText.append("<label class=\"input\">"); htmlText.append(String.format("<input type=\"text\" list=\"%1$s\" name=\"%1$s\" value=\"%2$s\">", comboBox.getName(), comboBox.getDefaultValue())); htmlText.append(String.format("<datalist id=\"%1$s\">", comboBox.getName())); for (HtmlSelectOption option : comboBox.getValue()) { htmlText.append(String.format("<option value=\"%s\">%s</option>", option.getValue(), option.getText())); } htmlText.append("</datalist>"); htmlText.append("</label>"); htmlText.append("</div> "); return htmlText.toString(); } private String getSelect2AutoCompleteComboBoxText(HtmlComboBox comboBox) { StringBuilder htmlText = new StringBuilder(""); htmlText.append("<div class=\"form-group\">"); htmlText.append(String.format("<label>%s:</label>", comboBox.getText())); htmlText.append(String.format("<select class=\"select2AutoComplete\" id=\"%1$s\" name=\"%1$s\">", comboBox.getName())); for (HtmlSelectOption option : comboBox.getValue()) { String selected = option.isSelected() ? "selected=\"selected\"" : ""; htmlText.append(String.format("<option value=\"%s\" %s>%s</option>", option.getValue(), selected, option.getText())); } htmlText.append("</select>"); htmlText.append("</div> "); return htmlText.toString(); } }
package de.otto.edison.mongo.configuration; import com.mongodb.client.MongoDatabase; import de.otto.edison.jobs.repository.JobMetaRepository; import de.otto.edison.jobs.repository.JobRepository; import de.otto.edison.mongo.jobs.MongoJobMetaRepository; import de.otto.edison.mongo.jobs.MongoJobRepository; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static org.slf4j.LoggerFactory.getLogger; @Configuration @ConditionalOnClass(name = "de.otto.edison.jobs.configuration.JobsConfiguration") public class MongoJobsConfiguration { private static final Logger LOG = getLogger(MongoJobsConfiguration.class); @Bean public JobRepository jobRepository(final MongoDatabase mongoDatabase, final @Value("${edison.jobs.collection.jobinfo:jobinfo}") String collectionName) { LOG.info("==============================="); LOG.info("Using MongoJobRepository with {} MongoDatabase impl.", mongoDatabase.getClass().getSimpleName()); LOG.info("==============================="); return new MongoJobRepository(mongoDatabase, collectionName); } @Bean public JobMetaRepository jobMetaRepository(final MongoDatabase mongoDatabase, final @Value("${edison.jobs.collection.jobmeta:jobmeta}") String collectionName) { LOG.info("==============================="); LOG.info("Using MongoJobMetaRepository with {} MongoDatabase impl.", mongoDatabase.getClass().getSimpleName()); LOG.info("==============================="); return new MongoJobMetaRepository(mongoDatabase, collectionName); } }
package org.exist.indexing.spatial; import java.io.IOException; import java.io.StringReader; import java.sql.Connection; import java.sql.SQLException; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.TransformerException; import org.apache.log4j.Logger; import org.exist.collections.Collection; import org.exist.dom.AttrImpl; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.ElementImpl; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.StoredNode; import org.exist.dom.TextImpl; import org.exist.indexing.AbstractStreamListener; import org.exist.indexing.Index; import org.exist.indexing.IndexController; import org.exist.indexing.IndexWorker; import org.exist.indexing.MatchListener; import org.exist.indexing.StreamListener; import org.exist.numbering.NodeId; import org.exist.storage.DBBroker; import org.exist.storage.IndexSpec; import org.exist.storage.NodePath; import org.exist.storage.txn.Txn; import org.exist.util.Base64Decoder; import org.exist.util.Base64Encoder; import org.exist.util.DatabaseConfigurationException; import org.exist.util.Occurrences; import org.exist.util.serializer.Receiver; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.ValueSequence; import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer; import org.geotools.gml.GMLFilterDocument; import org.geotools.gml.GMLFilterGeometry; import org.geotools.gml.GMLHandlerJTS; import org.geotools.gml.producer.GeometryTransformer; import org.geotools.referencing.CRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.OperationNotFoundException; import org.opengis.referencing.operation.TransformException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.WKBReader; import com.vividsolutions.jts.io.WKBWriter; import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTWriter; public abstract class AbstractGMLJDBCIndexWorker implements IndexWorker { public static final String GML_NS = "http: //The general configuration's element name to configure this kind of worker protected final static String INDEX_ELEMENT = "gml"; public static final String START_KEY = "start_key"; public static final String END_KEY = "end_key"; private static final Logger LOG = Logger.getLogger(AbstractGMLJDBCIndexWorker.class); protected IndexController controller; protected AbstractGMLJDBCIndex index; protected DBBroker broker; protected int currentMode = StreamListener.UNKNOWN; protected DocumentImpl currentDoc = null; private boolean isDocumentGMLAware = false; protected Map geometries = new TreeMap(); NodeId currentNodeId = null; Geometry streamedGeometry = null; boolean documentDeleted = false; int flushAfter = -1; protected GMLHandlerJTS geometryHandler = new GeometryHandler(); protected GMLFilterGeometry geometryFilter = new GMLFilterGeometry(geometryHandler); protected GMLFilterDocument geometryDocument = new GMLFilterDocument(geometryFilter); protected GMLStreamListener gmlStreamListener = new GMLStreamListener(); protected TreeMap transformations = new TreeMap(); protected boolean useLenientMode = false; protected GeometryCoordinateSequenceTransformer coordinateTransformer = new GeometryCoordinateSequenceTransformer(); protected GeometryTransformer gmlTransformer = new GeometryTransformer(); protected WKBWriter wkbWriter = new WKBWriter(); protected WKBReader wkbReader = new WKBReader(); protected WKTWriter wktWriter = new WKTWriter(); protected WKTReader wktReader = new WKTReader(); protected Base64Encoder base64Encoder = new Base64Encoder(); protected Base64Decoder base64Decoder = new Base64Decoder(); public AbstractGMLJDBCIndexWorker(AbstractGMLJDBCIndex index, DBBroker broker) { this.index = index; this.broker = broker; } public String getIndexId() { return AbstractGMLJDBCIndex.ID; } public String getIndexName() { return index.getIndexName(); } public Index getIndex() { return index; } public Object configure(IndexController controller, NodeList configNodes, Map namespaces) throws DatabaseConfigurationException { this.controller = controller; Map map = null; for(int i = 0; i < configNodes.getLength(); i++) { Node node = configNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && INDEX_ELEMENT.equals(node.getLocalName())) { map = new TreeMap(); GMLIndexConfig config = new GMLIndexConfig(namespaces, (Element)node); map.put(AbstractGMLJDBCIndex.ID, config); } } return map; } public void setDocument(DocumentImpl document) { isDocumentGMLAware = false; documentDeleted= false; if (document != null) { IndexSpec idxConf = document.getCollection().getIndexConfiguration(broker); if (idxConf != null) { Map collectionConfig = (Map) idxConf.getCustomIndexSpec(AbstractGMLJDBCIndex.ID); if (collectionConfig != null) { isDocumentGMLAware = true; if (collectionConfig.get(AbstractGMLJDBCIndex.ID) != null) flushAfter = ((GMLIndexConfig)collectionConfig.get(AbstractGMLJDBCIndex.ID)).getFlushAfter(); } } } if (isDocumentGMLAware) { currentDoc = document; } else { currentDoc = null; currentMode = StreamListener.UNKNOWN; } } public void setMode(int newMode) { currentMode = newMode; } public void setDocument(DocumentImpl doc, int mode) { setDocument(doc); setMode(mode); } /** * Returns the document for the next operation. * * @return the document */ public DocumentImpl getDocument() { return currentDoc; } /** * Returns the mode for the next operation. * * @return the document */ public int getMode() { return currentMode; } public StreamListener getListener() { //We won't listen to anything here if (currentDoc == null || currentMode == StreamListener.REMOVE_ALL_NODES) return null; return gmlStreamListener; } public MatchListener getMatchListener(DBBroker broker, NodeProxy proxy) { return null; } public StoredNode getReindexRoot(StoredNode node, NodePath path, boolean includeSelf) { if (!isDocumentGMLAware) //Not concerned return null; StoredNode topMost = node; StoredNode currentNode = node; for (int i = path.length() ; i > 0; i currentNode = (StoredNode)currentNode.getParentNode(); if (GML_NS.equals(currentNode.getNamespaceURI())) //TODO : retain only geometries topMost = currentNode; } return topMost; } public void flush() { if (!isDocumentGMLAware) //Not concerned return; //Is the job already done ? if (currentMode == StreamListener.REMOVE_ALL_NODES && documentDeleted) return; Connection conn = null; try { conn = acquireConnection(); conn.setAutoCommit(false); switch (currentMode) { case StreamListener.STORE : saveDocumentNodes(conn); break; case StreamListener.REMOVE_SOME_NODES : dropDocumentNode(conn); break; case StreamListener.REMOVE_ALL_NODES: removeDocument(conn); documentDeleted = true; break; } conn.commit(); } catch (SQLException e) { LOG.error("Document: " + currentDoc + " NodeID: " + currentNodeId, e); try { conn.rollback(); } catch (SQLException ee) { LOG.error(ee); } } finally { try { if (conn != null) { conn.setAutoCommit(true); releaseConnection(conn); } } catch (SQLException e) { LOG.error(e); } } } private void saveDocumentNodes(Connection conn) throws SQLException { if (geometries.size() == 0) return; try { for (Iterator iterator = geometries.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); NodeId nodeId = (NodeId)entry.getKey(); SRSGeometry srsGeometry = (SRSGeometry)entry.getValue(); try { saveGeometryNode(srsGeometry.getGeometry(), srsGeometry.getSRSName(), currentDoc, nodeId, conn); } finally { //Help the garbage collector srsGeometry = null; } } } finally { geometries.clear(); } } private void dropDocumentNode(Connection conn) throws SQLException { if (currentNodeId == null) return; try { boolean removed = removeDocumentNode(currentDoc, currentNodeId, conn); if (!removed) LOG.error("No data dropped for node " + currentNodeId.toString() + " from GML index"); else { if (LOG.isDebugEnabled()) LOG.debug("Dropped data for node " + currentNodeId.toString() + " from GML index"); } } finally { currentNodeId = null; } } private void removeDocument(Connection conn) throws SQLException { if (LOG.isDebugEnabled()) LOG.debug("Dropping GML index for document " + currentDoc.getURI()); int nodeCount = removeDocument(currentDoc, conn); if (LOG.isDebugEnabled()) LOG.debug("Dropped " + nodeCount + " nodes from GML index"); } public void removeCollection(Collection collection, DBBroker broker) { boolean isCollectionGMLAware = false; IndexSpec idxConf = collection.getIndexConfiguration(broker); if (idxConf != null) { Map collectionConfig = (Map) idxConf.getCustomIndexSpec(AbstractGMLJDBCIndex.ID); if (collectionConfig != null) { isCollectionGMLAware = (collectionConfig != null); } } if (!isCollectionGMLAware) return; Connection conn = null; try { conn = acquireConnection(); if (LOG.isDebugEnabled()) LOG.debug("Dropping GML index for collection " + collection.getURI()); int nodeCount = removeCollection(collection, conn); if (LOG.isDebugEnabled()) LOG.debug("Dropped " + nodeCount + " nodes from GML index"); } catch (SQLException e) { LOG.error(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); } } } public NodeSet search(DBBroker broker, NodeSet contextSet, Geometry EPSG4326_geometry, int spatialOp) throws SpatialIndexException { Connection conn = null; try { conn = acquireConnection(); return search(broker, contextSet, EPSG4326_geometry, spatialOp, conn); } catch (SQLException e) { throw new SpatialIndexException(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } } public Geometry getGeometryForNode(DBBroker broker, NodeProxy p, boolean getEPSG4326) throws SpatialIndexException { Connection conn = null; try { conn = acquireConnection(); return getGeometryForNode(broker, p, getEPSG4326, conn); } catch (SQLException e) { throw new SpatialIndexException(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } } protected Geometry[] getGeometriesForNodes(DBBroker broker, NodeSet contextSet, boolean getEPSG4326) throws SpatialIndexException { Connection conn = null; try { conn = acquireConnection(); return getGeometriesForNodes(broker, contextSet, getEPSG4326, conn); } catch (SQLException e) { throw new SpatialIndexException(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } } public AtomicValue getGeometricPropertyForNode(DBBroker broker, NodeProxy p, String propertyName) throws SpatialIndexException { Connection conn = null; try { conn = acquireConnection(); return getGeometricPropertyForNode(broker, p, conn, propertyName); } catch (SQLException e) { throw new SpatialIndexException(e); } catch (XPathException e) { throw new SpatialIndexException(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } } public ValueSequence getGeometricPropertyForNodes(DBBroker broker, NodeSet contextSet, String propertyName) throws SpatialIndexException { Connection conn = null; try { conn = acquireConnection(); return getGeometricPropertyForNodes(broker, contextSet, conn, propertyName); } catch (SQLException e) { throw new SpatialIndexException(e); } catch (XPathException e) { throw new SpatialIndexException(e); } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } } public boolean checkIndex(DBBroker broker) { Connection conn = null; try { conn = acquireConnection(); return checkIndex(broker, conn); } catch (SQLException e) { LOG.error(e); return false; } catch (SpatialIndexException e) { LOG.error(e); return false; } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return false; } } } protected abstract boolean saveGeometryNode(Geometry geometry, String srsName, DocumentImpl doc, NodeId nodeId, Connection conn) throws SQLException; protected abstract boolean removeDocumentNode(DocumentImpl doc, NodeId nodeID, Connection conn) throws SQLException; protected abstract int removeDocument(DocumentImpl doc, Connection conn) throws SQLException; protected abstract int removeCollection(Collection collection, Connection conn) throws SQLException; protected abstract Map getGeometriesForDocument(DocumentImpl doc, Connection conn) throws SQLException; protected abstract AtomicValue getGeometricPropertyForNode(DBBroker broker, NodeProxy p, Connection conn, String propertyName) throws SQLException, XPathException; protected abstract ValueSequence getGeometricPropertyForNodes(DBBroker broker, NodeSet contextSet, Connection conn, String propertyName) throws SQLException, XPathException; protected abstract Geometry getGeometryForNode(DBBroker broker, NodeProxy p, boolean getEPSG4326, Connection conn) throws SQLException; protected abstract Geometry[] getGeometriesForNodes(DBBroker broker, NodeSet contextSet, boolean getEPSG4326, Connection conn) throws SQLException; protected abstract NodeSet search(DBBroker broker, NodeSet contextSet, Geometry EPSG4326_geometry, int spatialOp, Connection conn) throws SQLException; protected abstract boolean checkIndex(DBBroker broker, Connection conn) throws SQLException, SpatialIndexException; protected abstract Connection acquireConnection() throws SQLException; protected abstract void releaseConnection(Connection conn) throws SQLException; public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet contextSet, Map hints) { //TODO : try to use contextSet Map occurences = new TreeMap(); Connection conn = null; try { conn = acquireConnection(); //Collect the (normalized) geometries for each document for (Iterator iDoc = docs.iterator(); iDoc.hasNext();) { DocumentImpl doc = (DocumentImpl)iDoc.next(); //TODO : check if document is GML-aware ? //Aggregate the occurences between different documents for (Iterator iGeom = getGeometriesForDocument(doc, conn).entrySet().iterator(); iGeom.hasNext();) { ///TODO : use the IndexWorker.VALUE_COUNT hint, if present, to limit the number of returned entries Map.Entry entry = (Map.Entry) iGeom.next(); Geometry key = (Geometry)entry.getKey(); //Do we already have an occurence for this geometry ? Occurrences oc = (Occurrences)occurences.get(key); if (oc != null) { //Yes : increment occurence count oc.addOccurrences(oc.getOccurrences() + 1); //...and reference the document oc.addDocument(doc); } else { //No : create a new occurence with EPSG4326_WKT as "term" oc = new Occurrences((String)entry.getValue()); //... with a count set to 1 oc.addOccurrences(1); //... and reference the document oc.addDocument(doc); occurences.put(key, oc); } } } } catch (SQLException e) { LOG.error(e); return null; } finally { try { if (conn != null) releaseConnection(conn); } catch (SQLException e) { LOG.error(e); return null; } } Occurrences[] result = new Occurrences[occurences.size()]; occurences.values().toArray(result); return result; } public Geometry streamNodeToGeometry(XQueryContext context, NodeValue node) throws SpatialIndexException { try { context.pushDocumentContext(); try { //TODO : get rid of the context dependency node.toSAX(context.getBroker(), geometryDocument, null); } finally { context.popDocumentContext(); } } catch (SAXException e) { throw new SpatialIndexException(e); } return streamedGeometry; } public Element streamGeometryToElement(Geometry geometry, String srsName, Receiver receiver) throws SpatialIndexException { //YES !!! String gmlString = null; try { //TODO : find a way to pass //1) the SRS //2) gmlPrefix //3) other stuff... //This will possible require some changes in GeometryTransformer gmlString = gmlTransformer.transform(geometry); } catch (TransformerException e) { throw new SpatialIndexException(e); } try { //Copied from org.exist.xquery.functions.request.getData SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); InputSource src = new InputSource(new StringReader(gmlString)); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler((ContentHandler)receiver); reader.parse(src); Document doc = receiver.getDocument(); return doc.getDocumentElement(); } catch (ParserConfigurationException e) { throw new SpatialIndexException(e); } catch (SAXException e) { throw new SpatialIndexException(e); } catch (IOException e) { throw new SpatialIndexException(e); } } public Geometry transformGeometry(Geometry geometry, String sourceCRS, String targetCRS) throws SpatialIndexException { //provisional workarounds if ("osgb:BNG".equalsIgnoreCase(sourceCRS.trim())) sourceCRS = "EPSG:27700"; if ("osgb:BNG".equalsIgnoreCase(targetCRS.trim())) targetCRS = "EPSG:27700"; MathTransform transform = (MathTransform)transformations.get(sourceCRS + "_" + targetCRS); if (transform == null) { try { try { transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode); } catch (OperationNotFoundException e) { LOG.info(e); LOG.info("Switching to lenient mode... beware of precision loss !"); //Last parameter set to true ; won't bail out if it can't find the Bursa Wolf parameters //as it is the case in current gt2-epsg-wkt-2.4-M1.jar useLenientMode = true; transform = CRS.findMathTransform(CRS.decode(sourceCRS), CRS.decode(targetCRS), useLenientMode); } transformations.put(sourceCRS + "_" + targetCRS, transform); LOG.debug("Instantiated transformation from '" + sourceCRS + "' to '" + targetCRS + "'"); } catch (NoSuchAuthorityCodeException e) { LOG.error(e); } catch (FactoryException e) { LOG.error(e); } } if (transform == null) { throw new SpatialIndexException("Unable to get a transformation from '" + sourceCRS + "' to '" + targetCRS +"'"); } coordinateTransformer.setMathTransform(transform); try { return coordinateTransformer.transform(geometry); } catch (TransformException e) { throw new SpatialIndexException(e); } } private class GMLStreamListener extends AbstractStreamListener { Stack srsNamesStack = new Stack(); ElementImpl deferredElement; public IndexWorker getWorker() { return AbstractGMLJDBCIndexWorker.this; } public void startElement(Txn transaction, ElementImpl element, NodePath path) { if (isDocumentGMLAware) { //Release the deferred element if any if (deferredElement != null) processDeferredElement(); //Retain this element deferredElement = element; } //Forward the event to the next listener super.startElement(transaction, element, path); } public void attribute(Txn transaction, AttrImpl attrib, NodePath path) { //Forward the event to the next listener super.attribute(transaction, attrib, path); } public void characters(Txn transaction, TextImpl text, NodePath path) { if (isDocumentGMLAware) { //Release the deferred element if any if (deferredElement != null) processDeferredElement(); try { geometryDocument.characters(text.getData().toCharArray(), 0, text.getLength()); } catch (Exception e) { LOG.error(e); } } //Forward the event to the next listener super.characters(transaction, text, path); } public void endElement(Txn transaction, ElementImpl element, NodePath path) { if (isDocumentGMLAware) { //Release the deferred element if any if (deferredElement != null) processDeferredElement(); //Process the element processCurrentElement(element); } //Forward the event to the next listener super.endElement(transaction, element, path); } private void processDeferredElement() { //We need to collect the deferred element's attributes in order to feed the SAX handler AttributesImpl attList = new AttributesImpl(); NamedNodeMap attrs = deferredElement.getAttributes(); String whatToPush = null; for (int i = 0; i < attrs.getLength() ; i++) { AttrImpl attrib = (AttrImpl)attrs.item(i); //Store the srs if (GML_NS.equals(deferredElement.getNamespaceURI())) { //Maybe we could assume a configurable default value here if (attrib.getName().equals("srsName")) { whatToPush = attrib.getValue(); } } attList.addAttribute(attrib.getNamespaceURI(), attrib.getLocalName(), attrib.getQName().getStringValue(), Integer.toString(attrib.getType()), attrib.getValue()); } srsNamesStack.push(whatToPush); try { geometryDocument.startElement(deferredElement.getNamespaceURI(), deferredElement.getLocalName(), deferredElement.getQName().getStringValue(), attList); } catch (Exception e) { e.printStackTrace(); LOG.error(e); } finally { deferredElement = null; } } private void processCurrentElement(ElementImpl element) { String currentSrsName = (String)srsNamesStack.pop(); try { geometryDocument.endElement(element.getNamespaceURI(), element.getLocalName(), element.getQName().getStringValue()); //Some invalid/(yet) incomplete geometries don't have a SRS if (streamedGeometry != null && currentSrsName != null) { currentNodeId = element.getNodeId(); geometries.put(currentNodeId, new SRSGeometry(currentSrsName, streamedGeometry)); if (flushAfter != -1 && geometries.size() >= flushAfter) { //Mmmh... doesn't flush since it is currently dependant from the //number of nodes in the DOM file ; would need refactorings //currentDoc.getBroker().checkAvailableMemory(); broker.flush(); ///Aaaaaargl ! final double percent = ((double) Runtime.getRuntime().freeMemory() / (double) Runtime.getRuntime().maxMemory()) * 100; if (percent < 30) { System.gc(); } } } } catch (Exception e) { LOG.error("Unable to collect geometry for node: " + currentNodeId + ". Indexing will be skipped", e); } finally { streamedGeometry = null; } } } private class GeometryHandler extends XMLFilterImpl implements GMLHandlerJTS { public void geometry(Geometry geometry) { streamedGeometry = geometry; //TODO : null geometries can be returned for many reasons, including a (too) strict //topology check done by the Geotools SAX parser. //It would be nice to have static classes extending Geometry to report such geometries if (geometry == null) LOG.error("Collected null geometry for node: " + currentNodeId + ". Indexing will be skipped"); } } private class SRSGeometry { private String SRSName; private Geometry geometry; public SRSGeometry(String SRSName, Geometry geometry) { //TODO : implement a default, eventually configurable, SRS ? if (SRSName == null) throw new IllegalArgumentException("Got null SRS"); if (geometry == null) throw new IllegalArgumentException("Got null geometry"); this.SRSName = SRSName; this.geometry = geometry; } public String getSRSName() { return SRSName; } public Geometry getGeometry() { return geometry; } } }
package com.linkedin.datahub.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.linkedin.common.UrnArray; import com.linkedin.common.urn.Urn; import com.linkedin.data.template.RecordTemplate; import com.linkedin.datahub.models.PagedCollection; import com.linkedin.metadata.dao.utils.RecordUtils; import com.linkedin.metadata.query.SearchResultMetadata; import com.linkedin.restli.common.CollectionResponse; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.annotation.Nonnull; public class RestliUtil { public static final ObjectMapper OM = new ObjectMapper(); private RestliUtil() { } // convert restli collection response to PagedCollection @Nonnull public static <T extends RecordTemplate> PagedCollection<T> toPagedCollection( @Nonnull CollectionResponse<T> response) { PagedCollection<T> result = new PagedCollection<>(); result.setElements(response.getElements()); result.setStart(response.getPaging().getStart()); result.setCount(response.getPaging().getCount()); result.setTotal(response.getPaging().getTotal()); return result; } // convert restli RecordTemplate to JsonNode @Nonnull public static <T extends RecordTemplate> JsonNode toJsonNode(@Nonnull T record) throws IOException { String jsonString = RecordUtils.toJsonString(record); return OM.readTree(jsonString); } // convert restli collection response to JsonNode @Nonnull public static <T extends RecordTemplate> JsonNode collectionResponseToJsonNode( @Nonnull CollectionResponse<T> response) throws IOException { final ObjectNode node = OM.createObjectNode(); node.set("elements", collectionToArrayNode(response.getElements())); node.put("start", response.getPaging().getStart()); node.put("count", response.getPaging().getCount()); node.put("total", response.getPaging().getTotal()); return node; } // Converts a collection to Json ArrayNode @Nonnull public static <T extends RecordTemplate> ArrayNode collectionToArrayNode(@Nonnull Collection<T> elements) throws IOException { final ArrayNode arrayNode = OM.createArrayNode(); for (T element : elements) { arrayNode.add(toJsonNode(element)); } return arrayNode; } // Converts a collection to Json ArrayNode. For each element in the collection, it adds the corresponding urn @Nonnull public static <T extends RecordTemplate> ArrayNode collectionToArrayNode(@Nonnull Collection<T> elements, @Nonnull UrnArray urns) throws IOException { if (elements.size() != urns.size()) { throw new RuntimeException("Collection size and urn size should match"); } final ArrayNode arrayNode = OM.createArrayNode(); final Iterator<Urn> urnIterator = urns.iterator(); for (T element : elements) { final ObjectNode node = (ObjectNode) toJsonNode(element); arrayNode.add(node.put("urn", urnIterator.next().toString())); } return arrayNode; } // Convert restli collection response with metadata to JsonNode @Nonnull public static <T extends RecordTemplate> JsonNode collectionResponseWithMetadataToJsonNode( @Nonnull CollectionResponse<T> response) throws IOException { final SearchResultMetadata searchResultMetadata = new SearchResultMetadata(response.getMetadataRaw()); final ObjectNode objectNode = (ObjectNode) collectionResponseToJsonNodeWithoutElements(response); objectNode.set("elements", collectionToArrayNode(response.getElements(), searchResultMetadata.getUrns())); if (response.getMetadataRaw() == null) { return objectNode; } // Use searchResultMetadatas field as a section in the final result json node final String name = SearchResultMetadata.fields().searchResultMetadatas().toString(); final String fieldName = name.startsWith("/") ? name.substring(1) : name; objectNode.set(fieldName, toJsonNode(searchResultMetadata).get(fieldName)); return objectNode; } // convert restli collection response to JsonNode without populating elements @Nonnull public static <T extends RecordTemplate> JsonNode collectionResponseToJsonNodeWithoutElements( @Nonnull CollectionResponse<T> response) throws IOException { final ObjectNode node = OM.createObjectNode(); node.put("start", response.getPaging().getStart()); node.put("count", response.getPaging().getCount()); node.put("total", response.getPaging().getTotal()); return node; } // Convert restli collection response with metadata to JsonNode @Nonnull public static <T extends RecordTemplate, Y extends RecordTemplate> JsonNode collectionResponseToJsonNode( @Nonnull CollectionResponse<T> response, @Nonnull Y metadata) throws IOException { JsonNode node = collectionResponseToJsonNode(response); ObjectNode objectNode = (ObjectNode) node; objectNode.set("metadata", toJsonNode(metadata)); return objectNode; } // Converts restli map response to JsonNode @Nonnull public static <T extends RecordTemplate> JsonNode mapResponseToJsonNode(@Nonnull Map<?, T> map) throws IOException { ObjectNode node = OM.createObjectNode(); for (Map.Entry<?, T> entry : map.entrySet()) { node.set(entry.getKey().toString(), toJsonNode(entry.getValue())); } return node; } // Converts a string collection to Json ArrayNode @Nonnull public static ArrayNode stringCollectionToArrayNode(@Nonnull Collection<String> elements) { final ArrayNode arrayNode = OM.createArrayNode(); elements.forEach(s -> arrayNode.add(s)); return arrayNode; } }
package br.net.mirante.singular.form.wicket.mapper; import java.io.Serializable; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.model.IModel; import br.net.mirante.singular.form.mform.MInstancia; import br.net.mirante.singular.form.mform.basic.ui.MPacoteBasic; import br.net.mirante.singular.form.mform.basic.view.MView; import br.net.mirante.singular.form.wicket.behavior.MoneyMaskBehavior; import br.net.mirante.singular.form.wicket.model.MInstanciaValorModel; import br.net.mirante.singular.util.wicket.bootstrap.layout.BSContainer; import br.net.mirante.singular.util.wicket.bootstrap.layout.BSControls; import br.net.mirante.singular.util.wicket.util.WicketUtils; public class MonetarioMapper implements ControlsFieldComponentMapper { private static final int DEFAULT_INTEGER_DIGITS = 9; private static final int DEFAULT_DIGITS = 2; private static final String PRECISION = "precision"; @Override public Component appendInput(MView view, BSContainer bodyContainer, BSControls formGroup, IModel<? extends MInstancia> model, IModel<String> labelModel) { TextField<BigDecimal> comp = new TextField<>(model.getObject().getNome(), new MInstanciaValorModel<>(model), BigDecimal.class); formGroup.appendInputText(comp.setLabel(labelModel).setOutputMarkupId(true) .add(new Behavior() { @Override public void beforeRender(Component component) { component.getResponse().write("<div class=\"input-group\">"); component.getResponse().write("<div class=\"input-group-addon\">R$</div>"); } @Override public void afterRender(Component component) { component.getResponse().write("</div>"); } }) .add(new MoneyMaskBehavior(withOptionsOf(model))) .add(WicketUtils.$b.attr("maxlength", calcularMaxLength(model)))); return comp; } private Serializable calcularMaxLength(IModel<?extends MInstancia> model) { Integer inteiro = getInteiroMaximo(model); Integer decimal = getDecimalMaximo(model); int tamanhoMascara = (int) Math.ceil((double)inteiro / 3); return inteiro + tamanhoMascara + decimal; } @Override public String getReadOnlyFormattedText(IModel<? extends MInstancia> model) { final MInstancia mi = model.getObject(); if ((mi != null) && (mi.getValor() != null)) { final NumberFormat numberFormat = NumberFormat.getInstance(new Locale("pt", "BR")); final DecimalFormat decimalFormat = (DecimalFormat) numberFormat; final BigDecimal valor = (BigDecimal) mi.getValor(); final Map<String, Object> options = withOptionsOf(model); final Integer digitos = (int) options.get(PRECISION); final StringBuilder pattern = new StringBuilder(); pattern.append("R$ for (int i = 0; i < digitos; i += 1) { pattern.append(" } decimalFormat.applyPattern(pattern.toString()); decimalFormat.setMinimumFractionDigits(digitos); return decimalFormat.format(valor); } return StringUtils.EMPTY; } private Map<String, Object> withOptionsOf(IModel<? extends MInstancia> model) { Map<String, Object> options = defaultOptions(); options.put(PRECISION, getDecimalMaximo(model)); return options; } private Integer getDecimalMaximo(IModel<? extends MInstancia> model) { Optional<Integer> decimalMaximo = Optional.ofNullable( model.getObject().getValorAtributo(MPacoteBasic.ATR_TAMANHO_DECIMAL_MAXIMO)); return decimalMaximo.orElse(DEFAULT_DIGITS); } private Integer getInteiroMaximo(IModel<? extends MInstancia> model) { Optional<Integer> inteiroMaximo = Optional.ofNullable( model.getObject().getValorAtributo(MPacoteBasic.ATR_TAMANHO_INTEIRO_MAXIMO)); return inteiroMaximo.orElse(DEFAULT_INTEGER_DIGITS); } private Map<String, Object> defaultOptions() { Map<String, Object> options = new HashMap<>(); options.put("thousands", "."); options.put("decimal", ","); options.put("allowZero", true); options.put("allowNegative", true); return options; } }
package cn.bvin.android.lib.widget.refresh; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.DecelerateInterpolator; import android.view.animation.Transformation; import android.widget.AbsListView; public class GestureRefreshLayout extends ViewGroup { private static final String TAG = "GestureRefreshLayout"; private static final int MAX_ALPHA = 255; private static final float DECELERATE_INTERPOLATION_FACTOR = 2f; private static final int SCALE_DOWN_DURATION = 150; private static final int ANIMATE_TO_TRIGGER_DURATION = 200; private static final int ANIMATE_TO_START_DURATION = 200; private static final int[] LAYOUT_ATTRS = new int[]{android.R.attr.enabled}; private static final int INVALID_POINTER = -1; private static final float DRAG_RATE = .5f; private View mTarget; private OnRefreshListener mListener; private boolean mRefreshing = false; private int mTouchSlop; private float mTotalDragDistance = -1; private int mMediumAnimationDuration; private int mCurrentTargetOffsetTop; // Whether or not the starting offset has been determined. private boolean mOriginalOffsetCalculated = false; protected int mOriginalOffsetTop; // End int mSpinnerOffsetEnd; private float mInitialMotionY; private float mInitialDownY; // Whether this item is scaled up rather than clipped private boolean mScale; // Target is returning to its start offset because it was cancelled or a // refresh was triggered. private boolean mReturningToStart; private final DecelerateInterpolator mDecelerateInterpolator; private View mRefreshView; private int mRefreshViewIndex = -1; protected int mFrom; private float mStartingScale; private Animation mScaleAnimation; private Animation mScaleDownAnimation; private Animation mScaleDownToStartAnimation; private boolean mIsBeingDragged; private int mActivePointerId = INVALID_POINTER; // View private boolean mIsInterceptedMoveEvent; private OnChildScrollUpCallback mChildScrollUpCallback; private OnGestureStateChangeListener mGestureChangeListener; private boolean mNotify; // Whether the client has set a custom starting position; private boolean mUsingCustomStart; // Content private boolean mTranslateContent; private OnLayoutTranslateCallback mOnLayoutTranslateCallback; private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mRefreshing) { // Make sure the progress view is fully visible if (mNotify) { if (mListener != null) { mListener.onRefresh(); } } } else { reset(); } mCurrentTargetOffsetTop = mRefreshView.getTop(); } }; public GestureRefreshLayout(Context context) { this(context, null); } public GestureRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); mMediumAnimationDuration = getResources().getInteger( android.R.integer.config_mediumAnimTime); mDecelerateInterpolator = new DecelerateInterpolator(DECELERATE_INTERPOLATION_FACTOR); final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS); setEnabled(a.getBoolean(0, true)); a.recycle(); // the absolute offset has to take into account that the circle starts at an offset mTotalDragDistance = mSpinnerOffsetEnd = 64; mOriginalOffsetTop = mCurrentTargetOffsetTop = -40;// refresh height } @Override protected int getChildDrawingOrder(int childCount, int i) { if (mRefreshViewIndex < 0) { return i; } else if (i == childCount - 1) { // Draw the selected child last return mRefreshViewIndex; } else if (i >= mRefreshViewIndex) { // Move the children after the selected child earlier one return i + 1; } else { // Keep the children before the selected child the same return i; } } void reset() { mRefreshView.clearAnimation(); mRefreshView.setVisibility(View.GONE); setColorViewAlpha(MAX_ALPHA); // Return the circle to its start position if (mScale) { setAnimationProgress(0 /* animation complete and view is hidden */); } else { setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCurrentTargetOffsetTop, true /* requires update */); } mCurrentTargetOffsetTop = mRefreshView.getTop(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); if (!enabled){ reset(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mRefreshView == null) { return; } reset(); } /** * The refresh indicator starting and resting position is always positioned * near the top of the refreshing content. This position is a consistent * location, but can be adjusted in either direction based on whether or not * there is a toolbar or actionbar present. * <p> * <strong>Note:</strong> Calling this will reset the position of the refresh indicator to * <code>start</code>. * </p> * * @param scale Set to true if there is no view at a higher z-order than where the progress * spinner is set to appear. Setting it to true will cause indicator to be scaled * up rather than clipped. * @param start The offset in pixels from the top of this view at which the * progress spinner should appear. * @param end The offset in pixels from the top of this view at which the * progress spinner should come to rest after a successful swipe * gesture. */ public void setRefreshViewOffset(boolean scale, int start, int end) { mOriginalOffsetTop = start; mSpinnerOffsetEnd = end; mUsingCustomStart = true; reset(); mRefreshing = false; } public void setTranslateContent(boolean translateContent) { mTranslateContent = translateContent; } /** * Set the listener to be notified when a refresh is triggered via the swipe * gesture. */ public void setOnRefreshListener(OnRefreshListener listener) { mListener = listener; } public void setOnLayoutTranslateCallback(OnLayoutTranslateCallback onLayoutTranslateCallback) { mOnLayoutTranslateCallback = onLayoutTranslateCallback; } /** * Pre API 11, alpha is used to make the progress circle appear instead of scale. */ private boolean isAlphaUsedForScale() { return android.os.Build.VERSION.SDK_INT < 11; } /** * Notify the widget that refresh state has changed. Do not call this when * refresh is triggered by a swipe gesture. * * @param refreshing Whether or not the view should show refresh progress. */ public void setRefreshing(boolean refreshing) { if (refreshing && mRefreshing != refreshing) { // scale and show mRefreshing = refreshing; int endTarget = 0; if (!mUsingCustomStart) { endTarget = (mSpinnerOffsetEnd + mOriginalOffsetTop); } else { endTarget = mSpinnerOffsetEnd; } // offset = mSpinnerOffsetEnd + mOriginalOffsetTop - mCurrentTargetOffsetTop // StartmOriginalOffsetTopmCurrentTargetOffsetTop // mSpinnerOffsetEnd setTargetOffsetTopAndBottom(endTarget - mCurrentTargetOffsetTop, true /* requires update */); mNotify = false; startScaleUpAnimation(mRefreshListener); } else { setRefreshing(refreshing, false /* notify */); } } private void startScaleUpAnimation(Animation.AnimationListener listener) { mRefreshView.setVisibility(View.VISIBLE); if (android.os.Build.VERSION.SDK_INT >= 11) { // Pre API 11, alpha is used in place of scale up to show the // progress circle appearing. // Don't adjust the alpha during appearance otherwise. //mProgress.setAlpha(MAX_ALPHA); } mScaleAnimation = new Animation() { @Override public void applyTransformation(float interpolatedTime, Transformation t) { setAnimationProgress(interpolatedTime); } }; mScaleAnimation.setDuration(mMediumAnimationDuration); mScaleAnimation.setAnimationListener(listener); mRefreshView.clearAnimation(); mRefreshView.startAnimation(mScaleAnimation); } /** * RefreshView. * @param targetAlpha */ private void setColorViewAlpha(int targetAlpha) { if (mRefreshView != null && mRefreshView.getBackground() != null) { mRefreshView.getBackground().setAlpha(targetAlpha); } } /** * Pre API 11, this does an alpha animation. * @param progress */ private void setAnimationProgress(float progress) { if (isAlphaUsedForScale()) { setColorViewAlpha((int) (progress * MAX_ALPHA)); } else { ViewCompat.setScaleX(mRefreshView, progress); ViewCompat.setScaleY(mRefreshView, progress); } } private void setRefreshing(boolean refreshing, final boolean notify) { if (mRefreshing != refreshing) { mNotify = notify; ensureTarget(); mRefreshing = refreshing; if (mRefreshing) { animateOffsetToCorrectPosition(mCurrentTargetOffsetTop, mRefreshListener); } else { startScaleDownAnimation(mRefreshListener); } } } private void startScaleDownAnimation(Animation.AnimationListener listener) { mScaleDownAnimation = new Animation() { @Override public void applyTransformation(float interpolatedTime, Transformation t) { setAnimationProgress(1 - interpolatedTime); } }; mScaleDownAnimation.setDuration(SCALE_DOWN_DURATION); mScaleDownAnimation.setAnimationListener(listener); mRefreshView.clearAnimation(); mRefreshView.startAnimation(mScaleDownAnimation); } private void ensureTarget() { if (mTarget == null) { mTarget = getChildAt(0); mRefreshView = getChildAt(1); } } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.d(TAG, "onMeasure: "); if (mTarget == null) { ensureTarget(); } if (mTarget == null) { return; } /*mTarget.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));*/ measureChild(mTarget, widthMeasureSpec, heightMeasureSpec); if (mRefreshView == null) { return; } measureChild(mRefreshView, widthMeasureSpec, heightMeasureSpec); // measure other child view. int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child != mTarget && child != mRefreshView) measureChild(child, widthMeasureSpec, heightMeasureSpec); } if (!mUsingCustomStart && !mOriginalOffsetCalculated) { mOriginalOffsetCalculated = true; mCurrentTargetOffsetTop = mOriginalOffsetTop = -mRefreshView.getMeasuredHeight(); // RefreshView64px mTotalDragDistance = mSpinnerOffsetEnd = (int) (-mOriginalOffsetTop + mTotalDragDistance); } mRefreshViewIndex = -1; // Get the index of the circleview. for (int index = 0; index < getChildCount(); index++) { if (getChildAt(index) == mRefreshView) { mRefreshViewIndex = index; break; } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { Log.d(TAG, "onLayout: "); final int width = getMeasuredWidth(); final int height = getMeasuredHeight(); if (getChildCount() == 0) { return; } if (mTarget == null) { ensureTarget(); } if (mTarget == null) { return; } final View child = mTarget; final int childLeft = getPaddingLeft(); int childTop = getPaddingTop(); if (mTranslateContent && mRefreshView != null) { childTop += mRefreshView.getMeasuredHeight() + mCurrentTargetOffsetTop; } final int childWidth = width - getPaddingLeft() - getPaddingRight(); final int childHeight = height - getPaddingTop() - getPaddingBottom(); child.layout(childLeft, childTop, childLeft + mTarget.getMeasuredWidth(), childTop + mTarget.getMeasuredHeight()); if (mRefreshView == null) { return; } mRefreshView.layout(childLeft, mCurrentTargetOffsetTop, childLeft + mRefreshView.getMeasuredWidth(), mCurrentTargetOffsetTop + mRefreshView.getMeasuredHeight()); // layout other child view final int count = getChildCount(); final int parentLeft = getPaddingLeft(); final int parentRight = r - l - getPaddingLeft(); final int parentTop = getPaddingTop(); final int parentBottom = b - t - getPaddingBottom(); for (int i = 0; i < count; i++) { final View view = getChildAt(i); if (view.getVisibility() != GONE && view != mTarget && view != mRefreshView &&mCurrentTargetOffsetTop==mOriginalOffsetTop) { //margin/gravity view.layout(parentLeft, -view.getMeasuredHeight(), parentLeft + view.getMeasuredWidth(), 0); } } if (mOnLayoutTranslateCallback != null) { mOnLayoutTranslateCallback.onLayoutTranslate(mCurrentTargetOffsetTop ); } } public void setChildScrollUpCallback(OnChildScrollUpCallback childScrollUpCallback) { mChildScrollUpCallback = childScrollUpCallback; } public void setOnGestureChangeListener(OnGestureStateChangeListener gestureChangeListener) { mGestureChangeListener = gestureChangeListener; } /** * @return Whether it is possible for the child view of this layout to * scroll up. Override this if the child view is a custom view. */ public boolean canChildScrollUp() { if (mChildScrollUpCallback != null) { return mChildScrollUpCallback.canChildScrollUp(this, mTarget); } if (android.os.Build.VERSION.SDK_INT < 14) { if (mTarget instanceof AbsListView) { final AbsListView absListView = (AbsListView) mTarget; return absListView.getChildCount() > 0 && (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0).getTop() < absListView.getPaddingTop()); } else { return ViewCompat.canScrollVertically(mTarget, -1) || mTarget.getScrollY() > 0; } } else { return ViewCompat.canScrollVertically(mTarget, -1); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mRefreshView == null) { return false; } Log.d(TAG, "onInterceptTouchEvent: "+ev.toString()); final int action = MotionEventCompat.getActionMasked(ev); if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { // Fail fast if we're not in a state where a swipe is possible mReturningToStart = false; } if (!isEnabled() || canChildScrollUp() || mReturningToStart || mRefreshing) { return false; } switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsBeingDragged = false; final float initialDownY = getMotionEventY(ev, mActivePointerId); if (initialDownY == -1) { return false; } mInitialDownY = initialDownY; mIsInterceptedMoveEvent = false; break; case MotionEvent.ACTION_MOVE: if (mActivePointerId == INVALID_POINTER) { Log.e(TAG, "Got ACTION_MOVE event but don't have an active pointer id."); return false; } final float y = getMotionEventY(ev, mActivePointerId); if (y == -1) { return false; } mIsInterceptedMoveEvent = true; determineUserWhetherBeingDragged(y); break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; break; } return mIsBeingDragged; } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // if this is a List < L or another view that doesn't support nested // scrolling, ignore this request so that the vertical scroll event // isn't stolen if ((android.os.Build.VERSION.SDK_INT < 21 && mTarget instanceof AbsListView) || (mTarget != null && !ViewCompat.isNestedScrollingEnabled(mTarget))) { // Nope. } else { super.requestDisallowInterceptTouchEvent(disallowIntercept); } } private void determineUserWhetherBeingDragged(float currentY) { final float yDiff = currentY - mInitialDownY; if (yDiff > mTouchSlop && !mIsBeingDragged) { mInitialMotionY = mInitialDownY + mTouchSlop; mIsBeingDragged = true; //mProgress.setAlpha(STARTING_PROGRESS_ALPHA); } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); } } private float getMotionEventY(MotionEvent ev, int activePointerId) { final int index = MotionEventCompat.findPointerIndex(ev, activePointerId); if (index < 0) { return -1; } return MotionEventCompat.getY(ev, index); } @Override public boolean onTouchEvent(MotionEvent ev) { if (mRefreshView == null) { return false; } Log.d(TAG, "onTouchEvent: "+ev.toString()); final int action = MotionEventCompat.getActionMasked(ev); if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { mReturningToStart = false; } if (!isEnabled() || mReturningToStart || canChildScrollUp()) { // Fail fast if we're not in a state where a swipe is possible return false; } switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: if (mIsInterceptedMoveEvent) mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsBeingDragged = false; break; case MotionEvent.ACTION_MOVE: { final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (pointerIndex < 0) { Log.e(TAG, "Got ACTION_MOVE event but have an invalid active pointer id."); return false; } final float y = MotionEventCompat.getY(ev, pointerIndex); if (!mIsInterceptedMoveEvent) { determineUserWhetherBeingDragged(y); } final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; if (mIsBeingDragged) { if (overscrollTop > 0) { if (mGestureChangeListener != null) { mGestureChangeListener.onStartDrag(y); } Log.d(TAG, "move: "+overscrollTop+","+y+","+mInitialMotionY); startDrag(overscrollTop); } else { return false; } } break; } case MotionEventCompat.ACTION_POINTER_DOWN: { final int index = MotionEventCompat.getActionIndex(ev); mActivePointerId = MotionEventCompat.getPointerId(ev, index); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: { if (mActivePointerId == INVALID_POINTER) { if (action == MotionEvent.ACTION_UP) { Log.e(TAG, "Got ACTION_UP event but don't have an active pointer id."); } return false; } final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); final float y = MotionEventCompat.getY(ev, pointerIndex); final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; mIsBeingDragged = false; if (mGestureChangeListener != null) { mGestureChangeListener.onFinishDrag(y); } endDrag(overscrollTop); mActivePointerId = INVALID_POINTER; return false; } } return true; } /** * * @param overscrollTop */ private void startDrag(float overscrollTop){ float originalDragPercent = overscrollTop / mTotalDragDistance; float dragPercent = Math.min(1f, Math.abs(originalDragPercent)); float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3; float extraOS = Math.abs(overscrollTop) - mTotalDragDistance; float slingshotDist = mUsingCustomStart ? mSpinnerOffsetEnd - mOriginalOffsetTop : mSpinnerOffsetEnd; float tensionSlingshotPercent = Math.max(0, Math.min(extraOS, slingshotDist * 2) / slingshotDist); float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow( (tensionSlingshotPercent / 4), 2)) * 2f; float extraMove = (slingshotDist) * tensionPercent * 2; int targetY = mOriginalOffsetTop + (int) ((slingshotDist * dragPercent) + extraMove); if (mRefreshView != null) { // where 1.0f is a full circle if (mRefreshView.getVisibility() != View.VISIBLE) { mRefreshView.setVisibility(View.VISIBLE); } if (!mScale) { ViewCompat.setScaleX(mRefreshView, 1f); ViewCompat.setScaleY(mRefreshView, 1f); } } if (overscrollTop < mTotalDragDistance){ // update progress if (mScale) { setAnimationProgress(Math.min(1f, overscrollTop / mTotalDragDistance)); } }else { } float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f; int offset = targetY - mCurrentTargetOffsetTop; Log.d(TAG, "startDrag: "+mCurrentTargetOffsetTop+","+offset); setTargetOffsetTopAndBottom(offset, true /* requires update */); if (mGestureChangeListener != null) {//overscrollTopdraggedDistance mGestureChangeListener.onDragging(overscrollTop, mTotalDragDistance); } } private void endDrag(float overscrollTop){ Log.d(TAG, "endDrag: "+overscrollTop+","+mTotalDragDistance); if (overscrollTop > mTotalDragDistance){ setRefreshing(true, true /* notify */); }else { // cancel refresh mRefreshing = false; Animation.AnimationListener listener = null; if (!mScale) { listener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (!mScale) { startScaleDownAnimation(null); } } @Override public void onAnimationRepeat(Animation animation) { } }; } animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener); } if (mGestureChangeListener != null) { mGestureChangeListener.onFinishDrag(mCurrentTargetOffsetTop); } } private void animateOffsetToCorrectPosition(int from, Animation.AnimationListener listener) { mFrom = from; mAnimateToCorrectPosition.reset(); mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION); mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator); mAnimateToCorrectPosition.setAnimationListener(listener); mRefreshView.clearAnimation(); mRefreshView.startAnimation(mAnimateToCorrectPosition); } private void animateOffsetToStartPosition(int from, Animation.AnimationListener listener) { if (mScale) { // Scale the item back down startScaleDownReturnToStartAnimation(from, listener); } else { mFrom = from; mAnimateToStartPosition.reset(); mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION); mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator); mAnimateToStartPosition.setAnimationListener(listener); mRefreshView.clearAnimation(); mRefreshView.startAnimation(mAnimateToStartPosition); } } private void moveToStart(float interpolatedTime) { int targetTop = 0; targetTop = (mFrom + (int) ((mOriginalOffsetTop - mFrom) * interpolatedTime)); int offset = targetTop - mRefreshView.getTop(); setTargetOffsetTopAndBottom(offset, false /* requires update */); } private final Animation mAnimateToCorrectPosition = new Animation() { @Override public void applyTransformation(float interpolatedTime, Transformation t) { int targetTop = 0; int endTarget = 0; if (!mUsingCustomStart) { endTarget = (int) (mSpinnerOffsetEnd - Math.abs(mOriginalOffsetTop)); } else { endTarget = (int) mSpinnerOffsetEnd; } targetTop = (mFrom + (int) ((endTarget - mFrom) * interpolatedTime)); int offset = targetTop - mRefreshView.getTop(); setTargetOffsetTopAndBottom(offset, false /* requires update */); //mProgress.setArrowScale(1 - interpolatedTime); } }; private final Animation mAnimateToStartPosition = new Animation() { @Override public void applyTransformation(float interpolatedTime, Transformation t) { moveToStart(interpolatedTime); } }; private void startScaleDownReturnToStartAnimation(int from, Animation.AnimationListener listener) { mFrom = from; if (isAlphaUsedForScale()) { mStartingScale = mRefreshView.getAlpha(); } else { mStartingScale = ViewCompat.getScaleX(mRefreshView); } mScaleDownToStartAnimation = new Animation() { @Override public void applyTransformation(float interpolatedTime, Transformation t) { float targetScale = (mStartingScale + (-mStartingScale * interpolatedTime)); setAnimationProgress(targetScale); moveToStart(interpolatedTime); } }; mScaleDownToStartAnimation.setDuration(SCALE_DOWN_DURATION); if (listener != null) { mScaleDownToStartAnimation.setAnimationListener(listener); } mRefreshView.clearAnimation(); mRefreshView.startAnimation(mScaleDownToStartAnimation); } private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) { if (mRefreshView == null) { ensureTarget(); } mRefreshView.bringToFront(); ViewCompat.offsetTopAndBottom(mRefreshView, offset); mCurrentTargetOffsetTop = mRefreshView.getTop(); if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) { invalidate(); } } /** * Classes that wish to override {@link #canChildScrollUp()} method * behavior should implement this interface. */ public interface OnChildScrollUpCallback { /** * Callback that will be called when {@link #canChildScrollUp()} method * is called to allow the implementer to override its behavior. * * @param parent SwipeRefreshLayout that this callback is overriding. * @param child The child view of SwipeRefreshLayout. * * @return Whether it is possible for the child view of parent layout to scroll up. */ boolean canChildScrollUp(GestureRefreshLayout parent, @Nullable View child); } public interface OnGestureStateChangeListener { void onStartDrag(float startY); void onDragging(float draggedDistance, float releaseDistance); void onFinishDrag(float endY); } public interface OnLayoutTranslateCallback { void onLayoutTranslate(int movementTop); } /** * Classes that wish to be notified when the swipe gesture correctly * triggers a refresh should implement this interface. */ public interface OnRefreshListener { public void onRefresh(); } }
package org.codehaus.gmaven.adapter.impl; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import java.util.Map.Entry; import com.google.common.base.Throwables; import groovy.lang.Binding; import groovy.lang.Closure; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyCodeSource; import groovy.lang.GroovyResourceLoader; import groovy.util.AntBuilder; import org.apache.tools.ant.BuildLogger; import org.codehaus.gmaven.adapter.ClassSource; import org.codehaus.gmaven.adapter.ClassSource.Inline; import org.codehaus.gmaven.adapter.ClosureTarget; import org.codehaus.gmaven.adapter.ConsoleWindow; import org.codehaus.gmaven.adapter.GroovyRuntime; import org.codehaus.gmaven.adapter.MagicContext; import org.codehaus.gmaven.adapter.ResourceLoader; import org.codehaus.gmaven.adapter.ScriptExecutor; import org.codehaus.gmaven.adapter.ShellRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkNotNull; /** * Default {@link GroovyRuntime} implementation. * * @since 2.0 */ public class GroovyRuntimeImpl implements GroovyRuntime { private final Logger log = LoggerFactory.getLogger(getClass()); @Override public ScriptExecutor createScriptExecutor() { return new ScriptExecutorImpl(this); } @Override public ConsoleWindow createConsoleWindow() { return new ConsoleWindowImpl(this); } @Override public ShellRunner createShellRunner() { return new ShellRunnerImpl(this); } @Override public void cleanup() { // nothing atm } // Internal /** * Create a {@link GroovyClassLoader} from given {@link ClassLoader} and {@link ResourceLoader}. */ public GroovyClassLoader createGroovyClassLoader(final ClassLoader classLoader, final ResourceLoader resourceLoader) { return AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() { @Override public GroovyClassLoader run() { GroovyClassLoader gcl = new GroovyClassLoader(classLoader); gcl.setResourceLoader(createGroovyResourceLoader(resourceLoader)); return gcl; } }); } /** * Creates a {@link GroovyResourceLoader} from a {@link ResourceLoader}. */ public GroovyResourceLoader createGroovyResourceLoader(final ResourceLoader resourceLoader) { checkNotNull(resourceLoader); return new GroovyResourceLoader() { @Override public URL loadGroovySource(final String name) throws MalformedURLException { return resourceLoader.loadResource(name); } }; } /** * Creates a {@link GroovyCodeSource} from a {@link ClassSource}. */ public GroovyCodeSource createGroovyCodeSource(final ClassSource source) throws IOException { checkNotNull(source); if (source.getUrl() != null) { return new GroovyCodeSource(source.getUrl()); } if (source.getFile() != null) { return new GroovyCodeSource(source.getFile()); } if (source.getInline() != null) { Inline inline = source.getInline(); return new GroovyCodeSource(inline.getInput(), inline.getName(), inline.getCodeBase()); } throw new Error("Unable to create GroovyCodeSource from: " + source); } /** * Creates a {@link Closure} from a {@link ClosureTarget}. */ public Closure createClosure(final Object owner, final ClosureTarget target) { checkNotNull(owner); checkNotNull(target); return new Closure(owner) { @Override public Object call(final Object[] args) { try { return target.call(args); } catch (Exception e) { throw Throwables.propagate(e); } } @Override public String toString() { return Closure.class.getSimpleName() + "{owner=" + owner + ", target=" + target + "}"; } }; } /** * Create an object for a {@link MagicContext} entry. */ public Object createMagicContextValue(final MagicContext magic) { checkNotNull(magic); switch (magic) { // Create the AntBuilder instance, normalizing its output to match mavens case ANT_BUILDER: { AntBuilder ant = new AntBuilder(); // TODO: Do we need to root the ant-project or otherwise augment the configuration? Object obj = ant.getAntProject().getBuildListeners().elementAt(0); if (obj instanceof BuildLogger) { BuildLogger logger = (BuildLogger) obj; logger.setEmacsMode(true); } return ant; } } throw new Error("Unsupported magic context: " + magic); } /** * Create script binding, handling conversion of {@link ClosureTarget} and {@link MagicContext} entries. */ public Binding createBinding(final Map<String, Object> context) { Binding binding = new Binding(); log.debug("Binding:"); for (Entry<String, Object> entry : context.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof ClosureTarget) { value = createClosure(this, (ClosureTarget) value); } else if (value instanceof MagicContext) { value = createMagicContextValue((MagicContext) value); } log.debug(" {}={}", key, value); binding.setVariable(entry.getKey(), value); } return binding; } }
package com.emc.greenplum.gpdb.hdfsconnector; import com.emc.greenplum.gpdb.hadoop.formathandler.AvroFileReader; import com.emc.greenplum.gpdb.hadoop.formathandler.GpdbParquetFileReader; import com.emc.greenplum.gpdb.hadoop.io.GPDBWritable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.*; import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl; import org.apache.hadoop.io.*; import java.io.*; import java.util.*; import java.net.URI; import java.net.URISyntaxException; public class HDFSReader { protected Configuration conf; protected int segid; protected boolean isTextFormat; protected boolean isAvroFormat; protected boolean isParquetFormat; protected int totalseg; protected String inputpath; protected String schemaFile = null; protected boolean schemaComplete = false; protected boolean autoSelect = false; protected ArrayList<InputSplit> segSplits; protected List<ColumnSchema> tableSchema = null; /** * Constructor - parse the input args * * @param args the list of input argument, that should include * local segment id, total number of segments, format (TEXT or GPDBWritable) * and the location in the form of gphdfs://host:port/file_path * * @throws Exception when something goes wrong */ public HDFSReader(String[] args) { /** * 4 input argments are required: * arg[0] : local segment id * arg[1] : total number of segments * arg[2] : format: TEXT or GPDBWritable, AVRO, PARQUET * arg[3] : hadoop connector version * arg[4] : gphdfs://host:port/file_path * arg[5] : table schema * arg[6] : table column name list */ if (args.length < 5) throw new IllegalArgumentException("Wrong number of argument"); segid = Integer.parseInt(args[0]); totalseg = Integer.parseInt(args[1]); isTextFormat = (args[2].equals("TEXT")); isAvroFormat = (args[2].equals("AVRO")); isParquetFormat = (args[2].equals("PARQUET")); String connVer = args[3]; URI inputURI; try { inputURI = new URI(args[4]); } catch (URISyntaxException e) { throw new IllegalArgumentException("Illegal input uri: "+args[4]); } if (args.length >= 6) { // extract table schema // format : sprintf(args[5], "%010d%d%d%03d", typid, rel->rd_att->attrs[i]->attnotnull, rel->rd_att->attrs[i]->attndims, delim); int i = 0; while (i < args[5].length()) { int typeId = Integer.parseInt(args[5].substring(i, i + 10)); i += 10; int notNull = args[5].charAt(i) - '0'; i++; int ndims = args[5].charAt(i) - '0'; i++; char delim = (char)Integer.parseInt(args[5].substring(i, i + 3)); i += 3; if (tableSchema == null) { tableSchema = new ArrayList<ColumnSchema>(); } tableSchema.add(new ColumnSchema(typeId, notNull, ndims, delim)); } if (args.length >= 7) { // extract table column names // format : col1,col2,...,SCHEMA_NAME_MAGIC String[] colNames = args[6].split(","); if (colNames.length == tableSchema.size() && args[6].charAt(args[6].length() - 1) == ',') { // we got the whole column name list for (int j = 0; j < colNames.length; j++) { tableSchema.get(j).setColumName(colNames[j]); } schemaComplete = true; } } } if (inputURI.getQuery() != null) { String[] kv_pair = inputURI.getQuery().split("&"); for(int i=0; i<kv_pair.length; i++) { String[] kv = kv_pair[i].split("="); String key = kv[0].toLowerCase(); String val = kv[1]; if (key.equals("schema")) { schemaFile = val; }else if (key.equals("autoselect")) { autoSelect = ConnectorUtil.getBoolean(key, val); } } } // Create a conf, set the HDFS URI and the input path // Configuration.addDefaultResource("hdfs-site.xml");//hdfs-site.xml // here will be overlapped by hdfs-default.xml conf = new Configuration(); conf.addResource("hdfs-site.xml");//this line is not needed now, but line 73 // may related with some unknow old hadoop version, so I changed it here ConnectorUtil.setHadoopFSURI(conf, inputURI, connVer); inputpath = inputURI.getPath(); } /** * Either TEXT or GPDBWritable. Call the appropiate read method * * @throws Exception when something goes wrong */ public void doRead() throws IOException, InterruptedException { ConnectorUtil.loginSecureHadoop(conf); if (isTextFormat) { assignSplits(); readTextFormat(); } else if (isAvroFormat) { AvroFileReader avroReader = new AvroFileReader(conf, segid, totalseg, inputpath, tableSchema, schemaFile, schemaComplete, autoSelect, System.out); avroReader.readAvroFormat(); } else if (isParquetFormat) { GpdbParquetFileReader parquetReader = new GpdbParquetFileReader(conf, segid, totalseg, inputpath, tableSchema, schemaComplete, autoSelect, System.out); parquetReader.readParquetFormat(); } else { assignSplits(); readGPDBWritableFormat(); } } /** * Read the input as a TextInputFormat by using LineRecordReader * and write it to Std Out as is * * @throws Exception when something goes wrong */ protected void readTextFormat() throws IOException { // Text uses LineRecordReader LineRecordReader lrr = new LineRecordReader(); TaskAttemptContext fakeTaskCtx = new TaskAttemptContextImpl(conf, new TaskAttemptID()); // For each split, use the record reader to read the stuff for(int i=0; i<segSplits.size(); i++) { lrr.initialize(segSplits.get(i), fakeTaskCtx); while(lrr.nextKeyValue()) { Text val = lrr.getCurrentValue(); byte[] bytes = val.getBytes(); System.out.write(bytes, 0, val.getLength()); System.out.println(); System.out.flush(); } } lrr.close(); } /** * Read the input as GPDBWritable from SequenceFile * and write it to Std Out * * @throws Exception when something goes wrong */ protected void readGPDBWritableFormat() throws IOException, InterruptedException { // GPDBWritable uses SequenceFileRecordReader SequenceFileRecordReader<LongWritable, GPDBWritable> sfrr = new SequenceFileRecordReader<LongWritable, GPDBWritable>(); TaskAttemptContext fakeTaskCtx = new TaskAttemptContextImpl(conf, new TaskAttemptID()); /* * For each split, use the record reader to read the GPDBWritable. * Then GPDBWritable will write the serialized form to standard out, * which will be consumed by GPDB's gphdfsformatter. */ DataOutputStream dos = new DataOutputStream(System.out); for(int i=0; i<segSplits.size(); i++) { sfrr.initialize(segSplits.get(i), fakeTaskCtx); while(sfrr.nextKeyValue()) { GPDBWritable val = sfrr.getCurrentValue(); val.write(dos); dos.flush(); } } sfrr.close(); } /** * Create a list of input splits from the input path * and then assign splits to our segment in round robin */ protected void assignSplits() throws IOException { // Create a input split list for the input path Job jobCtx = new Job(conf); FileInputFormat.setInputPaths(jobCtx, new Path(inputpath)); FileInputFormat fformat = (isTextFormat)? new TextInputFormat() : new SequenceFileInputFormat(); List<InputSplit> splits = fformat.getSplits(jobCtx); // Round robin assign splits to segments segSplits = new ArrayList<InputSplit>(splits.size()/totalseg+1); for(int i=0; i<splits.size(); i++) { if (i%totalseg == segid) segSplits.add(splits.get(i)); } } public static void main(String[] args) throws Exception { HDFSReader hr = new HDFSReader(args); hr.doRead(); } }
package org.grobid.core.utilities.crossref; import java.time.Duration; import java.util.List; /** * Listener to catch response from a CrossrefRequest. * * @author Vincent Kaestle */ public class CrossrefRequestListener<T extends Object> { public static class Response<T> { public int status = -1; public List<T> results = null; public int interval; public int limitIterations; public long time; public String errorMessage; public Exception errorException; public Response() { this.status = -1; this.results = null; this.interval = 0; this.limitIterations = 1; this.time = System.currentTimeMillis(); this.errorMessage = null; this.errorException = null; } public void setTimeLimit(String limitInterval, String limitLimit) { this.interval = (int)Duration.parse("PT"+limitInterval.toUpperCase()).toMillis(); this.limitIterations = Integer.parseInt(limitLimit); } public void setException(Exception e, CrossrefRequest<T> request) { errorException = e; errorMessage = e.getClass().getName()+" thrown during request execution : "+request.toString()+"\n"+e.getMessage(); } public int getOneStepTime() { return interval/limitIterations; } public String toSring() { return "Response (status:"+status+" timeLimit:"+interval+"/"+limitIterations+", results:"+results.size(); } public boolean hasError() { return (errorMessage != null) || (errorException != null); } public boolean hasResults() { return (results != null) && (results.size() > 0); } } /** * Called when request executed and get any response */ public void onResponse(Response<T> response) {} /** * Called when request succeed and response format is as expected */ public void onSuccess(List<T> results) {} /** * Called when request gives an error */ public void onError(int status, String message, Exception exception) {} public void notify(Response<T> response) { onResponse(response); if (response.results != null && response.results.size() > 0) onSuccess(response.results); if (response.hasError()) onError(response.status, response.errorMessage, response.errorException); currentResponse = response; synchronized (this) { this.notifyAll(); } } protected Response<T> currentResponse = null; /** * Get response after waiting listener, usefull for synchronous call */ public Response<T> getResponse() { return currentResponse; } }
package org.genericsystem.ir.app.gui.utils; import java.text.Collator; import java.util.function.Predicate; import org.genericsystem.api.core.Snapshot; import org.genericsystem.common.Generic; import org.genericsystem.common.Root; import org.genericsystem.cv.model.Doc; import org.genericsystem.cv.model.DocClass; import org.genericsystem.cv.model.DocClass.DocClassInstance; import org.genericsystem.cv.model.ImgFilter; import org.genericsystem.cv.model.Score; import org.genericsystem.cv.model.Score.ScoreInstance; import org.genericsystem.cv.model.ZoneGeneric; import org.genericsystem.cv.model.ZoneGeneric.ZoneInstance; import org.genericsystem.cv.model.ZoneText; import org.genericsystem.cv.model.ZoneText.ZoneTextInstance; import org.genericsystem.reactor.context.ObservableListExtractor; import io.reactivex.Observable; /** * This class contains all the {@link ObservableListExtractor} needed across the app. * * @author Pierrik Lassalas */ public class ObservableListExtractorCustom { public static class DOC_CLASS_SELECTOR implements ObservableListExtractor { @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { Root root = generics[0].getRoot(); DocClass docClass = root.find(DocClass.class); Snapshot<Generic> docClassInstances = docClass.getInstances(); if (null == docClassInstances) return Observable.just(Snapshot.empty()); return Observable.just(docClassInstances); } } public static class DOC_SELECTOR implements ObservableListExtractor { @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { DocClassInstance currentDocClass = (DocClassInstance) generics[0]; Doc doc = generics[0].getRoot().find(Doc.class); if (null == currentDocClass) return Observable.just(Snapshot.empty()); System.out.println("Current doc class : " + currentDocClass.info()); Snapshot<Generic> docInstances = currentDocClass.getHolders(doc); if (null == docInstances) return Observable.just(Snapshot.empty()); return Observable.just(docInstances); } } public static class ZONE_SELECTOR implements ObservableListExtractor { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { Generic currentDocClass = generics[0]; Root root = currentDocClass.getRoot(); System.out.println("Current docClass: " + currentDocClass.info()); Snapshot<ZoneInstance> zones = (Snapshot) currentDocClass.getHolders(root.find(ZoneGeneric.class)); if (zones == null) return Observable.just(Snapshot.empty()); return Observable.just((Snapshot) zones.sorted()); } } public static class ZONE_SELECTOR_BEST implements ObservableListExtractor { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { Generic currentDoc = generics[0]; Root root = currentDoc.getRoot(); System.out.println("Document: " + currentDoc.info()); Snapshot<ZoneTextInstance> zoneTextInstances = (Snapshot) currentDoc.getHolders(root.find(ZoneText.class)); if (zoneTextInstances == null) return Observable.just(Snapshot.empty()); return Observable.just((Snapshot) zoneTextInstances.filter(zt -> "best".equals(zt.getImgFilter().getValue())).sort((g1, g2) -> Integer.compare(g1.getZoneNum(), g2.getZoneNum()))); } } public static class ZONE_SELECTOR_REALITY implements ObservableListExtractor { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { Generic currentDoc = generics[0]; Root root = currentDoc.getRoot(); System.out.println("Document: " + currentDoc.info()); Snapshot<ZoneTextInstance> zoneTextInstances = (Snapshot) currentDoc.getHolders(root.find(ZoneText.class)); if (zoneTextInstances == null) return Observable.just(Snapshot.empty()); long start = System.nanoTime(); Snapshot<Generic> ol = (Snapshot) zoneTextInstances.filter(zt -> "reality".equals(zt.getImgFilter().getValue())).sort((g1, g2) -> Integer.compare(g1.getZoneNum(), g2.getZoneNum())); long stop = System.nanoTime(); System.out.println(" return Observable.just(ol); } } public static class DATALIST_SELECTOR implements ObservableListExtractor { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { ZoneTextInstance zti = (ZoneTextInstance) generics[0]; Generic currentDoc = generics[1]; Root root = currentDoc.getRoot(); Predicate<ZoneTextInstance> filterByZone = z -> z.getZoneNum() == zti.getZoneNum() && !z.getValue().toString().isEmpty(); Snapshot<ZoneTextInstance> zoneTextInstances = (Snapshot) currentDoc.getHolders(root.find(ZoneText.class)); return Observable.just(zoneTextInstances.filter(filterByZone).sort((g1, g2) -> Collator.getInstance().compare(g1.getValue(), g2.getValue()))); } } public static class OCR_SELECTOR implements ObservableListExtractor { @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { Root root = generics[0].getRoot(); Snapshot<Generic> filters = root.find(ImgFilter.class).getInstances(); if (filters == null) return Observable.just(Snapshot.empty()); return Observable.just(filters); } } public static class SCORE_SELECTOR implements ObservableListExtractor { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Observable<Snapshot<Generic>> apply(Generic[] generics) { ZoneInstance zoneInstance = (ZoneInstance) generics[0]; Root root = zoneInstance.getRoot(); System.out.println("Current zone: " + zoneInstance.info()); Snapshot<ScoreInstance> scores = (Snapshot) zoneInstance.getHolders(root.find(Score.class)); // scores.forEach(g -> System.out.println(g.info())); if (scores == null) return Observable.just(Snapshot.empty()); return Observable.just((Snapshot) scores); } } }
package io.hops.hopsworks.api.modelregistry.models; import io.hops.hopsworks.api.dataset.inode.InodeBuilder; import io.hops.hopsworks.api.dataset.inode.InodeDTO; import io.hops.hopsworks.api.modelregistry.dto.ModelRegistryDTO; import io.hops.hopsworks.api.modelregistry.models.dto.ModelDTO; import io.hops.hopsworks.common.api.ResourceRequest; import io.hops.hopsworks.common.dao.AbstractFacade; import io.hops.hopsworks.common.dao.hdfsUser.HdfsUsersFacade; import io.hops.hopsworks.common.dao.project.ProjectFacade; import io.hops.hopsworks.common.dao.project.team.ProjectTeamFacade; import io.hops.hopsworks.common.dao.user.UserFacade; import io.hops.hopsworks.common.dataset.FilePreviewMode; import io.hops.hopsworks.common.dataset.util.DatasetHelper; import io.hops.hopsworks.common.dataset.util.DatasetPath; import io.hops.hopsworks.common.featurestore.FeaturestoreFacade; import io.hops.hopsworks.common.hdfs.HdfsUsersController; import io.hops.hopsworks.common.provenance.core.Provenance; import io.hops.hopsworks.common.provenance.state.ProvStateParamBuilder; import io.hops.hopsworks.common.provenance.state.ProvStateParser; import io.hops.hopsworks.common.provenance.state.ProvStateController; import io.hops.hopsworks.common.provenance.state.dto.ProvStateDTO; import io.hops.hopsworks.common.provenance.util.ProvHelper; import io.hops.hopsworks.common.util.Settings; import io.hops.hopsworks.exceptions.DatasetException; import io.hops.hopsworks.exceptions.GenericException; import io.hops.hopsworks.exceptions.MetadataException; import io.hops.hopsworks.exceptions.ModelRegistryException; import io.hops.hopsworks.exceptions.ProvenanceException; import io.hops.hopsworks.exceptions.SchematizedTagException; import io.hops.hopsworks.persistence.entity.dataset.DatasetType; import io.hops.hopsworks.persistence.entity.hdfs.user.HdfsUsers; import io.hops.hopsworks.persistence.entity.project.Project; import io.hops.hopsworks.persistence.entity.project.team.ProjectTeam; import io.hops.hopsworks.persistence.entity.user.Users; import io.hops.hopsworks.restutils.RESTCodes; import org.elasticsearch.search.sort.SortOrder; import org.javatuples.Pair; import org.json.JSONObject; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ws.rs.core.UriInfo; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; @Stateless @TransactionAttribute(TransactionAttributeType.NEVER) public class ModelsBuilder { public final static String MODEL_SUMMARY_XATTR_NAME = "model_summary"; private static final Logger LOGGER = Logger.getLogger(ModelsBuilder.class.getName()); @EJB private ProvStateController provenanceController; @EJB private ModelConverter modelConverter; @EJB private Settings settings; @EJB private UserFacade userFacade; @EJB private HdfsUsersFacade hdfsUsersFacade; @EJB private HdfsUsersController hdfsUsersController; @EJB private ProjectFacade projectFacade; @EJB private ProjectTeamFacade projectTeamFacade; @EJB private FeaturestoreFacade featurestoreFacade; @EJB private ModelsController modelsController; @EJB private InodeBuilder inodeBuilder; @EJB private DatasetHelper datasetHelper; @EJB private ModelUtils modelUtils; public ModelDTO uri(ModelDTO dto, UriInfo uriInfo, Project userProject, Project modelRegistryProject) { dto.setHref(uriInfo.getBaseUriBuilder() .path(ResourceRequest.Name.PROJECT.toString().toLowerCase()) .path(Integer.toString(userProject.getId())) .path(ResourceRequest.Name.MODELREGISTRIES.toString().toLowerCase()) .path(Integer.toString(modelRegistryProject.getId())) .path(ResourceRequest.Name.MODELS.toString().toLowerCase()) .build()); return dto; } public ModelDTO uri(ModelDTO dto, UriInfo uriInfo, Project userProject, Project modelRegistryProject, ProvStateDTO fileProvenanceHit) { dto.setHref(uriInfo.getBaseUriBuilder() .path(ResourceRequest.Name.PROJECT.toString().toLowerCase()) .path(Integer.toString(userProject.getId())) .path(ResourceRequest.Name.MODELREGISTRIES.toString().toLowerCase()) .path(Integer.toString(modelRegistryProject.getId())) .path(ResourceRequest.Name.MODELS.toString().toLowerCase()) .path(fileProvenanceHit.getMlId()) .build()); return dto; } public ModelDTO expand(ModelDTO dto, ResourceRequest resourceRequest) { if (resourceRequest != null && resourceRequest.contains(ResourceRequest.Name.MODELS)) { dto.setExpand(true); } return dto; } //Build collection public ModelDTO build(UriInfo uriInfo, ResourceRequest resourceRequest, Users user, Project userProject, Project modelRegistryProject ) throws ModelRegistryException, GenericException, SchematizedTagException, MetadataException { ModelDTO dto = new ModelDTO(); uri(dto, uriInfo, userProject, modelRegistryProject); expand(dto, resourceRequest); dto.setCount(0l); if(dto.isExpand()) { validatePagination(resourceRequest); ProvStateDTO fileState; try { Pair<ProvStateParamBuilder, ModelRegistryDTO> provFilesParamBuilder = buildModelProvenanceParams(userProject, modelRegistryProject, resourceRequest); if(provFilesParamBuilder.getValue1() == null) { //no endpoint - no results return dto; } fileState = provenanceController.provFileStateList( provFilesParamBuilder.getValue1().getParentProject(), provFilesParamBuilder.getValue0()); List<ProvStateDTO> models = new LinkedList<>(fileState.getItems()); dto.setCount(fileState.getCount()); String modelsDatasetPath = modelUtils.getModelsDatasetPath(userProject, modelRegistryProject); for(ProvStateDTO fileProvStateHit: models) { ModelDTO modelDTO = build(uriInfo, resourceRequest, user, userProject, modelRegistryProject, fileProvStateHit, modelsDatasetPath); if(modelDTO != null) { dto.addItem(modelDTO); } } } catch (ProvenanceException e) { if (ProvHelper.missingMappingForField( e)) { LOGGER.log(Level.WARNING, "Could not find elastic mapping for experiments query", e); return dto; } else { throw new ModelRegistryException(RESTCodes.ModelRegistryErrorCode.MODEL_LIST_FAILED, Level.FINE, "Unable to list models for project " + modelRegistryProject.getName(), e.getMessage(), e); } } catch(DatasetException e) { throw new ModelRegistryException(RESTCodes.ModelRegistryErrorCode.MODEL_LIST_FAILED, Level.FINE, "Unable to list models for project " + modelRegistryProject.getName(), e.getMessage(), e); } } return dto; } //Build specific public ModelDTO build(UriInfo uriInfo, ResourceRequest resourceRequest, Users user, Project userProject, Project modelRegistryProject, ProvStateDTO fileProvenanceHit, String modelsFolder) throws DatasetException, ModelRegistryException, SchematizedTagException, MetadataException { ModelDTO modelDTO = new ModelDTO(); uri(modelDTO, uriInfo, userProject, modelRegistryProject, fileProvenanceHit); if (expand(modelDTO, resourceRequest).isExpand()) { if (fileProvenanceHit.getXattrs() != null && fileProvenanceHit.getXattrs().containsKey(MODEL_SUMMARY_XATTR_NAME)) { JSONObject summary = new JSONObject(fileProvenanceHit.getXattrs().get(MODEL_SUMMARY_XATTR_NAME)); ModelDTO modelSummary = modelConverter.unmarshalDescription(summary.toString()); modelDTO.setId(fileProvenanceHit.getMlId()); modelDTO.setName(modelSummary.getName()); modelDTO.setVersion(modelSummary.getVersion()); modelDTO.setUserFullName(modelSummary.getUserFullName()); modelDTO.setCreated(fileProvenanceHit.getCreateTime()); modelDTO.setMetrics(modelSummary.getMetrics()); modelDTO.setDescription(modelSummary.getDescription()); modelDTO.setProgram(modelSummary.getProgram()); modelDTO.setFramework(modelSummary.getFramework()); String modelVersionPath = modelsFolder + "/" + modelDTO.getName() + "/" + modelDTO.getVersion() + "/"; DatasetPath modelSchemaPath = datasetHelper.getDatasetPath(userProject, modelVersionPath + Settings.HOPS_MODELS_SCHEMA, DatasetType.DATASET); if(resourceRequest.contains(ResourceRequest.Name.MODELSCHEMA) && modelSchemaPath.getInode() != null) { InodeDTO modelSchemaDTO = inodeBuilder.buildBlob(uriInfo, new ResourceRequest(ResourceRequest.Name.INODES), user, modelSchemaPath, modelSchemaPath.getInode(), FilePreviewMode.HEAD); modelDTO.setModelSchema(modelSchemaDTO); } else { InodeDTO modelSchemaDTO = inodeBuilder.buildResource(uriInfo, modelRegistryProject, modelSchemaPath); modelDTO.setModelSchema(modelSchemaDTO); } DatasetPath inputExamplePath = datasetHelper.getDatasetPath(userProject, modelVersionPath + Settings.HOPS_MODELS_INPUT_EXAMPLE, DatasetType.DATASET); if(resourceRequest.contains(ResourceRequest.Name.INPUTEXAMPLE) && inputExamplePath.getInode() != null) { InodeDTO inputExampleDTO = inodeBuilder.buildBlob(uriInfo, new ResourceRequest(ResourceRequest.Name.INODES), user, inputExamplePath, inputExamplePath.getInode(), FilePreviewMode.HEAD); modelDTO.setInputExample(inputExampleDTO); } else { InodeDTO inputExampleDTO = inodeBuilder.buildResource(uriInfo, modelRegistryProject, inputExamplePath); modelDTO.setInputExample(inputExampleDTO); } modelDTO.setEnvironment(modelSummary.getEnvironment()); modelDTO.setExperimentId(modelSummary.getExperimentId()); modelDTO.setExperimentProjectName(modelSummary.getExperimentProjectName()); modelDTO.setProjectName(modelSummary.getProjectName()); } } return modelDTO; } private Pair<ProvStateParamBuilder, ModelRegistryDTO> buildFilter(Project project, Project modelRegistryProject, Set<? extends AbstractFacade.FilterBy> filters) throws GenericException, ProvenanceException, DatasetException { ProvStateParamBuilder provFilesParamBuilder = new ProvStateParamBuilder(); if(filters != null) { Users filterUser = null; Project filterUserProject = project; for (AbstractFacade.FilterBy filterBy : filters) { if(filterBy.getParam().compareToIgnoreCase(Filters.NAME_EQ.name()) == 0) { provFilesParamBuilder.filterByXAttr(MODEL_SUMMARY_XATTR_NAME + ".name", filterBy.getValue()); } else if(filterBy.getParam().compareToIgnoreCase(Filters.NAME_LIKE.name()) == 0) { provFilesParamBuilder.filterLikeXAttr(MODEL_SUMMARY_XATTR_NAME + ".name", filterBy.getValue()); } else if(filterBy.getParam().compareToIgnoreCase(Filters.VERSION.name()) == 0) { provFilesParamBuilder.filterByXAttr(MODEL_SUMMARY_XATTR_NAME + ".version", filterBy.getValue()); } else if(filterBy.getParam().compareToIgnoreCase(Filters.ID_EQ.name()) == 0) { provFilesParamBuilder.filterByXAttr(MODEL_SUMMARY_XATTR_NAME + ".id", filterBy.getValue()); } else if (filterBy.getParam().compareToIgnoreCase(Filters.USER.name()) == 0) { try { filterUser = userFacade.find(Integer.parseInt(filterBy.getValue())); } catch(NumberFormatException e) { throw new GenericException(RESTCodes.GenericErrorCode.ILLEGAL_ARGUMENT, Level.INFO, "expected int user id, found: " + filterBy.getValue()); } } else if (filterBy.getParam().compareToIgnoreCase(Filters.USER_PROJECT.name()) == 0) { try { filterUserProject = projectFacade.find(Integer.parseInt(filterBy.getValue())); } catch(NumberFormatException e) { throw new GenericException(RESTCodes.GenericErrorCode.ILLEGAL_ARGUMENT, Level.INFO, "expected int user project id, found: " + filterBy.getValue()); } } else { throw new GenericException(RESTCodes.GenericErrorCode.ILLEGAL_ARGUMENT, Level.INFO, "Filter by - found: " + filterBy.getParam() + " expected:" + EnumSet.allOf(Filters.class)); } } if(filterUser != null) { ProjectTeam member = projectTeamFacade.findByPrimaryKey(filterUserProject, filterUser); if(member == null) { throw new GenericException(RESTCodes.GenericErrorCode.ILLEGAL_ARGUMENT, Level.INFO, "Selected user: " + filterUser.getUid() + " is not part of project:" + filterUserProject.getId()); } String hdfsUserStr = hdfsUsersController.getHdfsUserName(filterUserProject, filterUser); HdfsUsers hdfsUsers = hdfsUsersFacade.findByName(hdfsUserStr); provFilesParamBuilder.filterByField(ProvStateParser.FieldsP.USER_ID, hdfsUsers.getId().toString()); } } ModelRegistryDTO modelRegistryDTO = modelsController.getModelRegistry(modelRegistryProject); provFilesParamBuilder .filterByField(ProvStateParser.FieldsP.PROJECT_I_ID, modelRegistryDTO.getParentProject().getInode().getId()) .filterByField(ProvStateParser.FieldsP.DATASET_I_ID, modelRegistryDTO.getDatasetInodeId()); return Pair.with(provFilesParamBuilder, modelRegistryDTO); } private void buildSortOrder(ProvStateParamBuilder provFilesParamBuilder, Set<? extends AbstractFacade.SortBy> sort) { if(sort != null) { for(AbstractFacade.SortBy sortBy: sort) { if(sortBy.getValue().compareToIgnoreCase(SortBy.NAME.name()) == 0) { provFilesParamBuilder.sortByXAttr(MODEL_SUMMARY_XATTR_NAME + ".name", SortOrder.valueOf(sortBy.getParam().getValue())); } else { String sortKeyName = sortBy.getValue(); String sortKeyOrder = sortBy.getParam().getValue(); provFilesParamBuilder.sortByXAttr(MODEL_SUMMARY_XATTR_NAME + ".metrics." + sortKeyName, SortOrder.valueOf(sortKeyOrder)); } } } } private void validatePagination(ResourceRequest resourceRequest) { if(resourceRequest.getLimit() == null || resourceRequest.getLimit() <= 0) { resourceRequest.setLimit(settings.getElasticDefaultScrollPageSize()); } if(resourceRequest.getOffset() == null || resourceRequest.getOffset() <= 0) { resourceRequest.setOffset(0); } } protected enum SortBy { NAME } protected enum Filters { NAME_EQ, NAME_LIKE, VERSION, ID_EQ, USER, USER_PROJECT } private Pair<ProvStateParamBuilder, ModelRegistryDTO> buildModelProvenanceParams(Project project, Project modelRegistryProject, ResourceRequest resourceRequest) throws ProvenanceException, GenericException, DatasetException { Pair<ProvStateParamBuilder, ModelRegistryDTO> builder = buildFilter(project, modelRegistryProject, resourceRequest.getFilter()); builder.getValue0() .filterByField(ProvStateParser.FieldsP.ML_TYPE, Provenance.MLType.MODEL.name()) .hasXAttr(MODEL_SUMMARY_XATTR_NAME) .paginate(resourceRequest.getOffset(), resourceRequest.getLimit()); buildSortOrder(builder.getValue0(), resourceRequest.getSort()); return builder; } }
package com.yahoo.vespa.indexinglanguage; import com.yahoo.document.*; import com.yahoo.document.fieldpathupdate.FieldPathUpdate; import com.yahoo.document.update.FieldUpdate; import com.yahoo.document.update.ValueUpdate; import com.yahoo.vespa.indexinglanguage.expressions.Expression; import java.util.ArrayList; import java.util.List; /** * @author Simon Thoresen Hult */ @SuppressWarnings("rawtypes") public class SimpleAdapterFactory implements AdapterFactory { public static class SelectExpression { public Expression selectExpression(DocumentType documentType, String fieldName) { return null; } } private final SelectExpression expressionSelector; public SimpleAdapterFactory() { this(new SelectExpression()); } public SimpleAdapterFactory(SelectExpression expressionSelector) { this.expressionSelector = expressionSelector; } @Override public DocumentAdapter newDocumentAdapter(Document doc) { return newDocumentAdapter(doc, false); } public DocumentAdapter newDocumentAdapter(Document doc, boolean isUpdate) { if (isUpdate) { return new SimpleDocumentAdapter(doc); } return new SimpleDocumentAdapter(doc, doc); } @Override public List<UpdateAdapter> newUpdateAdapterList(DocumentUpdate upd) { List<UpdateAdapter> ret = new ArrayList<>(); DocumentType docType = upd.getDocumentType(); DocumentId docId = upd.getId(); Document complete = new Document(docType, upd.getId()); for (FieldPathUpdate fieldUpd : upd) { try { if (FieldPathUpdateHelper.isComplete(fieldUpd)) { // A 'complete' field path update is basically a regular top-level field update // in wolf's clothing. Convert it to a regular field update to be friendlier // towards the search core backend. FieldPathUpdateHelper.applyUpdate(fieldUpd, complete); } else { ret.add(new IdentityFieldPathUpdateAdapter(fieldUpd, newDocumentAdapter(complete, true))); } } catch (NullPointerException e) { throw new IllegalArgumentException("Exception during handling of update '" + fieldUpd + "' to field '" + fieldUpd.getFieldPath() + "'", e); } } for (FieldUpdate fieldUpd : upd.getFieldUpdates()) { Field field = fieldUpd.getField(); for (ValueUpdate valueUpd : fieldUpd.getValueUpdates()) { try { if (FieldUpdateHelper.isComplete(field, valueUpd)) { FieldUpdateHelper.applyUpdate(field, valueUpd, complete); } else { Document partial = FieldUpdateHelper.newPartialDocument(docType, docId, field, valueUpd); ret.add(FieldUpdateAdapter.fromPartialUpdate(expressionSelector.selectExpression(docType, field.getName()), newDocumentAdapter(partial, true), valueUpd)); } } catch (NullPointerException e) { throw new IllegalArgumentException("Exception during handling of update '" + valueUpd + "' to field '" + field + "'", e); } } } ret.add(FieldUpdateAdapter.fromCompleteUpdate(newDocumentAdapter(complete, true))); return ret; } }
package org.intermine.api.query.codegen; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.OrderDirection; import org.intermine.pathquery.OrderElement; import org.intermine.pathquery.OuterJoinStatus; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintBag; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintLoop; import org.intermine.pathquery.PathConstraintMultiValue; import org.intermine.pathquery.PathConstraintSubclass; import org.intermine.pathquery.PathException; import org.intermine.pathquery.PathQuery; import org.intermine.template.TemplateQuery; import org.intermine.util.TypeUtil; /** * Class for generating Python code to run a query, using the intermine python library. * @author Alex Kalderimis * */ public class WebservicePythonCodeGenerator implements WebserviceCodeGenerator { protected static final String NULL_QUERY = "Invalid query. Query can not be null."; protected static final String INDENT = " "; protected static final String SPACE = " "; private String endl = System.getProperty("line.separator"); protected String getInvalidQuery() { StringBuffer message = new StringBuffer() .append("# Invalid query.").append(endl) .append(" .append("# This query cannot be run because of the following problems:").append(endl); return message.toString(); } private static final String DEFAULT_SO_MSG = "Uncomment and edit the line below (the default) to select a custom sort order:"; private static final String CUSTOM_SO_MSG = "This query's custom sort order is specified below:"; private static final String DEFAULT_LOGIC_MSG = "Uncomment and edit the code below to specify your own custom logic:"; private static final String CUSTOM_LOGIC_MSG = "Your custom constraint logic is specified with the code below:"; protected static final String TEMPLATE_BAG_CONSTRAINT = "This template contains a list " + "constraint, which is currently not supported."; protected static final String LOOP_CONSTRAINT = "Loop path constraint is not supported " + "at the moment..."; private String getBoilerPlate() { String boilerplate = "#!/usr/bin/env python" + endl + endl + "# This is an automatically generated script to run your query" + endl + "# to use it you will require the intermine python client." + endl + "# To install the client, run the following command from a terminal:" + endl + "#" + endl + "# sudo easy_install intermine" + endl + "#" + endl + "# For further documentation you can visit:" + endl + " + "# The following two lines will be needed in every python script:" + endl + "from intermine.webservice import Service" + endl; return boilerplate; } private static final String OUTER_JOINS_TITLE = "Outer Joins"; private static final String[] OUTER_JOINS_EXPLANATION = new String[] { "(display properties of these relations if they exist,", "but also show objects without these relationships)"}; private static final String UNHANDLED_CONSTRAINT = "It contains a constraint type that can only be used internally"; /** * This method will generate code that will run using the python webservice * client library. * * @param info a WebserviceCodeGenInfo object * @return the code as a string */ @Override public String generate(WebserviceCodeGenInfo info) { endl = info.getLineBreak(); PathQuery query = info.getQuery(); // query is null if (query == null) { return NULL_QUERY; } List<String> problems = query.verifyQuery(); if (!problems.isEmpty()) { return getInvalidQuery() + formatProblems(problems); } StringBuffer sb = new StringBuffer(getBoilerPlate()); if (info.isPublic()) { sb.append("service = Service(\"" + info.getServiceBaseURL() + "/service\")" + endl + endl); } else { sb.append("service = Service(\"" + info.getServiceBaseURL() + "\", \"YOUR-API-KEY\")" + endl + endl); } List<String> rootLessViews = new ArrayList<String>(); List<String> rowKeyAccesses = new ArrayList<String>(); for (String v: query.getView()) { rootLessViews.add(decapitate(v)); } for (String key : rootLessViews) { rowKeyAccesses.add("row[\"" + key + "\"]"); } String error = null; if (query instanceof TemplateQuery) { error = handleTemplate(sb, query); } else { error = handlePathQuery(sb, query, rootLessViews); } if (error != null) { return error; } StringBuffer currentLine = new StringBuffer(INDENT + "print"); Iterator<String> rowKeyIt = rowKeyAccesses.iterator(); while (rowKeyIt.hasNext()) { String toPrint = rowKeyIt.next(); if (StringUtils.isNotBlank(currentLine.toString())) { toPrint = " " + toPrint; } if (rowKeyIt.hasNext()) { toPrint += ","; } if (currentLine.length() + toPrint.length() > 100) { sb.append(currentLine.toString() + " \\" + endl); currentLine = new StringBuffer(INDENT + INDENT); toPrint = toPrint.substring(1); } currentLine.append(toPrint); } sb.append(currentLine.toString() + endl); return sb.toString(); } private String decapitate(String longPath) { return longPath.substring(longPath.indexOf(".") + 1); } private String handlePathQuery(StringBuffer sb, PathQuery query, List<String> rootLessViews) { if (StringUtils.isNotBlank(query.getDescription())) { sb.append("# query description - " + query.getDescription() + endl + endl); } sb.append("# Get a new query on the class (table) you will be querying:" + endl); try { sb.append("query = service.new_query(\"" + query.getRootClass() + "\")" + endl); } catch (PathException e) { // Should have been caught above... return getInvalidQuery() + formatProblems(query.verifyQuery()); } sb.append(endl); int codedQueries = 0; List<String> uncodedQueryTexts = new ArrayList<String>(); List<String> codedQueryTexts = new ArrayList<String>(); List<String> constraintProblems = new LinkedList<String>(); if (query.getConstraints() != null && !query.getConstraints().isEmpty()) { for (Entry<PathConstraint, String> entry : query.getConstraints().entrySet()) { PathConstraint pc = entry.getKey(); String constraint = ""; try { constraint = pathContraintUtil(pc, entry.getValue()); } catch (UnhandledFeatureException e) { constraintProblems.add(e.getMessage()); } if (entry.getValue() != null) { codedQueries++; codedQueryTexts.add(constraint); } else { uncodedQueryTexts.add(constraint); } } } if (!constraintProblems.isEmpty()) { return getInvalidQuery() + formatProblems(constraintProblems); } if (!uncodedQueryTexts.isEmpty()) { // Subclass constraints must come first or the query will break sb.append("# Type constraints should come early - before all mentions "); sb.append("of the paths they constrain" + endl); for (String text: uncodedQueryTexts) { sb.append(text); } sb.append(endl); } sb.append("# The view specifies the output columns" + endl); sb.append("query.add_view("); StringBuffer viewLine = new StringBuffer(); listFormatUtil(viewLine, rootLessViews); if (viewLine.toString().length() <= 74) { sb.append(viewLine.toString()); } else { sb.append(endl); printLine(sb, INDENT, viewLine.toString()); } sb.append(")" + endl + endl); // Add orderBy if (query.getOrderBy() != null && !query.getOrderBy().isEmpty()) { // no sort order if (// The default query.getOrderBy().size() == 1 && query.getOrderBy().get(0).getOrderPath().equals(query.getView().get(0)) && query.getOrderBy().get(0).getDirection() == OrderDirection.ASC) { sb.append("# " + DEFAULT_SO_MSG + endl + "# "); } else { sb.append("# " + CUSTOM_SO_MSG + endl); } for (OrderElement oe : query.getOrderBy()) { sb.append("query.add_sort_order("); sb.append("\"" + oe.getOrderPath() + "\", \"" + oe.getDirection() + "\""); sb.append(")" + endl); } sb.append(endl); } // Add constraints if (!codedQueryTexts.isEmpty()) { // Add comments for constraints sb.append("# You can edit the constraint values below" + endl); for (String text: codedQueryTexts) { sb.append(text); } sb.append(endl); // Add constraintLogic if (query.getConstraintLogic() != null && !"".equals(query.getConstraintLogic())) { String logic = query.getConstraintLogic(); if (codedQueries <= 1 || logic.indexOf("or") == -1) { sb.append("# " + DEFAULT_LOGIC_MSG + endl + "# "); } else { sb.append("# " + CUSTOM_LOGIC_MSG + endl); } sb.append("query.set_logic(\"" + logic + "\")" + endl + endl); } } if (query.getOuterJoinStatus() != null && !query.getOuterJoinStatus().isEmpty()) { List<String> outerjoinSection = generateOuterJoinSection(query.getOuterJoinStatus()); if (!outerjoinSection.isEmpty()) { sb.append("# " + OUTER_JOINS_TITLE + endl); for (String line : OUTER_JOINS_EXPLANATION) { sb.append("# " + line + endl); } for (String line : outerjoinSection) { sb.append(line + endl); } sb.append(endl); } } sb.append("for row in query.rows():" + endl); return null; } private List<String> generateOuterJoinSection( Map<String, OuterJoinStatus> outerJoinStatus) { List<String> lines = new LinkedList<String>(); for (Entry<String, OuterJoinStatus> entry : outerJoinStatus.entrySet()) { if (entry.getValue() == OuterJoinStatus.OUTER) { lines.add("query.outerjoin(\"" + decapitate(entry.getKey()) + "\")"); } } return lines; } private String handleTemplate(StringBuffer sb, PathQuery query) { String templateName = ((TemplateQuery) query).getName(); String description = ((TemplateQuery) query).getDescription(); Map<PathConstraint, String> allConstraints = query.getConstraints(); List<PathConstraint> editableConstraints = ((TemplateQuery) query) .getEditableConstraints(); if (editableConstraints == null || editableConstraints.isEmpty()) { return getInvalidQuery() + formatProblems(Arrays.asList( "This template has no editable constraints.")); } StringBuffer constraints = new StringBuffer(); StringBuffer constraintComments = new StringBuffer(); constraintComments.append("# You can edit the constraint values below" + endl); Iterator<PathConstraint> conIter = editableConstraints.iterator(); List<String> constraintProblems = new LinkedList<String>(); while (conIter.hasNext()) { PathConstraint pc = conIter.next(); // Add comments for constraints String path = pc.getPath(); String opCode = allConstraints.get(pc); constraintComments.append("# " + opCode + INDENT + path); String constraintDes = ((TemplateQuery) query).getConstraintDescription(pc); if (constraintDes == null || "".equals(constraintDes)) { constraintComments.append(endl); } else { constraintComments.append(INDENT + constraintDes + endl); } try { constraints.append(templateConstraintUtil(pc, opCode)); } catch (UnhandledFeatureException e) { constraintProblems.add(e.getMessage()); } if (conIter.hasNext()) { constraints.append(","); } constraints.append(endl); } if (!constraintProblems.isEmpty()) { return getInvalidQuery() + formatProblems(constraintProblems); } if (description != null && !"".equals(description)) { printLine(sb, "# ", description); sb.append(endl); } sb.append("template = service.get_template('" + templateName + "')" + endl + endl); sb.append(constraintComments.toString() + endl); sb.append("rows = template.rows(" + endl); sb.append(constraints.toString() + ")" + endl); sb.append("for row in rows:" + endl); return null; } private void listFormatUtil(StringBuffer sb, Collection<String> coll) { Iterator<String> it = coll.iterator(); while (it.hasNext()) { sb.append("\"" + it.next() + "\""); if (it.hasNext()) { sb.append(", "); } } } private String formatProblems(List<String> problems) { StringBuffer buf = new StringBuffer(); for (String issue: problems) { buf.append(" buf.append(issue); buf.append(endl); } return buf.toString(); } /* * Nicely format long lines */ private void printLine(StringBuffer sb, String prefix, String line) { String lineToPrint; if (prefix != null) { lineToPrint = prefix + line; } else { lineToPrint = line; } if (lineToPrint.length() > 80 && lineToPrint.lastIndexOf(' ', 80) != -1) { int lastCutPoint = lineToPrint.lastIndexOf(' ', 80); String frontPart = lineToPrint.substring(0, lastCutPoint); sb.append(frontPart + endl); String nextLine = lineToPrint.substring(lastCutPoint + 1); printLine(sb, prefix, nextLine); } else { sb.append(lineToPrint + endl); } } /** * This method helps to generate constraint source code for PathQuery * * @param pc PathConstraint object * @return a string for constraints source code * @throws UnhandledFeatureException If the constraint type cannot be represented in python. */ private String pathContraintUtil(PathConstraint pc, String code) throws UnhandledFeatureException { // Ref to Constraints StringBuffer sb = new StringBuffer("query.add_constraint("); String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String path = pc.getPath().substring(pc.getPath().indexOf(".") + 1); ConstraintOp op = pc.getOp(); sb.append("\"" + path + "\", "); if ("PathConstraintSubclass".equals(className)) { String type = ((PathConstraintSubclass) pc).getType(); sb.append("\"" + type + "\""); } else if ("PathConstraintNull".equals(className)) { sb.append("\"" + op.toString() + "\""); } else if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); sb.append("\"" + op.toString() + "\""); sb.append(", \"" + value + "\""); } else if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); sb.append('"').append(op.toString()).append('"'); sb.append(", \"").append(value).append('"'); if (extraValue != null) { sb.append(", \"").append(extraValue).append('"'); } } else if ("PathConstraintBag".equals(className)) { String list = ((PathConstraintBag) pc).getBag(); sb.append("\"" + op.toString() + "\""); sb.append(", \"" + list + "\""); } else if ("PathConstraintMultiValue".equals(className)) { sb.append("\"" + op.toString() + "\""); sb.append(", ["); Collection<String> values = ((PathConstraintMultiValue) pc).getValues(); listFormatUtil(sb, values); sb.append("]"); } else if ("PathConstraintLoop".equals(className)) { if (op.equals(ConstraintOp.EQUALS)) { sb.append("\"IS\""); } else { sb.append("\"IS NOT\""); } String loopPath = ((PathConstraintLoop) pc).getLoopPath(); sb.append(", \"" + decapitate(loopPath) + "\""); } else { throw new UnhandledFeatureException(UNHANDLED_CONSTRAINT + " (" + className + ")"); } if (code != null) { sb.append(", code = \"" + code + "\""); // kwargs } sb.append(")" + endl); return sb.toString(); } /** * This method helps to generate Template Parameters (predefined * constraints) source code for TemplateQuery * * @param pc * PathConstraint object * @param opCode * operation code * @return a line of source code */ private String templateConstraintUtil(PathConstraint pc, String opCode) throws UnhandledFeatureException { String className = TypeUtil.unqualifiedName(pc.getClass().toString()); String op = pc.getOp().toString(); String start = INDENT + opCode + " = "; if ("PathConstraintAttribute".equals(className)) { String value = ((PathConstraintAttribute) pc).getValue(); return start + "{\"op\": \"" + op + "\", \"value\": \"" + value + "\"}"; } if ("PathConstraintLookup".equals(className)) { String value = ((PathConstraintLookup) pc).getValue(); String extraValue = ((PathConstraintLookup) pc).getExtraValue(); StringBuilder sb = new StringBuilder(start) .append("{\"op\": \"LOOKUP\", \"value\": \"") .append(value) .append('"'); if (extraValue != null) { sb.append(", \"extra_value\": \"").append(extraValue).append('"'); } sb.append('}'); return sb.toString(); } if ("PathConstraintBag".equals(className)) { String value = ((PathConstraintBag) pc).getBag(); return start + "{\"op\": \"" + op + "\", \"value\": \"" + value + "\"}"; } if ("PathConstraintIds".equals(className)) { throw new UnhandledFeatureException(UNHANDLED_CONSTRAINT + " (" + className + ")"); } if ("PathConstraintMultiValue".equals(className)) { StringBuffer sb = new StringBuffer(); sb.append("["); Collection<String> values = ((PathConstraintMultiValue) pc).getValues(); listFormatUtil(sb, values); sb.append("]"); return start + "{\"op\": \"" + op + "\", \"values\": \"" + sb.toString() + "\"}"; } if ("PathConstraintNull".equals(className)) { return start + "{\"op\": \"" + op + "\"}"; } if ("PathConstraintSubclass".equals(className)) { throw new UnhandledFeatureException(UNHANDLED_CONSTRAINT + " (" + className + ")"); } if ("PathConstraintLoop".equals(className)) { throw new UnhandledFeatureException(UNHANDLED_CONSTRAINT + " (" + className + ")"); } return null; } }
package com.izforge.izpack.installer.data; import com.izforge.izpack.api.data.AutomatedInstallData; import com.izforge.izpack.api.exception.IzPackException; import com.izforge.izpack.api.merge.Mergeable; import com.izforge.izpack.api.rules.RulesEngine; import com.izforge.izpack.api.substitutor.VariableSubstitutor; import com.izforge.izpack.data.CustomData; import com.izforge.izpack.data.ExecutableFile; import com.izforge.izpack.merge.resolve.PathResolver; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.IoHelper; import com.izforge.izpack.util.PrivilegedRunner; import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipOutputStream; public class UninstallDataWriter { private static final String UNINSTALLER_CONDITION = "UNINSTALLER_CONDITION"; private static final String LOGFILE_PATH = "InstallerFrame.logfilePath"; private VariableSubstitutor variableSubstitutor; private UninstallData udata; private AutomatedInstallData installdata; private PathResolver pathResolver; private BufferedOutputStream bos; private FileOutputStream out; private ZipOutputStream outJar; private RulesEngine rules; public UninstallDataWriter(VariableSubstitutor variableSubstitutor, UninstallData udata, AutomatedInstallData installdata, PathResolver pathResolver, RulesEngine rules) { this.variableSubstitutor = variableSubstitutor; this.udata = udata; this.installdata = installdata; this.pathResolver = pathResolver; this.rules = rules; } /** * Write uninstall data. * * @return true if the infos were successfuly written, false otherwise. */ public boolean write() { try { if (!isUninstallShouldBeWriten()) { return false; } BufferedWriter extLogWriter = getExternLogFile(installdata); createOutputJar(); // We get the data List<String> files = udata.getUninstalableFilesList(); if (outJar == null) { return true; // it is allowed not to have an installer } System.out.println("[ Writing the uninstaller data ... ]"); writeJarSkeleton(installdata, pathResolver, outJar); writeFilesLog(installdata, extLogWriter, files, outJar); writeUninstallerJarFileLog(udata, outJar); writeExecutables(udata, outJar); writeAdditionalUninstallData(udata, outJar); writeScriptFiles(udata, outJar); // Cleanup outJar.flush(); outJar.close(); bos.close(); out.close(); return true; } catch (Exception err) { err.printStackTrace(); return false; } } public boolean isUninstallShouldBeWriten() { String uninstallerCondition = installdata.getInfo().getUninstallerCondition(); if (uninstallerCondition == null) { return true; } if (uninstallerCondition.length() > 0) { return true; } return this.rules.isConditionTrue(uninstallerCondition); } // Show whether a separated logfile should be also written or not. private BufferedWriter getExternLogFile(AutomatedInstallData installdata) { String logfile = installdata.getVariable(LOGFILE_PATH); BufferedWriter extLogWriter = null; if (logfile != null) { if (logfile.toLowerCase().startsWith("default")) { logfile = installdata.getInfo().getUninstallerPath() + "/install.log"; } logfile = IoHelper.translatePath(logfile, variableSubstitutor); File outFile = new File(logfile); if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } FileOutputStream out = null; try { out = new FileOutputStream(outFile); } catch (FileNotFoundException e) { Debug.trace("Cannot create logfile!"); Debug.error(e); } if (out != null) { extLogWriter = new BufferedWriter(new OutputStreamWriter(out)); } } return extLogWriter; } // We write the files log private void writeFilesLog(AutomatedInstallData installdata, BufferedWriter extLogWriter, List<String> files, ZipOutputStream outJar) throws IOException { outJar.putNextEntry(new ZipEntry("install.log")); BufferedWriter logWriter = new BufferedWriter(new OutputStreamWriter(outJar)); logWriter.write(installdata.getInstallPath()); logWriter.newLine(); Iterator<String> iter = files.iterator(); if (extLogWriter != null) { // Write intern (in uninstaller.jar) and extern log file. while (iter.hasNext()) { String txt = iter.next(); logWriter.write(txt); extLogWriter.write(txt); if (iter.hasNext()) { logWriter.newLine(); extLogWriter.newLine(); } } logWriter.flush(); extLogWriter.flush(); extLogWriter.close(); } else { while (iter.hasNext()) { String txt = iter.next(); logWriter.write(txt); if (iter.hasNext()) { logWriter.newLine(); } } logWriter.flush(); } outJar.closeEntry(); } // Write out executables to execute on uninstall private void writeExecutables(UninstallData udata, ZipOutputStream outJar) throws IOException { outJar.putNextEntry(new ZipEntry("executables")); ObjectOutputStream execStream = new ObjectOutputStream(outJar); execStream.writeInt(udata.getExecutablesList().size()); for (ExecutableFile file : udata.getExecutablesList()) { execStream.writeObject(file); } execStream.flush(); outJar.closeEntry(); } // We write the uninstaller jar file log private void writeUninstallerJarFileLog(UninstallData udata, ZipOutputStream outJar) throws IOException { BufferedWriter logWriter; outJar.putNextEntry(new ZipEntry("jarlocation.log")); logWriter = new BufferedWriter(new OutputStreamWriter(outJar)); logWriter.write(udata.getUninstallerJarFilename()); logWriter.newLine(); logWriter.write(udata.getUninstallerPath()); logWriter.flush(); outJar.closeEntry(); } // write the script files, which will // perform several complement and unindependend uninstall actions private void writeScriptFiles(UninstallData udata, ZipOutputStream outJar) throws IOException { ArrayList<String> unInstallScripts = udata.getUninstallScripts(); ObjectOutputStream rootStream; int idx = 0; for (String unInstallScript : unInstallScripts) { outJar.putNextEntry(new ZipEntry(UninstallData.ROOTSCRIPT + Integer.toString(idx))); rootStream = new ObjectOutputStream(outJar); rootStream.writeUTF(unInstallScript); rootStream.flush(); outJar.closeEntry(); idx++; } } // Write out additional uninstall data // Do not "kill" the installation if there is a problem // with custom uninstall data. Therefore log it to Debug, // but do not throw. private void writeAdditionalUninstallData(UninstallData udata, ZipOutputStream outJar) throws IOException { Map<String, Object> additionalData = udata.getAdditionalData(); if (additionalData != null && !additionalData.isEmpty()) { Set<String> exist = new HashSet<String>(); for (String key : additionalData.keySet()) { Object contents = additionalData.get(key); if ("__uninstallLibs__".equals(key)) { for (Object o : ((List) contents)) { String nativeLibName = (String) ((List) o).get(0); byte[] buffer = new byte[5120]; long bytesCopied = 0; int bytesInBuffer; outJar.putNextEntry(new ZipEntry("native/" + nativeLibName)); InputStream in = getClass().getResourceAsStream( "/native/" + nativeLibName); while ((bytesInBuffer = in.read(buffer)) != -1) { outJar.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } outJar.closeEntry(); } } else if ("uninstallerListeners".equals(key) || "uninstallerJars".equals(key)) { // It is a ArrayList of ArrayLists which contains the full // package paths of all needed class files. // First we create a new ArrayList which contains only // the full paths for the uninstall listener self; thats // the first entry of each sub ArrayList. ArrayList<String> subContents = new ArrayList<String>(); // Secound put the class into uninstaller.jar for (Object o : ((List) contents)) { byte[] buffer = new byte[5120]; long bytesCopied = 0; int bytesInBuffer; CustomData customData = (CustomData) o; // First element of the list contains the listener // class path; // remind it for later. if (customData.listenerName != null) { subContents.add(customData.listenerName); } for (String content : customData.contents) { if (exist.contains(content)) { continue; } exist.add(content); try { outJar.putNextEntry(new ZipEntry(content)); } catch (ZipException ze) { // Ignore, or ignore not ?? May be it is a // exception because // a doubled entry was tried, then we should // ignore ... Debug.trace("ZipException in writing custom data: " + ze.getMessage()); continue; } InputStream in = getClass().getResourceAsStream("/" + content); if (in != null) { while ((bytesInBuffer = in.read(buffer)) != -1) { outJar.write(buffer, 0, bytesInBuffer); bytesCopied += bytesInBuffer; } } else { Debug.trace("custom data not found: " + content); } outJar.closeEntry(); } } // Third we write the list into the // uninstaller.jar outJar.putNextEntry(new ZipEntry(key)); ObjectOutputStream objOut = new ObjectOutputStream(outJar); objOut.writeObject(subContents); objOut.flush(); outJar.closeEntry(); } else { outJar.putNextEntry(new ZipEntry(key)); if (contents instanceof ByteArrayOutputStream) { ((ByteArrayOutputStream) contents).writeTo(outJar); } else { ObjectOutputStream objOut = new ObjectOutputStream(outJar); objOut.writeObject(contents); objOut.flush(); } outJar.closeEntry(); } } } } /** * Puts the uninstaller skeleton. * * @param installdata * @param pathResolver * @param outJar * @throws Exception Description of the Exception */ public void writeJarSkeleton(AutomatedInstallData installdata, PathResolver pathResolver, ZipOutputStream outJar) throws Exception { // get the uninstaller base, returning if not found so that // installData.uninstallOutJar remains null List<Mergeable> uninstallerMerge = pathResolver.getMergeableFromPath("com/izforge/izpack/uninstaller/"); uninstallerMerge.addAll(pathResolver.getMergeableFromPath("uninstaller-META-INF/", "META-INF/")); uninstallerMerge.addAll(pathResolver.getMergeableFromPath("com/izforge/izpack/api/")); uninstallerMerge.addAll(pathResolver.getMergeableFromPath("com/izforge/izpack/util/")); uninstallerMerge.addAll(pathResolver.getMergeableFromPath("com/izforge/izpack/gui/")); uninstallerMerge.addAll(pathResolver.getMergeableFromPath("img/")); // The uninstaller extension is facultative; it will be exist only // if a native library was marked for uninstallation. // REFACTOR Change uninstaller methods of merge and get // Me make the .uninstaller directory // We copy the uninstallers for (Mergeable mergeable : uninstallerMerge) { mergeable.merge(outJar); } // Should we relaunch the uninstaller with privileges? if (PrivilegedRunner.isPrivilegedMode() && installdata.getInfo().isPrivilegedExecutionRequiredUninstaller()) { outJar.putNextEntry(new ZipEntry("exec-admin")); outJar.closeEntry(); } // We put the langpack List<Mergeable> langPack = pathResolver.getMergeableFromPath("resources/langpacks/" + installdata.getLocaleISO3() + ".xml", "langpack.xml"); System.out.println(">>> Langpacks"); for (Mergeable mergeable : langPack) { System.out.println(">>> " + langPack); mergeable.merge(outJar); } } private void createOutputJar() { // Me make the .uninstaller directory String dest = IoHelper.translatePath(installdata.getInfo().getUninstallerPath(), variableSubstitutor); String jar = dest + File.separator + installdata.getInfo().getUninstallerName(); File pathMaker = new File(dest); pathMaker.mkdirs(); // We log the uninstaller deletion information udata.setUninstallerJarFilename(jar); udata.setUninstallerPath(dest); // We open our final jar file try { out = new FileOutputStream(jar); } catch (FileNotFoundException e) { throw new IzPackException("Problem writing uninstaller jar", e); } // Intersect a buffer else byte for byte will be written to the file. bos = new BufferedOutputStream(out); outJar = new ZipOutputStream(bos); outJar.setLevel(9); udata.addFile(jar, true); } }
package com.exedio.dsmf; public class ConstraintTest extends SchemaTest { private static final Class CHECK = CheckConstraint.class; private static final Class PK = PrimaryKeyConstraint.class; private static final Class FK = ForeignKeyConstraint.class; private static final Class UNIQUE = UniqueConstraint.class; private static final String TABLE = "ConstraintTable"; private static final String NOT_NULL_COLUMN = "notNull"; private static final String NOT_NULL_NAME = "notNullId"; private static final String CHECK_COLUMN = "check"; private static final String CHECK_NAME = "check"; private static final String PK_COLUMN = "primaryKey"; private static final String PK_NAME = "primaryKeyId"; protected Schema getSchema() { final Schema result = newSchema(); { final Table table = new Table(result, TABLE); if(supportsCheckConstraints) { new Column(table, NOT_NULL_COLUMN, stringType); new CheckConstraint(table, NOT_NULL_NAME, p(NOT_NULL_COLUMN)+" IS NOT NULL"); new Column(table, CHECK_COLUMN, stringType); new CheckConstraint(table, CHECK_NAME, "("+p(CHECK_COLUMN)+" IS NOT NULL) AND ("+p(CHECK_COLUMN)+" IN (0,1))"); } new Column(table, PK_COLUMN, stringType); new PrimaryKeyConstraint(table, PK_NAME, PK_COLUMN); new Column(table, "someItem", stringType); { final Table targetTable = new Table(result, "EmptyItem"); new Column(targetTable, "thus", stringType); new PrimaryKeyConstraint(targetTable, "EmptyItem_Pk", "thus"); } new ForeignKeyConstraint(table, "AttributeItem_someItem_Fk", "someItem", "EmptyItem", "thus"); new Column(table, "uniqueString", stringType); new UniqueConstraint(table, "ItemWithSingUni_unStr_Unq", "("+p("uniqueString")+")"); new Column(table, "string", stringType); new Column(table, "integer", intType); new UniqueConstraint(table, "ItemWithDoubUni_doUni_Unq", "("+p("string")+","+p("integer")+")"); } return result; } public void testConstraints() { final Schema schema = getVerifiedSchema(); final Table attributeItem = schema.getTable(TABLE); assertNotNull(attributeItem); assertEquals(null, attributeItem.getError()); assertEquals(Schema.COLOR_OK, attributeItem.getParticularColor()); assertCheckConstraint(attributeItem, NOT_NULL_NAME, p(NOT_NULL_COLUMN)+" IS NOT NULL"); assertCheckConstraint(attributeItem, CHECK_NAME, "("+p(CHECK_COLUMN)+" IS NOT NULL) AND ("+p(CHECK_COLUMN)+" IN (0,1))"); assertPkConstraint(attributeItem, PK_NAME, null, PK_COLUMN); assertFkConstraint(attributeItem, "AttributeItem_someItem_Fk", "someItem", "EmptyItem", "thus"); assertUniqueConstraint(attributeItem, "ItemWithSingUni_unStr_Unq", "("+p("uniqueString")+")"); assertUniqueConstraint(attributeItem, "ItemWithDoubUni_doUni_Unq", "("+p("string")+","+p("integer")+")"); } private void assertCheckConstraint(final Table table, final String constraintName, final String requiredCondition) { final CheckConstraint constraint = (CheckConstraint)assertConstraint(table, CHECK, constraintName, requiredCondition); } private void assertPkConstraint(final Table table, final String constraintName, final String requiredCondition, final String primaryKeyColumn) { final PrimaryKeyConstraint constraint = (PrimaryKeyConstraint)assertConstraint(table, PK, constraintName, requiredCondition); assertEquals(primaryKeyColumn, constraint.getPrimaryKeyColumn()); } private void assertFkConstraint(final Table table, final String constraintName, final String foreignKeyColumn, final String targetTable, final String targetColumn) { final ForeignKeyConstraint constraint = (ForeignKeyConstraint)assertConstraint(table, FK, constraintName, null); assertEquals(foreignKeyColumn, constraint.getForeignKeyColumn()); assertEquals(targetTable, constraint.getTargetTable()); assertEquals(targetColumn, constraint.getTargetColumn()); } private void assertUniqueConstraint(final Table table, final String constraintName, final String clause) { final UniqueConstraint constraint = (UniqueConstraint)assertConstraint(table, UNIQUE, constraintName, clause); assertEquals(clause, constraint.getClause()); } private Constraint assertConstraint(final Table table, final Class constraintType, final String constraintName, final String requiredCondition) { final Constraint constraint = table.getConstraint(constraintName); if(supportsCheckConstraints || constraintType!=CHECK) { assertNotNull("no such constraint "+constraintName+", but has "+table.getConstraints(), constraint); assertEquals(constraintName, constraintType, constraint.getClass()); assertEquals(constraintName, requiredCondition, constraint.getRequiredCondition()); assertEquals(constraintName, null, constraint.getError()); assertEquals(constraintName, Schema.COLOR_OK, constraint.getParticularColor()); } else assertEquals(constraintName, null, constraint); return constraint; } }
package com.intellij.psi.impl.search; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.lang.LighterAST; import com.intellij.lang.LighterASTNode; import com.intellij.lang.ParserDefinition; import com.intellij.lang.java.JavaParserDefinition; import com.intellij.lang.java.lexer.JavaLexer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiKeyword; import com.intellij.psi.impl.source.JavaLightTreeUtil; import com.intellij.psi.impl.source.tree.ElementType; import com.intellij.psi.impl.source.tree.LightTreeUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.IntArrayList; import com.intellij.util.indexing.*; import com.intellij.util.io.DataInputOutputUtil; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import com.intellij.util.text.StringSearcher; import gnu.trove.THashMap; import gnu.trove.TIntArrayList; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.*; import static com.intellij.psi.impl.source.tree.JavaElementType.*; public class JavaNullMethodArgumentIndex extends ScalarIndexExtension<JavaNullMethodArgumentIndex.MethodCallData> implements PsiDependentIndex { private static final Logger LOG = Logger.getInstance(JavaNullMethodArgumentIndex.class); public static final ID<MethodCallData, Void> INDEX_ID = ID.create("java.null.method.argument"); private interface Lazy { TokenSet CALL_TYPES = TokenSet.create(METHOD_CALL_EXPRESSION, NEW_EXPRESSION, ANONYMOUS_CLASS); TIntHashSet WHITE_SPACE_OR_EOL_SYMBOLS = new TIntHashSet(new int[]{' ', '\n', '\r', '\t', '\f'}); TIntHashSet STOP_SYMBOLS = new TIntHashSet(new int[]{'(', ',', ')', '/'}); } private final boolean myOfflineMode = ApplicationManager.getApplication().isCommandLine() && !ApplicationManager.getApplication().isUnitTestMode(); @NotNull @Override public ID<MethodCallData, Void> getName() { return INDEX_ID; } @NotNull @Override public DataIndexer<MethodCallData, Void, FileContent> getIndexer() { return inputData -> { if (myOfflineMode) { return Collections.emptyMap(); } LighterAST lighterAst = ((PsiDependentFileContent)inputData).getLighterAST(); CharSequence text = inputData.getContentAsText(); Set<LighterASTNode> calls = findCallsWithNulls(lighterAst, text); if (calls.isEmpty()) return Collections.emptyMap(); Map<MethodCallData, Void> result = new THashMap<>(); for (LighterASTNode element : calls) { final IntArrayList indices = getNullParameterIndices(lighterAst, element); if (indices != null) { final String name = getMethodName(lighterAst, element, element.getTokenType()); if (name != null) { for (int i = 0; i < indices.size(); i++) { result.put(new MethodCallData(name, indices.get(i)), null); } } } } return result; }; } private static boolean containsStopSymbol(int startIndex, @NotNull CharSequence text, boolean leftDirection) { int i = startIndex; while (true) { if (leftDirection) i--; else i++; if (leftDirection) { if (i < 0) return false; } else { if (i >= text.length()) return false; } char c = text.charAt(i); if (Lazy.STOP_SYMBOLS.contains(c)) return true; if (!Lazy.WHITE_SPACE_OR_EOL_SYMBOLS.contains(c) && !Character.isWhitespace(c)) { return false; } } } @NotNull private static Set<LighterASTNode> findCallsWithNulls(@NotNull LighterAST lighterAst, @NotNull CharSequence text) { Set<LighterASTNode> calls = new HashSet<>(); TIntArrayList occurrences = new TIntArrayList(); new StringSearcher(PsiKeyword.NULL, true, true).processOccurrences(text, idx -> { if (containsStopSymbol(idx, text, true) && containsStopSymbol(idx + 3, text, false)) { occurrences.add(idx); } return true; }); LightTreeUtil.processLeavesAtOffsets(occurrences.toNativeArray(), lighterAst, (leaf, offset) -> { LighterASTNode literal = leaf == null ? null : lighterAst.getParent(leaf); if (isNullLiteral(lighterAst, literal)) { LighterASTNode exprList = lighterAst.getParent(literal); if (exprList != null && exprList.getTokenType() == EXPRESSION_LIST) { ContainerUtil.addIfNotNull(calls, LightTreeUtil.getParentOfType(lighterAst, exprList, Lazy.CALL_TYPES, ElementType.MEMBER_BIT_SET)); } } }); return calls; } @Nullable private static IntArrayList getNullParameterIndices(LighterAST lighterAst, @NotNull LighterASTNode methodCall) { final LighterASTNode node = LightTreeUtil.firstChildOfType(lighterAst, methodCall, EXPRESSION_LIST); if (node == null) return null; final List<LighterASTNode> parameters = JavaLightTreeUtil.getExpressionChildren(lighterAst, node); IntArrayList indices = new IntArrayList(1); for (int idx = 0; idx < parameters.size(); idx++) { if (isNullLiteral(lighterAst, parameters.get(idx))) { indices.add(idx); } } return indices; } private static boolean isNullLiteral(LighterAST lighterAst, @Nullable LighterASTNode expr) { return expr != null && expr.getTokenType() == LITERAL_EXPRESSION && lighterAst.getChildren(expr).get(0).getTokenType() == JavaTokenType.NULL_KEYWORD; } @Nullable private static String getMethodName(LighterAST lighterAst, @NotNull LighterASTNode call, IElementType elementType) { if (elementType == NEW_EXPRESSION || elementType == ANONYMOUS_CLASS) { final List<LighterASTNode> refs = LightTreeUtil.getChildrenOfType(lighterAst, call, JAVA_CODE_REFERENCE); if (refs.isEmpty()) return null; final LighterASTNode lastRef = refs.get(refs.size() - 1); return JavaLightTreeUtil.getNameIdentifierText(lighterAst, lastRef); } LOG.assertTrue(elementType == METHOD_CALL_EXPRESSION); final LighterASTNode methodReference = lighterAst.getChildren(call).get(0); if (methodReference.getTokenType() == REFERENCE_EXPRESSION) { return JavaLightTreeUtil.getNameIdentifierText(lighterAst, methodReference); } return null; } @NotNull @Override public KeyDescriptor<MethodCallData> getKeyDescriptor() { return new KeyDescriptor<MethodCallData>() { @Override public int getHashCode(MethodCallData value) { return value.hashCode(); } @Override public boolean isEqual(MethodCallData val1, MethodCallData val2) { return val1.equals(val2); } @Override public void save(@NotNull DataOutput out, MethodCallData value) throws IOException { EnumeratorStringDescriptor.INSTANCE.save(out, value.getMethodName()); DataInputOutputUtil.writeINT(out, value.getNullParameterIndex()); } @Override public MethodCallData read(@NotNull DataInput in) throws IOException { return new MethodCallData(EnumeratorStringDescriptor.INSTANCE.read(in), DataInputOutputUtil.readINT(in)); } }; } @Override public int getVersion() { return 0; } @NotNull @Override public FileBasedIndex.InputFilter getInputFilter() { return new DefaultFileTypeSpecificInputFilter(JavaFileType.INSTANCE) { @Override public boolean acceptInput(@NotNull VirtualFile file) { return JavaParserDefinition.JAVA_FILE.shouldBuildStubFor(file); } }; } @Override public boolean dependsOnFileContent() { return true; } public static final class MethodCallData { @NotNull private final String myMethodName; private final int myNullParameterIndex; public MethodCallData(@NotNull String name, int index) { myMethodName = name; myNullParameterIndex = index; } @NotNull public String getMethodName() { return myMethodName; } public int getNullParameterIndex() { return myNullParameterIndex; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MethodCallData data = (MethodCallData)o; if (myNullParameterIndex != data.myNullParameterIndex) return false; if (!myMethodName.equals(data.myMethodName)) return false; return true; } @Override public int hashCode() { int result = myMethodName.hashCode(); result = 31 * result + myNullParameterIndex; return result; } @Override public String toString() { return "MethodCallData{" + "myMethodName='" + myMethodName + '\'' + ", myNullParameterIndex=" + myNullParameterIndex + '}'; } } }
package jsettlers.main.swing.menu.joinpanel; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import jsettlers.common.ai.EPlayerType; import jsettlers.common.menu.ENetworkMessage; import jsettlers.common.menu.EProgressState; import jsettlers.common.menu.IChatMessageListener; import jsettlers.common.menu.IJoinPhaseMultiplayerGameConnector; import jsettlers.common.menu.IJoiningGame; import jsettlers.common.menu.IJoiningGameListener; import jsettlers.common.menu.IMultiplayerConnector; import jsettlers.common.menu.IMultiplayerListener; import jsettlers.common.menu.IMultiplayerPlayer; import jsettlers.common.menu.IStartingGame; import jsettlers.common.utils.collections.ChangingList; import jsettlers.graphics.localization.Labels; import jsettlers.graphics.startscreen.SettingsManager; import jsettlers.logic.map.loading.EMapStartResources; import jsettlers.logic.map.loading.MapLoader; import jsettlers.logic.player.PlayerSetting; import jsettlers.main.JSettlersGame; import jsettlers.main.swing.JSettlersFrame; import jsettlers.main.swing.JSettlersSwingUtil; import jsettlers.main.swing.lookandfeel.ELFStyle; import jsettlers.main.swing.lookandfeel.components.BackgroundPanel; import jsettlers.main.swing.menu.joinpanel.slots.PlayerSlot; import jsettlers.main.swing.menu.joinpanel.slots.SlotToggleGroup; import jsettlers.main.swing.menu.joinpanel.slots.factories.ClientOfMultiplayerPlayerSlotFactory; import jsettlers.main.swing.menu.joinpanel.slots.factories.HostOfMultiplayerPlayerSlotFactory; import jsettlers.main.swing.menu.joinpanel.slots.factories.IPlayerSlotFactory; import jsettlers.main.swing.menu.joinpanel.slots.factories.SinglePlayerSlotFactory; import java8.util.J8Arrays; /** * @author codingberlin */ public class JoinGamePanel extends BackgroundPanel { private static final long serialVersionUID = -1186791399814385303L; private final JSettlersFrame settlersFrame; private final JLabel titleLabel = new JLabel(); private final JPanel contentPanel = new JPanel(); private final JPanel westPanel = new JPanel(); private final JPanel mapPanel = new JPanel(); private final JPanel settingsPanel = new JPanel(); private final JPanel centerPanel = new JPanel(); private final JLabel mapNameLabel = new JLabel(); private final JLabel mapImage = new JLabel(); private final JLabel numberOfPlayersLabel = new JLabel(); private final JComboBox<Integer> numberOfPlayersComboBox = new JComboBox<>(); private final JLabel peaceTimeLabel = new JLabel(); private final JComboBox<EPeaceTime> peaceTimeComboBox = new JComboBox<>(); private final JLabel startResourcesLabel = new JLabel(); private final JComboBox<MapStartResourcesUIWrapper> startResourcesComboBox = new JComboBox<>(); private final JPanel playerSlotsPanel = new JPanel(); private final JButton cancelButton = new JButton(); private final JButton startGameButton = new JButton(); private final JLabel slotsHeadlinePlayerNameLabel = new JLabel(); private final JLabel slotsHeadlineCivilisation = new JLabel(); private final JLabel slotsHeadlineType = new JLabel(); private final JLabel slotsHeadlineMapSlot = new JLabel(); private final JLabel slotsHeadlineTeam = new JLabel(); private final JTextField chatInputField = new JTextField(); private final JTextArea chatArea = new JTextArea(); private final JButton sendChatMessageButton = new JButton(); private MapLoader mapLoader; private final List<PlayerSlot> playerSlots = new Vector<>(); private IPlayerSlotFactory playerSlotFactory; public JoinGamePanel(JSettlersFrame settlersFrame) { this.settlersFrame = settlersFrame; createStructure(); setStyle(); localize(); addListener(); } private void createStructure() { add(contentPanel); contentPanel.setLayout(new BorderLayout(30, 30)); JPanel titleLabelWrapper = new JPanel(); contentPanel.add(titleLabelWrapper, BorderLayout.NORTH); titleLabelWrapper.add(titleLabel); titleLabel.setHorizontalAlignment(SwingConstants.CENTER); contentPanel.add(westPanel, BorderLayout.WEST); contentPanel.add(centerPanel, BorderLayout.CENTER); westPanel.setLayout(new BorderLayout()); westPanel.add(mapPanel, BorderLayout.NORTH); JPanel settingsPanelWrapper = new JPanel(); westPanel.add(settingsPanelWrapper, BorderLayout.CENTER); settingsPanelWrapper.add(settingsPanel); settingsPanel.setLayout(new GridLayout(0, 2, 20, 20)); mapPanel.setLayout(new BorderLayout()); JPanel mapNameLabelWrapper = new JPanel(); mapPanel.add(mapNameLabelWrapper, BorderLayout.NORTH); mapNameLabelWrapper.add(mapNameLabel); mapNameLabel.setHorizontalAlignment(SwingConstants.CENTER); mapPanel.add(mapImage, BorderLayout.CENTER); mapImage.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); settingsPanel.add(numberOfPlayersLabel); settingsPanel.add(numberOfPlayersComboBox); settingsPanel.add(startResourcesLabel); settingsPanel.add(startResourcesComboBox); settingsPanel.add(peaceTimeLabel); settingsPanel.add(peaceTimeComboBox); centerPanel.setLayout(new BorderLayout(0, 30)); sendChatMessageButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 15)); JPanel chatPanel = new JPanel(); chatPanel.setLayout(new BorderLayout(0, 10)); JPanel chatInputPanel = new JPanel(); chatInputPanel.setLayout(new BorderLayout(10, 0)); chatPanel.add(chatArea, BorderLayout.CENTER); chatPanel.add(chatInputPanel, BorderLayout.SOUTH); chatInputPanel.add(chatInputField, BorderLayout.CENTER); chatInputPanel.add(sendChatMessageButton, BorderLayout.EAST); centerPanel.add(chatPanel, BorderLayout.CENTER); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.setLayout(new GridBagLayout()); JScrollPane playerSlotPanelWrapper = new JScrollPane(playerSlotsPanel); playerSlotsPanel.setBorder(new EmptyBorder(20, 25, 20, 20)); centerPanel.add(playerSlotPanelWrapper, BorderLayout.NORTH); JPanel southPanelWrapper = new JPanel(); contentPanel.add(southPanelWrapper, BorderLayout.SOUTH); JPanel southPanel = new JPanel(); southPanel.setLayout(new GridLayout(0, 3, 20, 20)); southPanelWrapper.add(southPanel); cancelButton.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 15)); southPanel.add(cancelButton); startGameButton.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 15)); southPanel.add(startGameButton); } private void setStyle() { mapNameLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_LONG); numberOfPlayersLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_SHORT); startResourcesLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_SHORT); peaceTimeLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_SHORT); titleLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_HEADER); cancelButton.putClientProperty(ELFStyle.KEY, ELFStyle.BUTTON_MENU); startGameButton.putClientProperty(ELFStyle.KEY, ELFStyle.BUTTON_MENU); slotsHeadlinePlayerNameLabel.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_DYNAMIC); slotsHeadlineCivilisation.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_DYNAMIC); slotsHeadlineType.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_DYNAMIC); slotsHeadlineMapSlot.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_DYNAMIC); slotsHeadlineTeam.putClientProperty(ELFStyle.KEY, ELFStyle.LABEL_DYNAMIC); sendChatMessageButton.putClientProperty(ELFStyle.KEY, ELFStyle.BUTTON_MENU); chatInputField.putClientProperty(ELFStyle.KEY, ELFStyle.TEXT_DEFAULT); chatArea.putClientProperty(ELFStyle.KEY, ELFStyle.PANEL_DARK); startResourcesComboBox.putClientProperty(ELFStyle.KEY, ELFStyle.COMBOBOX); numberOfPlayersComboBox.putClientProperty(ELFStyle.KEY, ELFStyle.COMBOBOX); peaceTimeComboBox.putClientProperty(ELFStyle.KEY, ELFStyle.COMBOBOX); chatArea.putClientProperty(ELFStyle.KEY, ELFStyle.TEXT_DEFAULT); SwingUtilities.updateComponentTreeUI(this); } private void localize() { numberOfPlayersLabel.setText(Labels.getString("join-game-panel-number-of-players")); startResourcesLabel.setText(Labels.getString("join-game-panel-start-resources")); cancelButton.setText(Labels.getString("join-game-panel-cancel")); startGameButton.setText(Labels.getString("join-game-panel-start")); peaceTimeLabel.setText(Labels.getString("join-game-panel-peace-time")); slotsHeadlinePlayerNameLabel.setText(Labels.getString("join-game-panel-player-name")); slotsHeadlineCivilisation.setText(Labels.getString("join-game-panel-civilisation")); slotsHeadlineType.setText(Labels.getString("join-game-panel-player-type")); slotsHeadlineMapSlot.setText(Labels.getString("join-game-panel-map-slot")); slotsHeadlineTeam.setText(Labels.getString("join-game-panel-team")); sendChatMessageButton.setText(Labels.getString("join-game-panel-send-chat-message")); } private void addListener() { numberOfPlayersComboBox.addActionListener(e -> updateNumberOfPlayerSlots()); } public void setSinglePlayerMap(MapLoader mapLoader) { this.playerSlotFactory = new SinglePlayerSlotFactory(); titleLabel.setText(Labels.getString("join-game-panel-new-single-player-game-title")); numberOfPlayersComboBox.setEnabled(true); peaceTimeComboBox.setEnabled(true); startResourcesComboBox.setEnabled(true); startGameButton.setVisible(true); setChatVisible(false); cancelButton.addActionListener(e -> settlersFrame.showMainMenu()); setStartButtonActionListener(e -> { long randomSeed = System.currentTimeMillis(); PlayerSetting[] playerSettings = playerSlots.stream() .sorted((playerSlot, otherPlayerSlot) -> playerSlot.getSlot() - otherPlayerSlot.getSlot()) .map(playerSlot -> { if (playerSlot.isAvailable()) { return new PlayerSetting(playerSlot.getPlayerType(), playerSlot.getCivilisation(), playerSlot.getTeam()); } else { return new PlayerSetting(); } }) .toArray(PlayerSetting[]::new); JSettlersGame game = new JSettlersGame(mapLoader, randomSeed, playerSlots.get(0).getSlot(), playerSettings); IStartingGame startingGame = game.start(); settlersFrame.showStartingGamePanel(startingGame); }); setCancelButtonActionListener(e -> settlersFrame.showMainMenu()); prepareUiFor(mapLoader); } public void setNewMultiPlayerMap(MapLoader mapLoader, IMultiplayerConnector connector) { this.playerSlotFactory = new HostOfMultiplayerPlayerSlotFactory(); titleLabel.setText(Labels.getString("join-game-panel-new-multi-player-game-title")); numberOfPlayersComboBox.setEnabled(false); peaceTimeComboBox.setEnabled(false); startResourcesComboBox.setEnabled(false); startGameButton.setVisible(true); setChatVisible(true); setStartButtonActionListener(e -> { }); IJoiningGame joiningGame = connector.openNewMultiplayerGame(new OpenMultiPlayerGameInfo(mapLoader)); joiningGame.setListener(new IJoiningGameListener() { @Override public void joinProgressChanged(EProgressState state, float progress) { } @Override public void gameJoined(IJoinPhaseMultiplayerGameConnector connector) { SwingUtilities.invokeLater(() -> { initializeChatFor(connector); setStartButtonActionListener(e -> connector.startGame()); connector.getPlayers().setListener(changingPlayers -> onPlayersChanges(changingPlayers, connector)); connector.setMultiplayerListener(new IMultiplayerListener() { @Override public void gameIsStarting(IStartingGame game) { settlersFrame.showStartingGamePanel(game); } @Override public void gameAborted() { settlersFrame.showMainMenu(); } }); onPlayersChanges(connector.getPlayers(), connector); // init the UI with the players }); } }); setCancelButtonActionListener(e -> { joiningGame.abort(); settlersFrame.showMainMenu(); }); prepareUiFor(mapLoader); } public void setJoinMultiPlayerMap(IJoinPhaseMultiplayerGameConnector joinMultiPlayerMap, MapLoader mapLoader) { playerSlotFactory = new ClientOfMultiplayerPlayerSlotFactory(); titleLabel.setText(Labels.getString("join-game-panel-join-multi-player-game-title")); numberOfPlayersComboBox.setEnabled(false); peaceTimeComboBox.setEnabled(false); startResourcesComboBox.setEnabled(false); setChatVisible(true); cancelButton.addActionListener(e -> settlersFrame.showMainMenu()); startGameButton.setVisible(false); prepareUiFor(mapLoader); joinMultiPlayerMap.getPlayers().setListener(changingPlayers -> onPlayersChanges(changingPlayers, joinMultiPlayerMap)); joinMultiPlayerMap.setMultiplayerListener(new IMultiplayerListener() { @Override public void gameIsStarting(IStartingGame game) { settlersFrame.showStartingGamePanel(game); } @Override public void gameAborted() { settlersFrame.showMainMenu(); } }); initializeChatFor(joinMultiPlayerMap); onPlayersChanges(joinMultiPlayerMap.getPlayers(), joinMultiPlayerMap); // init the UI with the players } private void initializeChatFor(IJoinPhaseMultiplayerGameConnector joinMultiPlayerMap) { joinMultiPlayerMap.setChatListener(new IChatMessageListener() { @Override public void chatMessageReceived(String authorId, String message) { chatArea.append(authorId + ": " + message + "\n"); } @Override public void systemMessageReceived(IMultiplayerPlayer author, ENetworkMessage message) { chatArea.append(Labels.getString("network-message-" + message.name()) + "\n"); } }); ActionListener sendChatMessage = e -> { String message = chatInputField.getText(); if (!message.equals("")) { joinMultiPlayerMap.sendChatMessage(message); chatInputField.setText(""); } }; J8Arrays.stream(sendChatMessageButton.getActionListeners()).forEach(sendChatMessageButton::removeActionListener); J8Arrays.stream(chatInputField.getActionListeners()).forEach(chatInputField::removeActionListener); sendChatMessageButton.addActionListener(sendChatMessage); chatInputField.addActionListener(sendChatMessage); } private void setChatVisible(boolean isVisible) { chatArea.setVisible(isVisible); chatInputField.setVisible(isVisible); sendChatMessageButton.setVisible(isVisible); chatArea.setText(""); chatInputField.setText(""); } private void onPlayersChanges(ChangingList<? extends IMultiplayerPlayer> changingPlayers, IJoinPhaseMultiplayerGameConnector joinMultiPlayerMap) { SwingUtilities.invokeLater(() -> { List<? extends IMultiplayerPlayer> players = changingPlayers.getItems(); String myId = SettingsManager.getInstance().get(SettingsManager.SETTING_UUID); for (int i = 0; i < players.size(); i++) { PlayerSlot playerSlot = playerSlots.get(i); IMultiplayerPlayer player = players.get(i); playerSlot.setPlayerName(player.getName()); playerSlot.setReady(player.isReady()); playerSlot.setPlayerType(EPlayerType.HUMAN, false); if (player.getId().equals(myId)) { playerSlot.setReadyButtonEnabled(true); playerSlot.informGameAboutReady(joinMultiPlayerMap); } else { playerSlot.setReadyButtonEnabled(false); } } for (int i = players.size(); i < playerSlots.size(); i++) { playerSlots.get(i).setPlayerType(EPlayerType.AI_VERY_HARD, false); } setCancelButtonActionListener(e -> { joinMultiPlayerMap.abort(); settlersFrame.showMainMenu(); }); }); } private void prepareUiFor(MapLoader mapLoader) { this.mapLoader = mapLoader; mapNameLabel.setText(mapLoader.getMapName()); mapImage.setIcon(new ImageIcon(JSettlersSwingUtil.createBufferedImageFrom(mapLoader))); peaceTimeComboBox.removeAllItems(); peaceTimeComboBox.addItem(EPeaceTime.WITHOUT); startResourcesComboBox.removeAllItems(); J8Arrays.stream(EMapStartResources.values()) .map(MapStartResourcesUIWrapper::new) .forEach(startResourcesComboBox::addItem); startResourcesComboBox.setSelectedIndex(EMapStartResources.HIGH_GOODS.value - 1); resetNumberOfPlayersComboBox(); buildPlayerSlots(); updateNumberOfPlayerSlots(); } private void buildPlayerSlots() { int maximumNumberOfPlayers = this.mapLoader.getMaxPlayers(); playerSlots.clear(); for (byte i = 0; i < maximumNumberOfPlayers; i++) { PlayerSlot playerSlot = playerSlotFactory.createPlayerSlot(i, this.mapLoader); playerSlots.add(playerSlot); } PlayerSetting[] playerSettings = mapLoader.getFileHeader().getPlayerSettings(); for (byte i = 0; i < playerSlots.size(); i++) { PlayerSlot playerSlot = playerSlots.get(i); PlayerSetting playerSetting = playerSettings[i]; playerSlot.setSlot(i); if (playerSetting.getTeamId() != null) { playerSlot.setTeam(playerSetting.getTeamId(), false); } else { playerSlot.setTeam(i); } if (playerSetting.getCivilisation() != null) { playerSlot.setCivilisation(playerSetting.getCivilisation(), false); } if (playerSetting.getPlayerType() != null) { playerSlot.setPlayerType(playerSetting.getPlayerType(), false); } } } private void setStartButtonActionListener(ActionListener actionListener) { ActionListener[] actionListeners = startGameButton.getActionListeners(); J8Arrays.stream(actionListeners).forEach(startGameButton::removeActionListener); startGameButton.addActionListener(actionListener); } private void setCancelButtonActionListener(ActionListener actionListener) { ActionListener[] actionListeners = cancelButton.getActionListeners(); J8Arrays.stream(actionListeners).forEach(cancelButton::removeActionListener); cancelButton.addActionListener(actionListener); } private void resetNumberOfPlayersComboBox() { numberOfPlayersComboBox.removeAllItems(); for (int i = 1; i < mapLoader.getMaxPlayers() + 1; i++) { numberOfPlayersComboBox.addItem(i); } numberOfPlayersComboBox.setSelectedIndex(mapLoader.getMaxPlayers() - 1); } private void updateNumberOfPlayerSlots() { if (playerSlotFactory == null || numberOfPlayersComboBox.getSelectedItem() == null) { return; } playerSlotsPanel.removeAll(); addPlayerSlotHeadline(); for (int i = 0; i < playerSlots.size(); i++) { if (i < (int) numberOfPlayersComboBox.getSelectedItem()) { playerSlots.get(i).addTo(playerSlotsPanel, i + 1); } else { playerSlots.get(i).setAvailable(false); } } SwingUtilities.updateComponentTreeUI(playerSlotsPanel); SlotToggleGroup slotToggleGroup = new SlotToggleGroup(); playerSlots.forEach(slotToggleGroup::add); } private void addPlayerSlotHeadline() { GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 1; constraints.gridy = 0; constraints.gridwidth = 4; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.add(slotsHeadlinePlayerNameLabel, constraints); constraints.gridx = 5; constraints.gridy = 0; constraints.gridwidth = 2; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.add(slotsHeadlineCivilisation, constraints); constraints = new GridBagConstraints(); constraints.gridx = 7; constraints.gridy = 0; constraints.gridwidth = 4; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.add(slotsHeadlineType, constraints); constraints = new GridBagConstraints(); constraints.gridx = 11; constraints.gridy = 0; constraints.gridwidth = 1; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.add(slotsHeadlineMapSlot, constraints); constraints = new GridBagConstraints(); constraints.gridx = 12; constraints.gridy = 0; constraints.gridwidth = 1; constraints.fill = GridBagConstraints.HORIZONTAL; playerSlotsPanel.add(slotsHeadlineTeam, constraints); } private enum EPeaceTime { WITHOUT; @Override public String toString() { return Labels.getString("peace-time-" + name()); } } }
package org.junit.jupiter.api; import static org.junit.jupiter.api.AssertionTestUtils.assertMessageContains; import static org.junit.jupiter.api.AssertionTestUtils.assertMessageEquals; import static org.junit.jupiter.api.AssertionTestUtils.assertMessageStartsWith; import static org.junit.jupiter.api.AssertionTestUtils.expectAssertionFailedError; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.function.ThrowingSupplier; import org.opentest4j.AssertionFailedError; /** * Unit tests for JUnit Jupiter {@link Assertions}. * * @since 5.0 */ class AssertThrowsAssertionsTests { private static final Executable nix = () -> { }; @Test void assertThrowsWithFutureMethodReference() { FutureTask<String> future = new FutureTask<>(() -> { throw new RuntimeException("boom"); }); future.run(); ExecutionException exception; // Current compiler's type inference exception = assertThrows(ExecutionException.class, future::get); assertEquals("boom", exception.getCause().getMessage()); // Explicitly as an Executable exception = assertThrows(ExecutionException.class, (Executable) future::get); assertEquals("boom", exception.getCause().getMessage()); // Explicitly as a ThrowingSupplier exception = assertThrows(ExecutionException.class, (ThrowingSupplier<?>) future::get); assertEquals("boom", exception.getCause().getMessage()); } @Test void assertThrowsWithMethodReferenceForVoidReturnType() { var object = new Object(); IllegalMonitorStateException exception; // Note: the following does not compile since the compiler cannot properly // perform type inference for a method reference for an overloaded method // that has a void return type such as java.lang.Object.wait(...) // Current compiler's type inference exception = assertThrows(IllegalMonitorStateException.class, object::notify); assertNotNull(exception); // Explicitly as an Executable exception = assertThrows(IllegalMonitorStateException.class, (Executable) object::notify); assertNotNull(exception); exception = assertThrows(IllegalMonitorStateException.class, (Executable) object::wait); assertNotNull(exception); } @Test void assertThrowsWithExecutableThatThrowsThrowable() { EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> { throw new EnigmaThrowable(); }); assertNotNull(enigmaThrowable); } @Test void assertThrowsWithExecutableThatThrowsThrowableWithMessage() { EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> { throw new EnigmaThrowable(); }, "message"); assertNotNull(enigmaThrowable); } @Test void assertThrowsWithExecutableThatThrowsThrowableWithMessageSupplier() { EnigmaThrowable enigmaThrowable = assertThrows(EnigmaThrowable.class, (Executable) () -> { throw new EnigmaThrowable(); }, () -> "message"); assertNotNull(enigmaThrowable); } @Test void assertThrowsWithExecutableThatThrowsCheckedException() { IOException exception = assertThrows(IOException.class, (Executable) () -> { throw new IOException(); }); assertNotNull(exception); } @Test void assertThrowsWithExecutableThatThrowsRuntimeException() { IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, (Executable) () -> { throw new IllegalStateException(); }); assertNotNull(illegalStateException); } @Test void assertThrowsWithExecutableThatThrowsError() { StackOverflowError stackOverflowError = assertThrows(StackOverflowError.class, (Executable) AssertionTestUtils::recurseIndefinitely); assertNotNull(stackOverflowError); } @Test void assertThrowsWithExecutableThatDoesNotThrowAnException() { try { assertThrows(IllegalStateException.class, nix); expectAssertionFailedError(); } catch (AssertionFailedError ex) { // the following also implicitly verifies that the failure message does not contain "(returned null)". assertMessageEquals(ex, "Expected java.lang.IllegalStateException to be thrown, but nothing was thrown."); } } @Test void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageString() { try { assertThrows(IOException.class, nix, "Custom message"); expectAssertionFailedError(); } catch (AssertionError ex) { assertMessageEquals(ex, "Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown."); } } @Test void assertThrowsWithExecutableThatDoesNotThrowAnExceptionWithMessageSupplier() { try { assertThrows(IOException.class, nix, () -> "Custom message"); expectAssertionFailedError(); } catch (AssertionError ex) { assertMessageEquals(ex, "Custom message ==> Expected java.io.IOException to be thrown, but nothing was thrown."); } } @Test void assertThrowsWithExecutableThatThrowsAnUnexpectedException() { try { assertThrows(IllegalStateException.class, (Executable) () -> { throw new NumberFormatException(); }); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageStartsWith(ex, "Unexpected exception type thrown ==> "); assertMessageContains(ex, "expected: <java.lang.IllegalStateException>"); assertMessageContains(ex, "but was: <java.lang.NumberFormatException>"); } } @Test void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageString() { try { assertThrows(IllegalStateException.class, (Executable) () -> { throw new NumberFormatException(); }, "Custom message"); expectAssertionFailedError(); } catch (AssertionFailedError ex) { // Should look something like this: assertMessageStartsWith(ex, "Custom message ==> "); assertMessageContains(ex, "Unexpected exception type thrown ==> "); assertMessageContains(ex, "expected: <java.lang.IllegalStateException>"); assertMessageContains(ex, "but was: <java.lang.NumberFormatException>"); } } @Test void assertThrowsWithExecutableThatThrowsAnUnexpectedExceptionWithMessageSupplier() { try { assertThrows(IllegalStateException.class, (Executable) () -> { throw new NumberFormatException(); }, () -> "Custom message"); expectAssertionFailedError(); } catch (AssertionFailedError ex) { // Should look something like this: assertMessageStartsWith(ex, "Custom message ==> "); assertMessageContains(ex, "Unexpected exception type thrown ==> "); assertMessageContains(ex, "expected: <java.lang.IllegalStateException>"); assertMessageContains(ex, "but was: <java.lang.NumberFormatException>"); } } @Test @SuppressWarnings("serial") void assertThrowsWithExecutableThatThrowsInstanceOfAnonymousInnerClassAsUnexpectedException() { try { assertThrows(IllegalStateException.class, (Executable) () -> { throw new NumberFormatException() { }; }); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageStartsWith(ex, "Unexpected exception type thrown ==> "); assertMessageContains(ex, "expected: <java.lang.IllegalStateException>"); // As of the time of this writing, the class name of the above anonymous inner // class is org.junit.jupiter.api.AssertionsAssertThrowsTests$2; however, hard // coding "$2" is fragile. So we just check for the presence of the "$" // appended to this class's name. assertMessageContains(ex, "but was: <" + getClass().getName() + "$"); } } @Test void assertThrowsWithExecutableThatThrowsInstanceOfStaticNestedClassAsUnexpectedException() { try { assertThrows(IllegalStateException.class, (Executable) () -> { throw new LocalException(); }); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageStartsWith(ex, "Unexpected exception type thrown ==> "); assertMessageContains(ex, "expected: <java.lang.IllegalStateException>"); // The following verifies that the canonical name is used (i.e., "." instead of "$"). assertMessageContains(ex, "but was: <" + LocalException.class.getName().replace("$", ".") + ">"); } } @Test @SuppressWarnings("unchecked") void assertThrowsWithExecutableThatThrowsSameExceptionTypeFromDifferentClassLoader() throws Exception { try (EnigmaClassLoader enigmaClassLoader = new EnigmaClassLoader()) { // Load expected exception type from different class loader Class<? extends Throwable> enigmaThrowableClass = (Class<? extends Throwable>) enigmaClassLoader.loadClass( EnigmaThrowable.class.getName()); try { assertThrows(enigmaThrowableClass, (Executable) () -> { throw new EnigmaThrowable(); }); expectAssertionFailedError(); } catch (AssertionFailedError ex) { // Example Output: // Unexpected exception type thrown ==> // expected: <org.junit.jupiter.api.EnigmaThrowable@5d3411d> // but was: <org.junit.jupiter.api.EnigmaThrowable@2471cca7> assertMessageStartsWith(ex, "Unexpected exception type thrown ==> "); // The presence of the "@" sign is sufficient to indicate that the hash was // generated to disambiguate between the two identical class names. assertMessageContains(ex, "expected: <org.junit.jupiter.api.EnigmaThrowable@"); assertMessageContains(ex, "but was: <org.junit.jupiter.api.EnigmaThrowable@"); } } } @Test void assertThrowsWithThrowingSupplierThatReturns() { try { assertThrows(EnigmaThrowable.class, (ThrowingSupplier<?>) () -> 42); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageContains(ex, "(returned 42)"); } } @Test void assertThrowsWithThrowingSupplierThatReturnsNull() { try { assertThrows(EnigmaThrowable.class, (ThrowingSupplier<?>) () -> null); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageContains(ex, "(returned null)"); } } @Test void assertThrowsWithThrowingSupplierThatReturnsAndWithCustomMessage() { try { assertThrows(EnigmaThrowable.class, (ThrowingSupplier<?>) () -> 42, "custom message"); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageContains(ex, "(returned 42)"); assertMessageContains(ex, "custom message"); } } @Test void assertThrowsWithThrowingSupplierThatReturnsAndWithCustomMessageSupplier() { try { assertThrows(EnigmaThrowable.class, (ThrowingSupplier<?>) () -> 42, () -> "custom message"); expectAssertionFailedError(); } catch (AssertionFailedError ex) { assertMessageContains(ex, "(returned 42)"); assertMessageContains(ex, "custom message"); } } @SuppressWarnings("serial") private static class LocalException extends RuntimeException { } private static class EnigmaClassLoader extends URLClassLoader { EnigmaClassLoader() { super(new URL[] { EnigmaClassLoader.class.getProtectionDomain().getCodeSource().getLocation() }, getSystemClassLoader()); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (EnigmaThrowable.class.getName().equals(name) ? findClass(name) : super.loadClass(name)); } } }
package com.jme3.app.state; import com.jme3.app.Application; import com.jme3.renderer.RenderManager; /** * AppState represents a continously executing code inside the main loop. * An <code>AppState</code> can track when it is attached to the * {@link AppStateManager} or when it is detached. <br/><code>AppState</code>s * are initialized in the render thread, upon a call to {@link AppState#initialize(com.jme3.app.state.AppStateManager, com.jme3.app.Application) } * and are de-initialized upon a call to {@link AppState#cleanup()}. * Implementations should return the correct value with a call to * {@link AppState#isInitialized() } as specified above.<br/> * * * @author Kirill Vainer */ public interface AppState { /** * Called to initialize the AppState. * * @param stateManager The state manager * @param app */ public void initialize(AppStateManager stateManager, Application app); /** * @return True if <code>initialize()</code> was called on the state, * false otherwise. */ public boolean isInitialized(); /** * Enable or disable the functionality of the <code>AppState</code>. * The effect of this call depends on implementation. An * <code>AppState</code> starts as being enabled by default. * * @param active activate the AppState or not. */ public void setEnabled(boolean active); /** * @return True if the <code>AppState</code> is enabled, false otherwise. * * @see AppState#setEnabled(boolean) */ public boolean isEnabled(); /** * Called when the state was attached. * * @param stateManager State manager to which the state was attached to. */ public void stateAttached(AppStateManager stateManager); /** * Called when the state was detached. * * @param stateManager The state manager from which the state was detached from. */ public void stateDetached(AppStateManager stateManager); /** * Called to update the state. * * @param tpf Time per frame. */ public void update(float tpf); /** * Render the state. * * @param rm RenderManager */ public void render(RenderManager rm); /** * Called after all rendering commands are flushed. */ public void postRender(); /** * Cleanup the game state. */ public void cleanup(); }
package com.jme3.material; import com.jme3.asset.AssetManager; import com.jme3.renderer.Caps; import com.jme3.shader.*; import com.jme3.util.ListMap; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.logging.Logger; /** * Represents a technique instance. */ public class Technique /* implements Savable */ { private static final Logger logger = Logger.getLogger(Technique.class.getName()); private TechniqueDef def; private Material owner; private ArrayList<Uniform> worldBindUniforms; private DefineList defines; private Shader shader; private boolean needReload = true; /** * Creates a new technique instance that implements the given * technique definition. * * @param owner The material that will own this technique * @param def The technique definition being implemented. */ public Technique(Material owner, TechniqueDef def) { this.owner = owner; this.def = def; if (def.isUsingShaders()) { this.worldBindUniforms = new ArrayList<Uniform>(); this.defines = new DefineList(); } } /** * Serialization only. Do not use. */ public Technique() { } /** * Returns the technique definition that is implemented by this technique * instance. * * @return the technique definition that is implemented by this technique * instance. */ public TechniqueDef getDef() { return def; } /** * Returns the shader currently used by this technique instance. * <p> * Shaders are typically loaded dynamically when the technique is first * used, therefore, this variable will most likely be null most of the time. * * @return the shader currently used by this technique instance. */ public Shader getShader() { return shader; } /** * Returns a list of uniforms that implements the world parameters * that were requested by the material definition. * * @return a list of uniforms implementing the world parameters. */ public List<Uniform> getWorldBindUniforms() { return worldBindUniforms; } /** * Called by the material to tell the technique a parameter was modified. * Specify <code>null</code> for value if the param is to be cleared. */ void notifyParamChanged(String paramName, VarType type, Object value) { // Check if there's a define binding associated with this // parameter. String defineName = def.getShaderParamDefine(paramName); if (defineName != null) { // There is a define. Change it on the define list. // The "needReload" variable will determine // if the shader will be reloaded when the material // is rendered. if (value == null) { // Clear the define. needReload = defines.remove(defineName) || needReload; } else { // Set the define. needReload = defines.set(defineName, type, value) || needReload; } } } void updateUniformParam(String paramName, VarType type, Object value) { if (paramName == null) { throw new IllegalArgumentException(); } Uniform u = shader.getUniform(paramName); switch (type) { case TextureBuffer: case Texture2D: // fall intentional case Texture3D: case TextureArray: case TextureCubeMap: case Int: u.setValue(VarType.Int, value); break; default: u.setValue(type, value); break; } } /** * Returns true if the technique must be reloaded. * <p> * If a technique needs to reload, then the {@link Material} should * call {@link #makeCurrent(com.jme3.asset.AssetManager) } on this * technique. * * @return true if the technique must be reloaded. */ public boolean isNeedReload() { return needReload; } /** * Prepares the technique for use by loading the shader and setting * the proper defines based on material parameters. * * @param assetManager The asset manager to use for loading shaders. */ public void makeCurrent(AssetManager assetManager, boolean techniqueSwitched, EnumSet<Caps> rendererCaps) { if (!def.isUsingShaders()) { // No shaders are used, no processing is neccessary. return; } if (techniqueSwitched) { // If the technique was switched, check if the define list changed // based on material parameters. ListMap params = owner.getParamsMap(); if (!defines.equalsParams(params, def)) { // Defines were changed, update define list defines.clear(); for(int i=0;i<params.size();i++) { MatParam param = (MatParam)params.getValue(i); String defineName = def.getShaderParamDefine(param.getName()); if (defineName != null) { defines.set(defineName, param.getVarType(), param.getValue()); } } needReload = true; } } if (needReload) { loadShader(assetManager,rendererCaps); } } private void loadShader(AssetManager manager,EnumSet<Caps> rendererCaps) { ShaderKey key = new ShaderKey(def.getVertexShaderName(), def.getFragmentShaderName(), getAllDefines(), def.getVertexShaderLanguage(), def.getFragmentShaderLanguage()); if (getDef().isUsingShaderNodes()) { manager.getShaderGenerator(rendererCaps).initialize(this); key.setUsesShaderNodes(true); } shader = manager.loadShader(key); // register the world bound uniforms worldBindUniforms.clear(); if (def.getWorldBindings() != null) { for (UniformBinding binding : def.getWorldBindings()) { Uniform uniform = shader.getUniform("g_" + binding.name()); uniform.setBinding(binding); worldBindUniforms.add(uniform); } } needReload = false; } /** * Computes the define list * @return the complete define list */ public DefineList getAllDefines() { DefineList allDefines = new DefineList(); allDefines.addFrom(def.getShaderPresetDefines()); allDefines.addFrom(defines); return allDefines; } /* public void write(JmeExporter ex) throws IOException { OutputCapsule oc = ex.getCapsule(this); oc.write(def, "def", null); oc.writeSavableArrayList(worldBindUniforms, "worldBindUniforms", null); oc.write(defines, "defines", null); oc.write(shader, "shader", null); } public void read(JmeImporter im) throws IOException { InputCapsule ic = im.getCapsule(this); def = (TechniqueDef) ic.readSavable("def", null); worldBindUniforms = ic.readSavableArrayList("worldBindUniforms", null); defines = (DefineList) ic.readSavable("defines", null); shader = (Shader) ic.readSavable("shader", null); } */ }
package org.easybatch.core.job; import org.easybatch.core.dispatcher.RecordDispatcher; import org.easybatch.core.filter.RecordFilter; import org.easybatch.core.listener.JobListener; import org.easybatch.core.listener.PipelineListener; import org.easybatch.core.listener.RecordReaderListener; import org.easybatch.core.mapper.RecordMapper; import org.easybatch.core.marshaller.RecordMarshaller; import org.easybatch.core.processor.RecordProcessor; import org.easybatch.core.reader.RecordReader; import org.easybatch.core.retry.RetryPolicy; import org.easybatch.core.validator.RecordValidator; import org.easybatch.core.writer.RecordWriter; import java.util.concurrent.TimeUnit; import static org.easybatch.core.util.Utils.checkArgument; import static org.easybatch.core.util.Utils.checkNotNull; /** * Job instance builder. * This is the main entry point to configure a job. * * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) */ public final class JobBuilder { /** * The job to build. */ private JobImpl job; public JobBuilder() { job = new JobImpl(); } /** * Create a new {@link JobBuilder}. * * @return a new job builder. */ public static JobBuilder aNewJob() { return new JobBuilder(); } /** * Set the job name. * * @param name the job name * @return the job builder */ public JobBuilder named(final String name) { checkNotNull(name, "job name"); job.getJobReport().getParameters().setName(name); return this; } /** * Set the number of records to skip. * * @param number the number of records to skip * @return the job builder */ @Deprecated public JobBuilder skip(final long number) { checkArgument(number >= 1, "The number of records to skip should be >= 1"); job.getJobReport().getParameters().setSkip(number); return this; } /** * Set the limit number of records to process. * * @param number the limit number of records to process * @return the job builder */ @Deprecated public JobBuilder limit(final long number) { checkArgument(number >= 1, "The limit number of records should be >= 1"); job.getJobReport().getParameters().setLimit(number); return this; } /** * Set the timeout after which the job should be aborted. * * @param timeout the timeout value in milliseconds * @return the job builder */ @Deprecated public JobBuilder timeout(final long timeout) { return timeout(timeout, TimeUnit.MILLISECONDS); } /** * Set the timeout after which the job should be aborted. * * @param timeout the timeout value * @param unit the time unit * @return the job builder */ @Deprecated public JobBuilder timeout(final long timeout, final TimeUnit unit) { checkArgument(timeout >= 1, "The timeout should be >= 1"); checkNotNull(unit, "time unit"); job.getJobReport().getParameters().setTimeout(TimeUnit.MILLISECONDS.convert(timeout, unit)); return this; } /** * Register a record reader. * * @param recordReader the record reader to register * @return the job builder */ public JobBuilder reader(final RecordReader recordReader) { return reader(recordReader, false); } /** * Register a record reader. * * @param recordReader the record reader to register * @param keepAlive true if the reader should <strong>NOT</strong> be closed * @return the job builder */ public JobBuilder reader(final RecordReader recordReader, final boolean keepAlive) { checkNotNull(recordReader, "record reader"); job.getJobReport().getParameters().setKeepAlive(keepAlive); job.setRecordReader(recordReader); return this; } /** * Register a record reader. * * @param recordReader the record reader to register * @param retryPolicy the retry policy of the reader * @return the job builder */ public JobBuilder reader(final RecordReader recordReader, final RetryPolicy retryPolicy) { checkNotNull(recordReader, "record reader"); checkNotNull(retryPolicy, "retry policy"); job.getJobReport().getParameters().setRetryPolicy(retryPolicy); job.setRecordReader(recordReader); return this; } /** * Register a record reader. * * @param recordReader the record reader to register * @param keepAlive true if the reader should <strong>NOT</strong> be closed * @param retryPolicy the retry policy of the reader * @return the job builder */ public JobBuilder reader(final RecordReader recordReader, final boolean keepAlive, final RetryPolicy retryPolicy) { checkNotNull(recordReader, "record reader"); checkNotNull(retryPolicy, "retry policy"); job.getJobReport().getParameters().setKeepAlive(keepAlive); job.getJobReport().getParameters().setRetryPolicy(retryPolicy); job.setRecordReader(recordReader); return this; } /** * Register a record filter. * * @param recordFilter the record filter to register * @return the job builder */ public JobBuilder filter(final RecordFilter recordFilter) { checkNotNull(recordFilter, "record filter"); job.addRecordProcessor(recordFilter); return this; } /** * Register a record mapper. * * @param recordMapper the record mapper to register * @return the job builder */ public JobBuilder mapper(final RecordMapper recordMapper) { checkNotNull(recordMapper, "record mapper"); job.addRecordProcessor(recordMapper); return this; } /** * Register a record validator. * * @param recordValidator the record validator to register * @return the job builder */ public JobBuilder validator(final RecordValidator recordValidator) { checkNotNull(recordValidator, "record validator"); job.addRecordProcessor(recordValidator); return this; } /** * Register a record processor. * * @param recordProcessor the record processor to register * @return the job builder */ public JobBuilder processor(final RecordProcessor recordProcessor) { checkNotNull(recordProcessor, "record processor"); job.addRecordProcessor(recordProcessor); return this; } /** * Register a record marshaller. * * @param recordMarshaller the record marshaller to register * @return the job builder */ public JobBuilder marshaller(final RecordMarshaller recordMarshaller) { checkNotNull(recordMarshaller, "record marshaller"); job.addRecordProcessor(recordMarshaller); return this; } /** * Register a record writer. * * @param recordWriter the record writer to register * @return the job builder */ public JobBuilder writer(final RecordWriter recordWriter) { checkNotNull(recordWriter, "record writer"); job.addRecordProcessor(recordWriter); return this; } /** * Register a record dispatcher. * * @param recordDispatcher the record dispatcher to register * @return the job builder */ public JobBuilder dispatcher(final RecordDispatcher recordDispatcher) { checkNotNull(recordDispatcher, "record dispatcher"); job.addRecordProcessor(recordDispatcher); return this; } /** * Enable strict mode : if true, then the execution will be aborted on first processing error. * * @param strictMode true if strict mode should be enabled * @return the job builder * * @deprecated Use {@link JobBuilder#errorThreshold(long)} instead */ @Deprecated public JobBuilder strictMode(final boolean strictMode) { if (strictMode) { return errorThreshold(1); } return this; } /** * Set a limit for errors. When the threshold is exceeded, the job will be aborted * * @param errorThreshold the errors limit * @return the job builder */ public JobBuilder errorThreshold(final long errorThreshold) { job.getJobReport().getParameters().setErrorThreshold(errorThreshold); return this; } /** * Parameter to mute all loggers. * * @param silentMode true to enable silent mode * @return the job builder */ @Deprecated public JobBuilder silentMode(final boolean silentMode) { job.getJobReport().getParameters().setSilentMode(silentMode); return this; } /** * Activate JMX monitoring. * * @param jmx true to enable jmx monitoring * @return the job builder */ public JobBuilder jmxMode(final boolean jmx) { job.getJobReport().getParameters().setJmxMode(jmx); return this; } /** * Register a job listener. * See {@link JobListener} for available callback methods. * * @param jobListener The job listener to add. * @return the job builder */ public JobBuilder jobListener(final JobListener jobListener) { checkNotNull(jobListener, "job listener"); job.addJobListener(jobListener); return this; } /** * Register a record reader listener. * See {@link RecordReaderListener} for available callback methods. * * @param recordReaderListener The record reader listener to add. * @return the job builder */ public JobBuilder readerListener(final RecordReaderListener recordReaderListener) { checkNotNull(recordReaderListener, "record reader listener"); job.addRecordReaderListener(recordReaderListener); return this; } /** * Register a pipeline listener. * See {@link PipelineListener} for available callback methods. * * @param pipelineListener The pipeline listener to add. * @return the job builder */ public JobBuilder pipelineListener(final PipelineListener pipelineListener) { checkNotNull(pipelineListener, "pipeline listener"); job.addPipelineListener(pipelineListener); return this; } /** * Build an Easy Batch job instance. * * @return an Easy Batch job instance */ public Job build() { return job; } /** * Build and call the job. * * @return job execution report */ public JobReport call() { return job.call(); } }
package com.monolith.api; /** * Container storing information about one currently running touch event * in one particular frame. * <p/> * Touch event can be identified between frame using it's id. */ public class Touch { public static final int STATE_BEGAN = 1; public static final int STATE_RUNNING = 2; public static final int STATE_ENDED = 3; private int mId; private int mState; private float mX; private float mY; private float mStartX; private float mStartY; /** * Get the id of this touch event. This id can be used to track this * touch event across multiple frames. * * @return The id of this touch event. */ public int getId() { return mId; } /** * Set the id of this touch event. * * @param id Id to set. */ public void setId(int id) { this.mId = id; } /** * Return the state of this touch event. * <p/> * Can be one of {@link Touch#STATE_BEGAN}, {@link Touch#STATE_RUNNING} or {@link Touch#STATE_ENDED}. * * @return The state of this touch. */ public int getState() { return mState; } /** * Set the state of this touch event. * <p/> * Must be one of {@link Touch#STATE_BEGAN}, {@link Touch#STATE_RUNNING} or {@link Touch#STATE_ENDED}. * * @param state State to set. */ public void setState(int state) { this.mState = state; } /** * Get current x position of this touch event. * * @return Current x position of this touch event. */ public float getX() { return mX; } /** * Set current x position of this touch event. * * @param x Position to set. */ public void setX(float x) { this.mX = x; } /** * Get current y position of this touch event. * * @return Current y position of this touch event. */ public float getY() { return mY; } /** * Set current y position of this touch event. * * @param y Position to set. */ public void setY(float y) { this.mY = y; } /** * Get starting x position of this touch event. * * @return Starting x position of this touch event. */ public float getStartX() { return mStartX; } /** * Set starting x position of this touch event. * * @param startX Position to set. */ public void setStartX(float startX) { this.mStartX = startX; } /** * Get starting y position of this touch event. * * @return Starting y position of this touch event. */ public float getStartY() { return mStartY; } /** * Set starting y position of this touch event. * * @param startY Position to set. */ public void setStartY(float startY) { this.mStartY = startY; } }
package jme3test.input; import com.jme3.app.SimpleApplication; import com.jme3.input.JoyInput; import com.jme3.input.Joystick; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.JoyAxisTrigger; import com.jme3.system.AppSettings; public class TestJoystick extends SimpleApplication implements AnalogListener { public static void main(String[] args){ TestJoystick app = new TestJoystick(); AppSettings settings = new AppSettings(true); settings.setUseJoysticks(true); app.setSettings(settings); app.start(); } @Override public void simpleInitApp() { Joystick[] joysticks = inputManager.getJoysticks(); if (joysticks == null) throw new IllegalStateException("Cannot find any joysticks!"); for (Joystick joy : joysticks){ System.out.println(joy.toString()); } inputManager.addMapping("DPAD Left", new JoyAxisTrigger(0, JoyInput.AXIS_POV_X, true)); inputManager.addMapping("DPAD Right", new JoyAxisTrigger(0, JoyInput.AXIS_POV_X, false)); inputManager.addMapping("DPAD Down", new JoyAxisTrigger(0, JoyInput.AXIS_POV_Y, true)); inputManager.addMapping("DPAD Up", new JoyAxisTrigger(0, JoyInput.AXIS_POV_Y, false)); inputManager.addListener(this, "DPAD Left", "DPAD Right", "DPAD Down", "DPAD Up"); inputManager.addMapping("Joy Left", new JoyAxisTrigger(0, 0, true)); inputManager.addMapping("Joy Right", new JoyAxisTrigger(0, 0, false)); inputManager.addMapping("Joy Down", new JoyAxisTrigger(0, 1, true)); inputManager.addMapping("Joy Up", new JoyAxisTrigger(0, 1, false)); inputManager.addListener(this, "Joy Left", "Joy Right", "Joy Down", "Joy Up"); } public void onAnalog(String name, float isPressed, float tpf) { System.out.println(name + " = " + isPressed); } public void onAction(String name, boolean isPressed, float tpf) { System.out.println(name + " = " + isPressed); } }
package dr.app.beauti.mcmcpanel; import dr.app.beauti.BeautiFrame; import dr.app.beauti.BeautiPanel; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.PartitionTreeModel; import dr.app.beauti.options.STARBEASTOptions; import dr.app.util.OSType; import org.virion.jam.components.WholeNumberField; import org.virion.jam.panels.OptionsPanel; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.List; /** * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: MCMCPanel.java,v 1.16 2006/09/05 13:29:34 rambaut Exp $ */ public class MCMCPanel extends BeautiPanel { private static final long serialVersionUID = -3710586474593827540L; WholeNumberField chainLengthField = new WholeNumberField(1, Integer.MAX_VALUE); WholeNumberField echoEveryField = new WholeNumberField(1, Integer.MAX_VALUE); WholeNumberField logEveryField = new WholeNumberField(1, Integer.MAX_VALUE); JCheckBox samplePriorCheckBox = new JCheckBox("Sample from prior only - create empty alignment"); public static final String fileNameStem = "untitled"; JTextField fileNameStemField = new JTextField(fileNameStem); private JCheckBox addTxt = new JCheckBox("Add .txt suffix"); JTextField logFileNameField = new JTextField(fileNameStem + ".log"); JTextField treeFileNameField = new JTextField(fileNameStem + "." + STARBEASTOptions.TREE_FILE_NAME); // JCheckBox allowOverwriteLogCheck = new JCheckBox("Allow to overwrite the existing log file"); // JCheckBox mapTreeLogCheck = new JCheckBox("Create tree file containing the MAP tree:"); // JTextField mapTreeFileNameField = new JTextField("untitled.MAP.tree"); JCheckBox substTreeLogCheck = new JCheckBox("Create tree log file with branch length in substitutions:"); JTextField substTreeFileNameField = new JTextField("untitled(subst).trees"); JCheckBox operatorAnalaysisCheck = new JCheckBox("Create operator analysis file:"); JTextField operatorAnalaysisFileNameField = new JTextField(fileNameStem + ".ops"); BeautiFrame frame = null; private final OptionsPanel optionsPanel; private BeautiOptions options; public MCMCPanel(BeautiFrame parent) { setLayout(new BorderLayout()); int verticalSpacing = 24; if (OSType.isMac()) { // Mac OS X components have more spacing round them verticalSpacing = 6; } optionsPanel = new OptionsPanel(12, verticalSpacing); this.frame = parent; setOpaque(false); optionsPanel.setOpaque(false); chainLengthField.setValue(100000); chainLengthField.setColumns(10); optionsPanel.addComponentWithLabel("Length of chain:", chainLengthField); chainLengthField.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { options.chainLength = chainLengthField.getValue(); frame.setDirty(); } }); optionsPanel.addSeparator(); echoEveryField.setValue(1000); echoEveryField.setColumns(10); optionsPanel.addComponentWithLabel("Echo state to screen every:", echoEveryField); echoEveryField.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { options.echoEvery = echoEveryField.getValue(); frame.setDirty(); } }); logEveryField.setValue(100); logEveryField.setColumns(10); optionsPanel.addComponentWithLabel("Log parameters every:", logEveryField); logEveryField.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { options.logEvery = logEveryField.getValue(); frame.setDirty(); } }); optionsPanel.addSeparator(); fileNameStemField.setColumns(32); optionsPanel.addComponentWithLabel("File name stem:", fileNameStemField); fileNameStemField.setEditable(true); fileNameStemField.addKeyListener(new java.awt.event.KeyListener() { public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) {} public void keyReleased(KeyEvent e) { options.fileNameStem = fileNameStemField.getText(); updateOtherFileNames(options); frame.setDirty(); } }); optionsPanel.addComponent(addTxt); if (OSType.isWindows()) { addTxt.setSelected(true); } else { addTxt.setSelected(false); } addTxt.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { setOptions(options); frame.setDirty(); } }); optionsPanel.addSeparator(); logFileNameField.setColumns(32); optionsPanel.addComponentWithLabel("Log file name:", logFileNameField); logFileNameField.setEditable(false); // optionsPanel.addComponent(allowOverwriteLogCheck); // allowOverwriteLogCheck.setSelected(false); // allowOverwriteLogCheck.addChangeListener(new ChangeListener() { // public void stateChanged(ChangeEvent changeEvent) { // options.allowOverwriteLog = allowOverwriteLogCheck.isSelected(); treeFileNameField.setColumns(32); optionsPanel.addComponentWithLabel("Trees file name:", treeFileNameField); treeFileNameField.setEditable(false); // addComponent(mapTreeLogCheck); // mapTreeLogCheck.setOpaque(false); // mapTreeLogCheck.addActionListener(new java.awt.event.ActionListener() { // public void actionPerformed(ActionEvent e) { // mapTreeFileNameField.setEnabled(mapTreeLogCheck.isSelected()); // mapTreeFileNameField.setColumns(32); // addComponentWithLabel("MAP tree file name:", mapTreeFileNameField); optionsPanel.addComponent(substTreeLogCheck); substTreeLogCheck.setOpaque(false); substTreeLogCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { options.substTreeLog = substTreeLogCheck.isSelected(); updateTreeFileNameList(); substTreeFileNameField.setEnabled(substTreeLogCheck.isSelected()); if (substTreeLogCheck.isSelected()) { substTreeFileNameField.setText(displayTreeList(options.substTreeFileName)); } else { substTreeFileNameField.setText(""); } frame.setDirty(); } }); substTreeFileNameField.setColumns(32); substTreeFileNameField.setEditable(false); substTreeFileNameField.setEnabled(false); optionsPanel.addComponentWithLabel("Substitutions trees file name:", substTreeFileNameField); optionsPanel.addComponent(operatorAnalaysisCheck); operatorAnalaysisCheck.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { options.operatorAnalysis = operatorAnalaysisCheck.isSelected(); updateOtherFileNames(options); frame.setDirty(); } }); operatorAnalaysisFileNameField.setColumns(32); operatorAnalaysisFileNameField.setEditable(false); operatorAnalaysisFileNameField.setEnabled(false); optionsPanel.addComponentWithLabel("Operator analysis file name:", operatorAnalaysisFileNameField); optionsPanel.addSeparator(); optionsPanel.addComponent(samplePriorCheckBox); samplePriorCheckBox.setOpaque(false); samplePriorCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { frame.setDirty(); } }); // logFileNameField.addKeyListener(listener); // treeFileNameField.addKeyListener(listener); //mapTreeFileNameField.addKeyListener(listener); // substTreeFileNameField.addKeyListener(listener); optionsPanel.setPreferredSize(new java.awt.Dimension(500, 600)); // optionsPanel.setMinimumSize(new java.awt.Dimension(800, 600)); JScrollPane scrollPane = new JScrollPane(optionsPanel); scrollPane.setOpaque(false); add(scrollPane, BorderLayout.CENTER); } private void updateTreeFileNameList(){ options.treeFileName.clear(); options.substTreeFileName.clear(); String treeFN; for (PartitionTreeModel tree : options.getPartitionTreeModels()) { if (options.substTreeLog) { treeFN = options.fileNameStem + "." + tree.getPrefix() + "(time)." + STARBEASTOptions.TREE_FILE_NAME; } else { treeFN = options.fileNameStem + "." + tree.getPrefix() + STARBEASTOptions.TREE_FILE_NAME; // stem.partitionName.tree } if (addTxt.isSelected()) treeFN = treeFN + ".txt"; options.treeFileName.add(treeFN); if (options.substTreeLog) { treeFN = options.fileNameStem + "." + tree.getPrefix() + "(subst)." + STARBEASTOptions.TREE_FILE_NAME; if (addTxt.isSelected()) treeFN = treeFN + ".txt"; options.substTreeFileName.add(treeFN); } } if (options.useStarBEAST) { treeFN = options.fileNameStem + "." + options.starBEASTOptions.SPECIES_TREE_FILE_NAME; if (addTxt.isSelected()) treeFN = treeFN + ".txt"; options.treeFileName.add(treeFN); //TODO: species sub tree } } private String displayTreeList(List<String> treeList) { String text = ""; for (String t : treeList) { text = text + t; if (treeList.indexOf(t) < treeList.size() - 1) { text = text + "; "; } } return text; } public void setOptions(BeautiOptions options) { this.options = options; chainLengthField.setValue(options.chainLength); echoEveryField.setValue(options.echoEvery); logEveryField.setValue(options.logEvery); if (options.fileNameStem != null) { fileNameStemField.setText(options.fileNameStem); } else { fileNameStemField.setText(fileNameStem); fileNameStemField.setEnabled(false); } operatorAnalaysisCheck.setSelected(options.operatorAnalysis); updateOtherFileNames(options); samplePriorCheckBox.setSelected(options.samplePriorOnly); optionsPanel.validate(); optionsPanel.repaint(); } private void updateOtherFileNames(BeautiOptions options) { if (options.fileNameStem != null) { // fileNameStemField.setText(options.fileNameStem); options.logFileName = options.fileNameStem + ".log"; if (addTxt.isSelected()) options.logFileName = options.logFileName + ".txt"; logFileNameField.setText(options.logFileName); // if (options.mapTreeFileName == null) { // mapTreeFileNameField.setText(options.fileNameStem + ".MAP.tree"); // } else { // mapTreeFileNameField.setText(options.mapTreeFileName); updateTreeFileNameList(); treeFileNameField.setText(displayTreeList(options.treeFileName)); if (options.substTreeLog) { substTreeFileNameField.setText(displayTreeList(options.substTreeFileName)); } else { substTreeFileNameField.setText(""); } options.operatorAnalysisFileName = options.fileNameStem + ".ops"; if (addTxt.isSelected()) { options.operatorAnalysisFileName = options.operatorAnalysisFileName + ".txt"; } operatorAnalaysisFileNameField.setEnabled(options.operatorAnalysis); if (options.operatorAnalysis) { operatorAnalaysisFileNameField.setText(options.operatorAnalysisFileName); } else { operatorAnalaysisFileNameField.setText(""); } // mapTreeLogCheck.setEnabled(true); // mapTreeLogCheck.setSelected(options.mapTreeLog); // mapTreeFileNameField.setEnabled(options.mapTreeLog); substTreeLogCheck.setEnabled(true); substTreeLogCheck.setSelected(options.substTreeLog); } else { // fileNameStemField.setText(fileNameStem); // fileNameStemField.setEnabled(false); logFileNameField.setText(fileNameStem + ".log"); treeFileNameField.setText(fileNameStem + "." + STARBEASTOptions.TREE_FILE_NAME); // mapTreeLogCheck.setEnabled(false); // mapTreeFileNameField.setEnabled(false); // mapTreeFileNameField.setText("untitled"); substTreeLogCheck.setSelected(false); substTreeFileNameField.setEnabled(false); substTreeFileNameField.setText(""); operatorAnalaysisCheck.setSelected(false); operatorAnalaysisFileNameField.setText(""); } } public void getOptions(BeautiOptions options) { options.fileNameStem = fileNameStemField.getText(); options.logFileName = logFileNameField.getText(); // options.mapTreeLog = mapTreeLogCheck.isSelected(); // options.mapTreeFileName = mapTreeFileNameField.getText(); options.substTreeLog = substTreeLogCheck.isSelected(); updateTreeFileNameList(); options.operatorAnalysis = operatorAnalaysisCheck.isSelected(); options.operatorAnalysisFileName = operatorAnalaysisFileNameField.getText(); options.samplePriorOnly = samplePriorCheckBox.isSelected(); } public JComponent getExportableComponent() { return optionsPanel; } }
package automaton.core; /** * {@link InputRange} represent a range of {@link Character} which can be used * in {@link TransitionTable} of {@link TDFA}. * * @author Fabien Dubosson */ public class InputRange implements Comparable<InputRange> { /** * First {@link Character} of the range */ private final char from; /** * Last {@link Character} or the range */ private final char to; /** * Constructor which take the first and last character as parameter * * @param from * The first {@link Character} of the range * @param to * The last {@link Character} of the range */ public InputRange(char from, char to) { this.from = from; this.to = to; } /** * Return the first {@link Character} of the range * * @return the first {@link Character} of the range */ public char getFrom() { return from; } /** * Return the last {@link Character} of the range * * @return the last {@link Character} of the range */ public char getTo() { return to; } /** * Tell if the {@link InputRange} contains a {@link Character} within its * range * * @param character * A specific {@link Character} * @return if the {@link Character} is contained within the * {@link InputRange} */ public boolean contains(Character character) { return (from <= character && character <= to); } @Override public int compareTo(InputRange o) { return o.getFrom() - this.getFrom(); } }
package com.badlogic.gdx.setup; import java.util.HashMap; public class DependencyBank { //Versions static String libgdxVersion = "1.5.6"; //Temporary snapshot version, we need a more dynamic solution for pointing to the latest nightly static String libgdxNightlyVersion = "1.5.7-SNAPSHOT"; static String roboVMVersion = "1.0.0"; static String buildToolsVersion = "20.0.0"; static String androidAPILevel = "20"; static String gwtVersion = "2.6.0"; //Repositories static String mavenCentral = "mavenCentral()"; static String jCenter = "jcenter()"; static String libGDXSnapshotsUrl = "https://oss.sonatype.org/content/repositories/snapshots/"; static String libGDXReleaseUrl = "https://oss.sonatype.org/content/repositories/releases/"; //Project plugins static String gwtPluginImport = "de.richsource.gradle.plugins:gwt-gradle-plugin:0.6"; static String androidPluginImport = "com.android.tools.build:gradle:1.0.0"; static String roboVMPluginImport = "org.robovm:robovm-gradle-plugin:" + roboVMVersion; //Extension versions static String box2DLightsVersion = "1.3"; static String ashleyVersion = "1.4.0"; static String aiVersion = "1.5.0"; HashMap<ProjectDependency, Dependency> gdxDependencies = new HashMap<ProjectDependency, Dependency>(); public DependencyBank() { for (ProjectDependency projectDep : ProjectDependency.values()) { Dependency dependency = new Dependency(projectDep.name(), projectDep.getGwtInherits(), projectDep.getDependencies(ProjectType.CORE), projectDep.getDependencies(ProjectType.DESKTOP), projectDep.getDependencies(ProjectType.ANDROID), projectDep.getDependencies(ProjectType.IOS), projectDep.getDependencies(ProjectType.HTML)); gdxDependencies.put(projectDep, dependency); } } public Dependency getDependency(ProjectDependency gdx) { return gdxDependencies.get(gdx); } /** * This enum will hold all dependencies available for libgdx, allowing the setup to pick the ones needed by default, * and allow the option to choose extensions as the user wishes. * <p/> * These depedency strings can be later used in a simple gradle plugin to manipulate the users project either after/before * project generation * * @see Dependency for the object that handles sub-module dependencies. If no dependency is found for a sub-module, ie * FreeTypeFont for gwt, an exception is thrown so the user can be notified of incompatability */ public enum ProjectDependency { GDX( new String[]{"com.badlogicgames.gdx:gdx:$gdxVersion"}, new String[]{"com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion", "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"}, new String[]{"com.badlogicgames.gdx:gdx-backend-android:$gdxVersion", "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi", "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a", "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"}, new String[]{"org.robovm:robovm-rt:${roboVMVersion}", "org.robovm:robovm-cocoatouch:${roboVMVersion}", "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion", "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"}, new String[]{"com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion", "com.badlogicgames.gdx:gdx:$gdxVersion:sources", "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"}, new String[]{"com.badlogic.gdx.backends.gdx_backends_gwt"}, "Core Library for LibGDX" ), BULLET( new String[]{"com.badlogicgames.gdx:gdx-bullet:$gdxVersion"}, new String[]{"com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-desktop"}, new String[]{"com.badlogicgames.gdx:gdx-bullet:$gdxVersion", "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi", "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-armeabi-v7a", "com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-x86"}, new String[]{"com.badlogicgames.gdx:gdx-bullet-platform:$gdxVersion:natives-ios"}, null, null, "3D Collision Detection and Rigid Body Dynamics" ), FREETYPE( new String[]{"com.badlogicgames.gdx:gdx-freetype:$gdxVersion"}, new String[]{"com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"}, new String[]{"com.badlogicgames.gdx:gdx-freetype:$gdxVersion", "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi", "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a", "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"}, new String[]{"com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-ios"}, null, null, "Generate BitmapFonts from .ttf font files" ), TOOLS( new String[]{}, new String[]{"com.badlogicgames.gdx:gdx-tools:$gdxVersion"}, new String[]{}, new String[]{}, new String[]{}, new String[]{}, "Collection of tools, including 2D/3D particle editors, texture packers, and file processors" ), CONTROLLERS( new String[]{"com.badlogicgames.gdx:gdx-controllers:$gdxVersion"}, new String[]{"com.badlogicgames.gdx:gdx-controllers-desktop:$gdxVersion", "com.badlogicgames.gdx:gdx-controllers-platform:$gdxVersion:natives-desktop"}, new String[]{"com.badlogicgames.gdx:gdx-controllers:$gdxVersion", "com.badlogicgames.gdx:gdx-controllers-android:$gdxVersion"}, new String[]{}, // works on iOS but never reports any controllers :) new String[]{"com.badlogicgames.gdx:gdx-controllers:$gdxVersion:sources", "com.badlogicgames.gdx:gdx-controllers-gwt:$gdxVersion", "com.badlogicgames.gdx:gdx-controllers-gwt:$gdxVersion:sources"}, new String[]{"com.badlogic.gdx.controllers.controllers-gwt"}, "Controller/Gamepad API" ), BOX2D( new String[]{"com.badlogicgames.gdx:gdx-box2d:$gdxVersion"}, new String[]{"com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"}, new String[]{"com.badlogicgames.gdx:gdx-box2d:$gdxVersion", "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi", "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a", "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"}, new String[]{"com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"}, new String[]{"com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources", "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"}, new String[]{"com.badlogic.gdx.physics.box2d.box2d-gwt"}, "2D Physics Library" ), BOX2DLIGHTS( new String[]{"com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion"}, new String[]{}, new String[]{"com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion"}, new String[]{}, new String[]{"com.badlogicgames.box2dlights:box2dlights:$box2DLightsVersion:sources"}, new String[]{"Box2DLights"}, "2D Lighting framework that utilises Box2D" ), ASHLEY( new String[]{"com.badlogicgames.ashley:ashley:$ashleyVersion"}, new String[]{}, new String[]{"com.badlogicgames.ashley:ashley:$ashleyVersion"}, new String[]{}, new String[]{"com.badlogicgames.ashley:ashley:$ashleyVersion:sources"}, new String[]{"com.badlogic.ashley_gwt"}, "Lightweight Entity framework" ), AI( new String[]{"com.badlogicgames.gdx:gdx-ai:$aiVersion"}, new String[]{}, new String[]{"com.badlogicgames.gdx:gdx-ai:$aiVersion"}, new String[]{}, new String[]{"com.badlogicgames.gdx:gdx-ai:$aiVersion:sources"}, new String[]{"com.badlogic.gdx.ai"}, "Artificial Intelligence framework" ); private String[] coreDependencies; private String[] desktopDependencies; private String[] androidDependencies; private String[] iosDependencies; private String[] gwtDependencies; private String[] gwtInherits; private String description; ProjectDependency(String[] coreDeps, String[] desktopDeps, String[] androidDeps, String[] iosDeps, String[] gwtDeps, String[] gwtInhertis, String description) { this.coreDependencies = coreDeps; this.desktopDependencies = desktopDeps; this.androidDependencies = androidDeps; this.iosDependencies = iosDeps; this.gwtDependencies = gwtDeps; this.gwtInherits = gwtInhertis; this.description = description; } public String[] getDependencies(ProjectType type) { switch (type) { case CORE: return coreDependencies; case DESKTOP: return desktopDependencies; case ANDROID: return androidDependencies; case IOS: return iosDependencies; case HTML: return gwtDependencies; } return null; } public String[] getGwtInherits() { return gwtInherits; } public String getDescription() { return description; } } public enum ProjectType { CORE("core", new String[]{"java"}), DESKTOP("desktop", new String[]{"java"}), ANDROID("android", new String[]{"android"}), IOS("ios", new String[]{"java", "robovm"}), HTML("html", new String[]{"gwt", "war"}); private final String name; private final String[] plugins; ProjectType(String name, String plugins[]) { this.name = name; this.plugins = plugins; } public String getName() { return name; } public String[] getPlugins() { return plugins; } } }
package org.fcrepo.api; import static org.fcrepo.test.util.PathSegmentImpl.createPathList; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.InputStream; import java.util.Date; import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.io.IOUtils; import org.fcrepo.Datastream; import org.fcrepo.exception.InvalidChecksumException; import org.fcrepo.identifiers.PidMinter; import org.fcrepo.services.DatastreamService; import org.fcrepo.services.NodeService; import org.fcrepo.test.util.TestHelpers; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FedoraContentTest { FedoraContent testObj; DatastreamService mockDatastreams; NodeService mockNodeService; Session mockSession; @Before public void setUp() throws LoginException, RepositoryException { mockDatastreams = mock(DatastreamService.class); mockNodeService = mock(NodeService.class); testObj = new FedoraContent(); testObj.setDatastreamService(mockDatastreams); testObj.setNodeService(mockNodeService); mockSession = TestHelpers.mockSession(testObj); testObj.setSession(mockSession); testObj.setUriInfo(TestHelpers.getUriInfoImpl()); } @After public void tearDown() { } @Test public void testPutContent() throws RepositoryException, IOException, InvalidChecksumException { final String pid = "FedoraDatastreamsTest1"; final String dsId = "testDS"; final String dsContent = "asdf"; final String dsPath = "/" + pid + "/" + dsId; final InputStream dsContentStream = IOUtils.toInputStream(dsContent); final Node mockNode = mock(Node.class); when(mockNode.isNew()).thenReturn(true); when(mockNodeService.exists(mockSession, dsPath)).thenReturn(false); when( mockDatastreams.createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class))) .thenReturn(mockNode); when(mockDatastreams.exists(mockSession, dsPath)).thenReturn(true); final Response actual = testObj.modifyContent(createPathList(pid, dsId), null, dsContentStream, null); assertEquals(Status.CREATED.getStatusCode(), actual.getStatus()); verify(mockDatastreams).createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class)); verify(mockSession).save(); } @Test public void testCreateContent() throws RepositoryException, IOException, InvalidChecksumException { final String pid = "FedoraDatastreamsTest1"; final String dsId = "xyz"; final String dsContent = "asdf"; final String dsPath = "/" + pid + "/" + dsId; final InputStream dsContentStream = IOUtils.toInputStream(dsContent); final Node mockNode = mock(Node.class); when(mockNode.isNew()).thenReturn(true); when(mockNodeService.exists(mockSession, dsPath)).thenReturn(false); when( mockDatastreams.createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class))) .thenReturn(mockNode); when(mockDatastreams.exists(mockSession, dsPath)).thenReturn(true); final Response actual = testObj.create(createPathList(pid, dsId), null, null, MediaType.TEXT_PLAIN_TYPE, dsContentStream); assertEquals(Status.CREATED.getStatusCode(), actual.getStatus()); verify(mockDatastreams).createDatastreamNode(mockSession,dsPath, "text/plain", dsContentStream, null, null); verify(mockSession).save(); } @Test public void testCreateContentAtMintedPath() throws RepositoryException, IOException, InvalidChecksumException { final String pid = "FedoraDatastreamsTest1"; final String dsId = "fcr:new"; final String dsContent = "asdf"; final String dsPath = "/" + pid + "/" + dsId; final InputStream dsContentStream = IOUtils.toInputStream(dsContent); final Node mockNode = mock(Node.class); PidMinter mockMinter = mock(PidMinter.class); when(mockMinter.mintPid()).thenReturn("xyz"); testObj.setPidMinter(mockMinter); when(mockNode.isNew()).thenReturn(true); when(mockNodeService.exists(mockSession, dsPath)).thenReturn(false); when( mockDatastreams.createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class))) .thenReturn(mockNode); when(mockDatastreams.exists(mockSession, dsPath)).thenReturn(true); final Response actual = testObj.create(createPathList(pid, dsId), null, null, MediaType.TEXT_PLAIN_TYPE, dsContentStream); assertEquals(Status.CREATED.getStatusCode(), actual.getStatus()); verify(mockDatastreams).createDatastreamNode(mockSession, "/" + pid + "/xyz", "text/plain", dsContentStream, null, null); verify(mockSession).save(); } @Test public void testModifyContent() throws RepositoryException, IOException, InvalidChecksumException { final String pid = "FedoraDatastreamsTest1"; final String dsId = "testDS"; final String dsContent = "asdf"; final String dsPath = "/" + pid + "/" + dsId; final InputStream dsContentStream = IOUtils.toInputStream(dsContent); final Node mockNode = mock(Node.class); when(mockNode.isNew()).thenReturn(false); final Datastream mockDs = TestHelpers.mockDatastream(pid, dsId, dsContent); when(mockDatastreams.getDatastream(mockSession, dsPath)).thenReturn( mockDs); final Request mockRequest = mock(Request.class); when( mockRequest.evaluatePreconditions(any(Date.class), any(EntityTag.class))).thenReturn(null); when( mockDatastreams.createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class))) .thenReturn(mockNode); when(mockDatastreams.exists(mockSession, dsPath)).thenReturn(true); final Response actual = testObj.modifyContent(createPathList(pid, dsId), null, dsContentStream, mockRequest); assertEquals(Status.NO_CONTENT.getStatusCode(), actual.getStatus()); verify(mockDatastreams).createDatastreamNode(any(Session.class), eq(dsPath), anyString(), any(InputStream.class)); verify(mockSession).save(); } @Test public void testGetContent() throws RepositoryException, IOException { final String pid = "FedoraDatastreamsTest1"; final String dsId = "testDS"; final String path = "/" + pid + "/" + dsId; final String dsContent = "asdf"; final Datastream mockDs = TestHelpers.mockDatastream(pid, dsId, dsContent); when(mockDatastreams.getDatastream(mockSession, path)).thenReturn( mockDs); final Request mockRequest = mock(Request.class); final Response actual = testObj.getContent(createPathList(pid, dsId), mockRequest); verify(mockDs).getContent(); verify(mockSession, never()).save(); final String actualContent = IOUtils.toString((InputStream) actual.getEntity()); assertEquals("asdf", actualContent); } }
package com.cloudera.impala.testutil; import java.io.File; import java.io.FileWriter; import java.util.List; import java.util.Map; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import com.cloudera.impala.catalog.Catalog; import com.cloudera.impala.catalog.Db; import com.cloudera.impala.catalog.HdfsPartition; import com.cloudera.impala.catalog.HdfsPartition.FileDescriptor; import com.cloudera.impala.catalog.HdfsTable; import com.cloudera.impala.catalog.Table; /** * Utility to generate an output file with all the block ids for each table * currently in the metastore. Having the block ids allows us to map hdfs * files to filesystem files. This is mostly a hack since hdfs does not * willingly expose this information. */ public class BlockIdGenerator { @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { if (args.length != 1) { throw new Exception("Invalid args: BlockIdGenerator <output_file>"); } HdfsConfiguration hdfsConfig = new HdfsConfiguration(); File output = new File(args[0]); FileWriter writer = null; try { writer = new FileWriter(output); // Load all tables in the catalog Catalog catalog = new Catalog(false); Db database = catalog.getDb(null); Map<String,Table> tables = database.getTables(); for (String tableName: tables.keySet()) { Table table = database.getTable(tableName); // Only do this for hdfs tables if (table == null || !(table instanceof HdfsTable)) { continue; } HdfsTable hdfsTable = (HdfsTable)table; // Write the output as <tablename>: <blockid1> <blockid2> <etc> writer.write(tableName + ":"); for (HdfsPartition partition: hdfsTable.getPartitions()) { List<FileDescriptor> fileDescriptors = partition.getFileDescriptors(); for (FileDescriptor fd : fileDescriptors) { String path = fd.getFilePath(); Path p = new Path(path); // Use a deprecated API to get block ids DistributedFileSystem dfs = (DistributedFileSystem)p.getFileSystem(hdfsConfig); LocatedBlocks locations = dfs.getClient().getNamenode().getBlockLocations( p.toUri().getPath(), 0, fd.getFileLength()); for (LocatedBlock lb : locations.getLocatedBlocks()) { long id = lb.getBlock().getBlockId(); writer.write(" " + id); } } } writer.write("\n"); } } finally { if (writer != null) writer.close(); } } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; class Lexical { private String line = null, type = null; private BufferedReader br; private String token; private ArrayList<String> letters = new ArrayList<String>(); //Collection of allowed letters private ArrayList<String> digits = new ArrayList<String>(); //Collection of allowed digits private ArrayList<String> operators = new ArrayList<String>(); //Collection of allowed operators private ArrayList<String> spaces = new ArrayList<String>(); //Collection of space and horizontal tab private ArrayList<String> punctions = new ArrayList<String>(); //Punctuations public ArrayList<String> reserved = new ArrayList<String>(); //Reserved tokens of grammar //Constructor to open file for reading Lexical(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } //Initialize the allowed LETTERS, DIGITS and OPERATOS char ch = 'a'; for (int i = 0 ; i < 26 ; i++) letters.add(""+ch++); ch = 'A'; for (int i = 0 ; i < 26 ; i++) letters.add(""+ch++); for (int i = 0 ; i < 10 ; i++) digits.add(""+i); String[] s = new String[] {"+", "-", "*", "<", ">", "&", ".", "@", "/", ":", "=", "~", "|", "$", "!", " "^", "_", "[", "]", "{", "}", "\"", "`", "?"}; operators.addAll(Arrays.asList(s)); s = new String[] {" ", "\t", "\n"}; spaces.addAll(Arrays.asList(s)); s = new String[] {"(", ")", ";", ","}; punctions.addAll(Arrays.asList(s)); s = new String[] {"let", "in", "fn", "where", "aug", "or", "not", "gr", "ge", "ls", "le", "eq", "ne", "within", "and", "rec"}; reserved.addAll(Arrays.asList(s)); } //Read a line from FILE private String readFile() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } //Parse the current line and select a token to return. If EndOfLine reached, make line = null for next line reading. private String parse() { StringBuilder sb = new StringBuilder(); boolean cont; do { cont = false; if (line == null) return ""; if (line.equals("")) { line = readFile(); cont = true; } //IDENTIFIER else if (letters.contains(line.charAt(0)+"")) { type = "<IDENTIFIER>"; //TYPE can be needed by the parser corresponding to a token while (true) { sb.append(line.charAt(0)+""); //Append that character to the current token line = line.substring(1); //Trim the first character from the LINE for next reading if (line.length() == 0) { line = null; break; } if (letters.contains(line.charAt(0)+"")) continue; else if (digits.contains(line.charAt(0)+"")) continue; else if (line.charAt(0) == '_') continue; else break; } } //INTEGER else if (digits.contains(line.charAt(0)+"")) { type = "<INTEGER>"; while (true) { sb.append(line.charAt(0)+""); line = line.substring(1); if (line.length() == 0) { line = null; break; } if (digits.contains(line.charAt(0)+"")) continue; else break; } } //COMMENT else if (line.charAt(0) == '/' && line.charAt(1) == '/') { type = "<DELETE>"; line = readFile(); if (line == null) return ""; cont = true; } //OPERATOR else if (operators.contains(line.charAt(0)+"")) { type = "<OPERATOR>"; while (true) { sb.append(line.charAt(0)+""); line = line.substring(1); if (line.length() == 0) { line = null; break; } if (operators.contains(line.charAt(0)+"")) continue; else break; } } //STRING else if (line.charAt(0) == '\'') { type = "<STRING>"; while (true) { sb.append(line.charAt(0)); line = line.substring(1); if (line.length() == 0) { line = null; break; } if (line.charAt(0) == '\\') { //If escape character, don't consider the next character sb.append(line.charAt(0)); line = line.substring(1); sb.append(line.charAt(0)); line = line.substring(1); } if (line.charAt(0) == '\'') { sb.append(line.charAt(0)); line = line.substring(1); if (line.length() == 0) line = null; break; } } } //SPACES else if (spaces.contains(line.charAt(0)+"")) { type = "<DELETE>"; line = line.substring(1); if (line.length() == 0) line = readFile(); if (line == null) return ""; cont = true; } //PUNCTUATIONS else if (punctions.contains(line.charAt(0)+"")) { type = "<PUNCTIONS>"; sb.append(line.charAt(0)); line = line.substring(1); if (line.length() == 0) line = null; } } while (cont == true); return sb.toString(); } //Get a new token for parsing. Read a new line if the previous one is finished. public String getToken() { token = ""; if (line == null) { line = readFile(); } if (line != null) { token = parse(); if (token.equals("")) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } else { //No more contents left in file to read try { br.close(); } catch (IOException e) { e.printStackTrace(); } token = ""; } return token; } //Get type of the last returned token public String getType() { if (token.equals("")) type = "<EOF>"; return type; } } /* * ABSTRACT SYNTAX TREE * * Tree is in FIRST CHILD NEXT SIBLING form, * child = first child, sibling = next sibling */ class Node { private String token; private Node child; private Node sibling; public void setToken(String token) { this.token = token; } public void setChild(Node child) { this.child = child; } public void setSibling(Node sibling) { this.sibling = sibling; } public String getToken() { return token; } public Node getChild() { return child; } public Node getSibling() { return sibling; } } class Parser { Lexical l; String token; Stack<Node> stack = new Stack<Node>(); //Constructor to initialize Lexical with fileName Parser(String fileName) { l = new Lexical(fileName); } //Read and compare the token with the expected value private void read(String s) { if (!s.equals(token)) { //SYNTAX ERROR !! exit. System.err.println("Expected '"+s+"' but found '"+token+"'"); System.exit(0); } if ((!l.reserved.contains(token)) && (l.getType().equals("<IDENTIFIER>") || l.getType().equals("<INTEGER>") || l.getType().equals("<STRING>"))) buildTree(token, 0); //Build a node in case of identifiers, integers and strings token = l.getToken(); } //Build Tree by popping the specified number of trees from stack and join with root node specified private void buildTree(String root, int n) { int i = 0; //To pop the required number of trees Node temp = null; String s; if (n == 0 && l.getType().equals("<IDENTIFIER>") && !l.reserved.contains(root)) s = "<ID:"+root+">"; else if (n == 0 && l.getType().equals("<INTEGER>")) s = "<INT:"+root+">"; else if (n == 0 && l.getType().equals("<STRING>") && !l.reserved.contains(root)) s = "<STR:"+root+">"; else s = root; while (i < n) { Node sib = stack.pop(); sib.setSibling(temp); //First popped node has sibling set as null, second popped has sibling as 'first popped' temp = sib; i++; } Node r = new Node(); r.setToken(s); r.setChild(temp); r.setSibling(null); stack.push(r); //Push the newly constructed tree which has root as token='root' from argument } /* * E -> 'let' D 'in' E => 'let' * -> 'fn' Vb+ '.' 'E' => 'lambda' * -> Ew; */ private void E() { if (token.equals("let")) { read("let"); D(); read("in"); E(); buildTree("let", 2); } else if (token.equals("fn")) { read("fn"); int n = 0; do { Vb(); n++; } while (l.getType().equals("<IDENTIFIER>") | token.equals("(")); read("."); E(); buildTree("lambda", n+1); } else { Ew(); } } /* * Ew -> T 'where' Dr => 'where' * -> T; */ private void Ew() { T(); if (token.equals("where")) { read("where"); Dr(); buildTree("where", 2); } } /* * T -> Ta ( ',' Ta )+ => 'tau' * -> Ta; */ private void T() { Ta(); int n = 0; while (token.equals(",")) { read(","); Ta(); n++; } if (n > 0) { buildTree("tau", n+1); } } /* * Ta -> Ta 'aug' Tc => 'aug' * -> Tc; */ private void Ta() { Tc(); while (token.equals("aug")) { read("aug"); Tc(); buildTree("aug", 2); } } /* * Tc -> B '->' Tc '|' Tc => '->' * -> B; */ private void Tc() { B(); if (token.equals("->")) { read("->"); Tc(); read("|"); Tc(); buildTree("->", 3); } } /* * B -> B 'or' Bt => 'or' * -> Bt; */ private void B() { Bt(); while (token.equals("or")) { read("or"); Bt(); buildTree("or", 2); } } /* * Bt -> Bt '&' Bs => '&' * -> Bs; */ private void Bt() { Bs(); while (token.equals("&")) { read("&"); Bs(); buildTree("&", 2); } } /* * Bs -> 'not' Bp => 'not' * -> Bp; */ private void Bs() { if (token.equals("not")) { read("not"); Bp(); buildTree("not", 1); } else { Bp(); } } /* * Bp -> A ( 'gr' | '>' ) A => 'gr' * -> A ( 'ge' | '>=' ) A => 'ge' * -> A ( 'ls' | '<' ) A => 'ls' * -> A ( 'le' | '<=' ) A => 'le' * -> A 'eq' A => 'eq' * -> A 'ne' A => 'ne' * -> A; */ private void Bp() { A(); if (token.equals("gr") || token.equals(">")) { read(token); A(); buildTree("gr", 2); } else if (token.equals("ge") || token.equals(">=")) { read(token); A(); buildTree("ge", 2); } else if (token.equals("ls") || token.equals("<")) { read(token); A(); buildTree("ls", 2); } else if (token.equals("le") || token.equals("<=")) { read(token); A(); buildTree("le", 2); } else if (token.equals("eq")) { read("eq"); A(); buildTree("eq", 2); } else if (token.equals("ne")) { read("ne"); A(); buildTree("ne", 2); } } /* * A -> A '+' At => '+' * -> A '-' At => '-' * -> '+' At * -> '-' At => 'neg' * -> At; */ private void A() { if (token.equals("+")) { read("+"); At(); } else if (token.equals("-")) { read("-"); At(); buildTree("neg", 1); } else { At(); } String temp; while (token.equals("+") || token.equals("-")) { temp = token; read(temp); At(); buildTree(temp, 2); } } /* * At -> At '*' Af => '*' * -> At '/' Af => '/' * -> Af; */ private void At() { Af(); String temp; while (token.equals("*") || token.equals("/")) { temp = token; read(temp); Af(); buildTree(temp, 2); } } /* * Af -> Ap '**' Af => '**' * -> Ap; */ private void Af() { Ap(); if (token.equals("**")) { read("**"); Af(); buildTree("**", 2); } } /* * Ap -> Ap '@' '<identifier>' R => '@' * -> R; */ private void Ap() { R(); while (token.equals("@")) { read("@"); read(token); R(); buildTree("@", 3); } } /* * R -> R Rn => 'gamma' * -> Rn; */ private void R() { Rn(); while ((!l.reserved.contains(token)) && (l.getType().equals("<IDENTIFIER>") || l.getType().equals("<INTEGER>") || l.getType().equals("<STRING>") || token.equals("true") || token.equals("false") || token.equals("nil") || token.equals("(") || token.equals("dummy"))) { Rn(); buildTree("gamma", 2); } } /* * Rn -> '<identifier>' * -> '<integer>' * -> '<string>' * -> 'true' => 'true' * -> 'false' => 'false' * -> 'nil' => 'nil' * -> '(' E ')' * -> 'dummy' => 'dummy' */ private void Rn() { if (l.getType().equals("<IDENTIFIER>") || l.getType().equals("<INTEGER>") || l.getType().equals("<STRING>")) { read(token); } else if (token.equals("true")) { read("true"); buildTree("true", 0); } else if (token.equals("false")) { read("false"); buildTree("false", 0); } else if (token.equals("nil")) { read("nil"); buildTree("nil", 0); } else if (token.equals("(")) { read("("); E(); read(")"); } else if (token.equals("dummy")) { read("dummy"); buildTree("dummy", 0); } } /* * D -> Da 'within' D => 'within' * -> Da; */ private void D() { Da(); if (token.equals("within")) { read("within"); D(); buildTree("within", 2); } } /* * Da -> Dr ( 'and' Dr )+ => 'and' * -> Dr; */ private void Da() { Dr(); int n = 0; while (token.equals("and")) { read("and"); Dr(); n++; } if (n > 0) buildTree("and", n+1); } /* * Dr -> 'rec' Db => 'rec' * -> Db; */ private void Dr() { if (token.equals("rec")) { read("rec"); Db(); buildTree("rec", 1); } else Db(); } /* * Db -> Vl '=' E => '=' * -> '<identifier>' Vb+ '=' E => 'fcn_form' * -> '(' D ')'; */ private void Db() { if (l.getType().equals("<IDENTIFIER>")) { Vl(); if (token.equals("=")) { read("="); E(); buildTree("=", 2); } else { int n = 0; while (l.getType().equals("<IDENTIFIER>") || token.equals("(")) { Vb(); n++; } read("="); E(); buildTree("function_form", n+2); } } else if (token.equals("(")) { read("("); D(); read(")"); } } /* * Vb -> '<identifier>' * -> '(' Vl ')' * -> '(' ')' => '()'; */ private void Vb() { if (l.getType().equals("<IDENTIFIER>")) read(token); else if (token.equals("(")) { read("("); if (token.equals(")")) { read(")"); buildTree("()", 2); } else { Vl(); read(")"); } } } /* * Vl -> '<identifier>' list ',' => ','?; */ private void Vl() { if (l.getType().equals("<IDENTIFIER>")) { read(token); } int n = 0; while (token.equals(",")) { read(","); read(token); n++; } if (n > 0) buildTree(",", n+1); } //Traverse the AST in pre-order and print the tokens private void preOrder(Node n, int level) { String dot = ""; for (int i = 0 ; i < level ; i++) dot = dot + "."; System.out.println(dot+""+n.getToken()); if (n.getChild() != null) { preOrder(n.getChild(), level+1); } if (n.getSibling() != null) { preOrder(n.getSibling(), level); } } //Print the generated Abstract Syntax Tree private void printAST() { Node ast = stack.pop(); preOrder(ast, 0); } //Start Parsing and call PRINT upon completion public void startParsing() { token = l.getToken(); E(); if (l.getType().equals("<EOF>")) { //EOF reached printAST(); } } } public class P1 { public static void main(String args[]){ String fileName; if (args.length == 0) { //No switches => no output System.exit(0); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("-l")) { //Listing // TO DO : listing } else if (args[0].equalsIgnoreCase("-ast")) { System.err.println("Error: FILE_NAME expected"); System.exit(0); } else { System.err.println("Error: Unidentified Switch"); System.exit(0); } } else if (args.length == 2 && args[0].equalsIgnoreCase("-ast")) { //Generate AST by reading FILE fileName = args[1]; Parser p = new Parser(fileName); p.startParsing(); } else { System.err.println("Error: Illegal parameters"); System.exit(0); } } }
package com.leandog.brazenhead; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import android.app.Activity; import android.content.res.Resources; import android.widget.Spinner; import com.jayway.android.robotium.solo.By; import com.jayway.android.robotium.solo.Solo; import com.leandog.brazenhead.test.BrazenheadTestRunner; @RunWith(BrazenheadTestRunner.class) public class BrazenheadTest { @Mock Solo solo; @Mock Activity activity; @Mock Resources resources; @Mock SpinnerPresser spinnerPresser; @Mock ListItemFinder listItemFinder; @Mock ListItemPresser listItemPresser; private Brazenhead brazenhead; @Before public void setUp() throws IOException { initMocks(); brazenhead = new Brazenhead(spinnerPresser, listItemFinder, listItemPresser); } @Test public void itCanFindAnIdFromTheTargetPackageResources() { when(activity.getPackageName()).thenReturn("com.some.package"); brazenhead.idFromName("some_id"); verify(resources).getIdentifier("some_id", "id", "com.some.package"); } @Test public void itCanPressSpinnersById() { brazenhead.pressSpinnerItemById(123, 7); verify(spinnerPresser).pressSpinnerItemById(123, 7); } @Test public void itCanPressSpinnersByView() { final Spinner spinner = mock(Spinner.class); brazenhead.pressSpinnerItem(spinner, 7); verify(spinnerPresser).pressSpinnerItem(spinner, 7); } @Test public void itCanLocateListItemsByText() throws Exception { brazenhead.listItemByText("Some text"); verify(listItemFinder).findByText("Some text"); } @Test public void itCanLocateListItemsByIndexInTheDefaultList() { brazenhead.listItemByIndex(7); verify(listItemFinder).findByIndex(7); } @Test public void itCanLocateListItemsByIndex() { brazenhead.listItemByIndex(7, 1); verify(listItemFinder).findByIndex(7, 1); } @Test public void itCanPressListItemsByIndex() throws Exception { brazenhead.pressListItemByIndex(7); verify(listItemPresser).pressListItem(7); } @Test public void itCanPressASpecificListsItems() { int whichList = 1; brazenhead.pressListItemByIndex(7, whichList); verify(listItemPresser).pressListItem(7, whichList); } @Test public void itCanFindWebViewsByVariousProperties() { final HashMap<String, String> hows = new HashMap<String, String>(); hows.put("id", "Id"); hows.put("xpath", "Xpath"); hows.put("cssSelector", "CssSelector"); hows.put("name", "Name"); hows.put("className", "ClassName"); hows.put("textContent", "Text"); hows.put("tagName", "TagName"); for(final Map.Entry<String, String> how : hows.entrySet()) { brazenhead.getWebViewsBy(how.getKey(), "does not matter"); final ArgumentCaptor<By> byArgument = ArgumentCaptor.forClass(By.class); verify(solo).getCurrentWebElements(byArgument.capture()); assertThat(byArgument.getValue().getClass().getName(), is(by(how.getValue()))); reset(solo); } } @Test public void itCanFindWebViewsByName() { brazenhead.getWebViewsBy("name", "blar"); final ArgumentCaptor<By> byArgument = ArgumentCaptor.forClass(By.class); verify(solo).getCurrentWebElements(byArgument.capture()); assertThat(byArgument.getValue().getClass().getName(), is(by("Name"))); } private void initMocks() { TestRunInformation.setSolo(solo); when(solo.getCurrentActivity()).thenReturn(activity); when(activity.getResources()).thenReturn(resources); } private String by(final String how) { return String.format("com.jayway.android.robotium.solo.By$%s", how); } }
package org.jgroups.tests; import org.jgroups.Global; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.View; import org.jgroups.stack.GossipRouter; import org.jgroups.util.Promise; import org.jgroups.util.Util; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Ensures that a disconnected channel reconnects correctly, for different stack * configurations. * * * @version $Id: TUNNEL_Test2.java,v 1.3 2009/02/17 15:03:51 vlada Exp $ **/ @Test(groups = Global.STACK_INDEPENDENT, sequential = true) public class TUNNEL_Test2 extends ChannelTestBase { private JChannel channel, coordinator; private final static String GROUP = "TUNNEL_Test2"; private GossipRouter gossipRouter1, gossipRouter2; private static final String props = "tunnel2.xml"; @BeforeClass void startRouter() throws Exception { gossipRouter1 = new GossipRouter(12002); gossipRouter1.start(); gossipRouter2 = new GossipRouter(12003); gossipRouter2.start(); } @AfterClass void stopRouter() throws Exception { gossipRouter1.stop(); gossipRouter2.stop(); } @AfterMethod void tearDown() throws Exception { Util.close(channel, coordinator); } public void testSimpleConnect() throws Exception { channel = new JChannel(props); channel.connect(GROUP); assert channel.getLocalAddress() != null; channel.disconnect(); assert channel.getLocalAddress() == null; } /** * Tests connect with two members * **/ public void testConnectTwoChannels() throws Exception { coordinator = new JChannel(props); channel = new JChannel(props); coordinator.connect(GROUP); channel.connect(GROUP); View view = channel.getView(); assert view.size() == 2; assert view.containsMember(channel.getLocalAddress()); assert view.containsMember(coordinator.getLocalAddress()); } public void testConnectThreeChannels() throws Exception { coordinator = new JChannel(props); channel = new JChannel(props); coordinator.connect(GROUP); channel.connect(GROUP); JChannel third = new JChannel(props); third.connect(GROUP); View view = channel.getView(); assert channel.getView().size() == 3; assert third.getView().size() == 3; assert view.containsMember(channel.getLocalAddress()); assert view.containsMember(coordinator.getLocalAddress()); Util.close(third); } public void testConnectSendMessage() throws Exception { final Promise<Message> msgPromise = new Promise<Message>(); coordinator = new JChannel(props); coordinator.connect(GROUP); coordinator.setReceiver(new PromisedMessageListener(msgPromise)); channel = new JChannel(props); channel.connect(GROUP); channel.send(new Message(null, null, "payload")); Message msg = msgPromise.getResult(20000); assert msg != null; assert "payload".equals(msg.getObject()); } public void testConnectSendMessageSecondGRDown() throws Exception { try { final Promise<Message> msgPromise = new Promise<Message>(); coordinator = new JChannel(props); coordinator.connect(GROUP); coordinator.setReceiver(new PromisedMessageListener(msgPromise)); channel = new JChannel(props); channel.connect(GROUP); gossipRouter2.stop(); channel.send(new Message(null, null, "payload")); Message msg = msgPromise.getResult(20000); assert msg != null; assert "payload".equals(msg.getObject()); } finally { if(!gossipRouter2.isStarted()) gossipRouter2.start(); } } public void testConnectSendMessageFirstGRDown() throws Exception { try { final Promise<Message> msgPromise = new Promise<Message>(); coordinator = new JChannel(props); coordinator.connect(GROUP); coordinator.setReceiver(new PromisedMessageListener(msgPromise)); channel = new JChannel(props); channel.connect(GROUP); gossipRouter1.stop(); channel.send(new Message(null, null, "payload")); Message msg = msgPromise.getResult(20000); assert msg != null; assert "payload".equals(msg.getObject()); } finally { if(!gossipRouter1.isStarted()) gossipRouter1.start(); } } private static class PromisedMessageListener extends ReceiverAdapter { private final Promise<Message> promise; public PromisedMessageListener(Promise<Message> promise) { this.promise = promise; } public void receive(Message msg) { promise.setResult(msg); } } }
import java.util.*; /* * Instances of this class are used to record the current * search pattern through the tunnels. We need to remember * the starting point, the keys we've found and the number * of steps to this stage. */ // Was essentially State in part 1. public class Journey { public Journey (List<Coordinate> entrances) { this(entrances, Collections.emptySet(), 0); } public Journey (List<Coordinate> entrances, Set<Character> keys, int steps) { _locations = entrances; _keys = keys; _steps = steps; _id = Util.keycode(_keys); } public final Coordinate getRobotLocation (int robot) { return _locations.get(robot); } public final Set<Character> getKeys () { return _keys; } public final int getSteps () { return _steps; } @Override public int hashCode () { return _locations.hashCode(); } @Override public boolean equals (Object obj) { if (obj == null) return false; if (this == obj) return true; if (getClass() == obj.getClass()) { Journey temp = (Journey) obj; // assume order matters for equality too! if (temp._locations.size() == _locations.size()) { for (int i = 0; i < temp._locations.size(); i++) { if (!temp._locations.get(i).equals(_locations.get(i))) return false; } return temp._keys.containsAll(_keys); } } return false; } @Override public String toString() { return "Journey < "+_id+ ", " + _steps+" >"; } private List<Coordinate> _locations; private Set<Character> _keys; private int _steps; private String _id; }
package gamePlayer.guiFeatures; import java.io.File; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Window; /** * Class loads directories * @author allankiplagat * */ public class FileLoader { private static FileLoader myReference = null; private FileLoader() { } public static FileLoader getInstance() { if (myReference==null) { myReference = new FileLoader(); } return myReference; } /** * @param stage the stage that directory loading is associated with * @return */ public File load(Window stage) { DirectoryChooser chooser = new DirectoryChooser(); chooser.setInitialDirectory(new File("./Games/")); return chooser.showDialog(stage); } /** * @param stage the stage that file loading is associated with * @param extensions to be filtered * @return */ public File load(Window stage, String fileType, String ... extensions) { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().add(new ExtensionFilter(fileType, extensions)); return chooser.showOpenDialog(stage); } }
package tlc2.tool.liveness; import java.io.IOException; import tlc2.tool.StateVec; import tlc2.tool.TLCState; import tlc2.tool.Tool; import tlc2.util.LongVec; import tlc2.util.statistics.IBucketStatistics; public interface ILiveCheck { /** * This method records that state is an initial state in the behavior graph. * It is called when a new initial state is generated. */ void addInitState(TLCState state, long stateFP); /** * This method adds new nodes into the behavior graph induced by s0. It is * called after the successors of s0 are computed. */ void addNextState(TLCState s0, long fp0, StateVec nextStates, LongVec nextFPs) throws IOException; /** * true iff a call to {@link ILiveCheck#check(boolean)} would indeed result in liveness checking. */ boolean doLiveCheck(); /** * Check liveness properties for the current (potentially partial) state graph. Returns * true iff it finds no errors. * * @param forceCheck * Always checks liveness if true, otherwise heuristics about the * partial graph are taken into account if it is worthwhile to * check liveness. * @return true iff it finds no errors or if liveness has not been checked * on the partial graph because it was deemed worthless. */ boolean check(boolean forceCheck) throws Exception; /** * No states can be added with add*State once finalCheck has been called. * * @see ILiveCheck#check() * @return * @throws Exception */ boolean finalCheck() throws Exception; /* simulation mode */ /** * This method is the mutual exclusive counterpart to addInitState and * addNextState. Where the two each take a single state and its successors, * checkTrace expects a sequence of TLCStates. The first state in this sequence * is seen as the init state whereas the remaining states in the sequence belong * to the behavior started by the init state. * <p> * checkTrace behaves similar to adding the sequence's first state with addInitState * and the others with addNextState. However, checkTrace is meant to be used * in simulation mode (see Simulator) only. Don't call check or finalCheck, it * is done as part of checkTrace. * <p> * checkTrace can be called multiple times until ILiveCheck has been closed (see close()). * * @param trace * @throws IOException * @throws InterruptedException */ void checkTrace(final StateVec trace) throws IOException, InterruptedException; /* auxiliary methods */ String getMetaDir(); Tool getTool(); IBucketStatistics getOutDegreeStatistics(); ILiveChecker getChecker(int idx); int getNumChecker(); /* Close all the files for disk graphs. */ void close() throws IOException; /* Checkpoint. */ void beginChkpt() throws IOException; void commitChkpt() throws IOException; void recover() throws IOException; IBucketStatistics calculateInDegreeDiskGraphs(IBucketStatistics aGraphStats) throws IOException; IBucketStatistics calculateOutDegreeDiskGraphs(IBucketStatistics aGraphStats) throws IOException; void reset() throws IOException; }
package tlc2.tool.liveness; import java.io.IOException; import java.util.concurrent.BlockingQueue; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.output.StatePrinter; import tlc2.tool.EvalException; import tlc2.tool.TLCState; import tlc2.tool.TLCStateInfo; import tlc2.util.IdThread; import tlc2.util.IntStack; import tlc2.util.LongVec; import tlc2.util.MemIntQueue; import tlc2.util.MemIntStack; import tlc2.util.SynchronousDiskIntStack; import tlc2.util.statistics.BucketStatistics; import tlc2.util.statistics.IBucketStatistics; /** * {@link LiveWorker} is doing the heavy lifting of liveness checking: * <ul> * <li>Searches for strongly connected components (SCC) a.k.a. cycles in the * liveness/behavior graph.</li> * <li>Checks each SCC if it violates the liveness properties.</li> * <li>In case of a violation, reconstructs and prints the error trace.</li> * </ul> */ public class LiveWorker extends IdThread { /** * A marker that is pushed onto the dfsStack during SCC depth-first-search * to marker an explored nodes on the stack. * <p> * A node with a marker is on the comStack. */ private static final long SCC_MARKER = -42L; public static final IBucketStatistics STATS = new BucketStatistics("Histogram SCC sizes", LiveWorker.class .getPackage().getName(), "StronglyConnectedComponent sizes"); private static int errFoundByThread = -1; private static final Object workerLock = new Object(); private OrderOfSolution oos = null; private AbstractDiskGraph dg = null; private PossibleErrorModel pem = null; private final ILiveCheck liveCheck; private final BlockingQueue<ILiveChecker> queue; private final boolean isFinalCheck; /** * Total number of LiveWorkers simultaneously checking liveness. */ private final int numWorkers; public LiveWorker(int id, int numWorkers, final ILiveCheck liveCheck, final BlockingQueue<ILiveChecker> queue, final boolean finalCheck) { super(id); this.numWorkers = numWorkers; this.liveCheck = liveCheck; this.queue = queue; this.isFinalCheck = finalCheck; // Set the name to something more indicative than "Thread-4711". this.setName("TLCLiveWorkerThread-" + String.format("%03d", id)); } /** * Returns true iff an error has already been found. */ public static boolean hasErrFound() { synchronized (workerLock) { return (errFoundByThread != -1); } } /** * Returns true iff either an error has not been found or the error is found * by this thread. * <p> * This is used so that only one of the threads which have found an error * prints it. */ private/* static synchronized */boolean setErrFound() { synchronized (workerLock) { if (errFoundByThread == -1) { errFoundByThread = this.myGetId(); // GetId(); return true; } else if (errFoundByThread == this.myGetId()) { // (* GetId()) { return true; } return false; } } private final void checkSccs() throws IOException { // Initialize this.dg: this.dg.makeNodePtrTbl(); // Initialize nodeQueue with initial states. The initial states stored // separately in the DiskGraph are resolved to their pointer location // in the on-disk part of the DiskGraph. // The pointer location generally is obviously used to: // * Speed up disk lookups in the RandomAccessFile(s) backing up the DiskGraph // * Is replaced by the SCC link number the moment the node's successors // are explored during DFS search. At this point the ptr location isn't // needed anymore. The successors have been resolved. // From each node in nodeQueue the SCC search is started down below, // which can subsequently add additional nodes into nodeQueue. // Contrary to plain Tarjan, not all vertices are added to the // nodeQueue of unexplored states, but only the initial states. Since we // know that all non-initial states are reachable from the set of // initial states, this is sufficient to start with. final LongVec initNodes = this.dg.getInitNodes(); final int numOfInits = initNodes.size(); // Allocate space for all initial states, assuming the majority of // initial nodes will be done. Multiplied by 5 because of // <<long, int, long>> per "record. final MemIntQueue nodeQueue = new MemIntQueue(liveCheck.getMetaDir(), "root", (numOfInits / 2) * 5); for (int j = 0; j < numOfInits; j += 2) { final long state = initNodes.elementAt(j); final int tidx = (int) initNodes.elementAt(j + 1); final long ptr = this.dg.getLink(state, tidx); // Check if the node <<state, tidx>> s is done. A node s is undone // if it is an initial state which hasn't been explored yet. This is // the case if s has been added via LiveChecker#addInitState but not // yet via LiveChecker#addNextState. LiveChecker#addNextState fully // explores the given init state s because it has access to s' // successors. if (ptr >= 0) { // Make sure none of the init states has already been assigned a // link number. That would indicate a bug in makeNodePtrTbl // which is supposed to reset all link numbers to file ptrs. assert DiskGraph.isFilePointer(ptr); nodeQueue.enqueueLong(state); nodeQueue.enqueueInt(tidx); nodeQueue.enqueueLong(ptr); } else { // If this is the final check on the complete graph, no node is // allowed to be undone. If it's not the final check, ptr has to // be UNDONE (a non-UNDONE negative pointer is probably a bug). // isFinalCheck => ptr # UNDONE assert !isFinalCheck || ptr != TableauNodePtrTable.UNDONE; } } final int[] eaaction = this.pem.EAAction; final int slen = this.oos.getCheckState().length; final int alen = this.oos.getCheckAction().length; // Tarjan's stack // Append thread id to name for unique disk files during concurrent SCC search final IntStack dfsStack = getStack(liveCheck.getMetaDir(), "dfs" + this.myGetId()); // comStack is only being added to during the deep first search. It is passed // to the checkComponent method while in DFS though. Note that the nodes pushed // onto comStack don't necessarily form a strongly connected component (see // comment above this.checkComponent(...) below for more details). // See tlc2.tool.liveness.LiveWorker.DetailedFormatter.toString(MemIntStack) // which is useful during debugging. final IntStack comStack = getStack(liveCheck.getMetaDir(), "com" + this.myGetId()); // Generate the SCCs and check if they contain a "bad" cycle. while (nodeQueue.size() > 0) { // Pick one of the unexplored nodes as root and start searching the // reachable SCCs from it. final long state = nodeQueue.dequeueLong(); final int tidx = nodeQueue.dequeueInt(); final long loc = nodeQueue.dequeueLong(); // Reset (remove all elements) the stack. Logically a new SCC search // is being started unrelated to the previous one. dfsStack.reset(); // Push the first node onto the DFS stack which makes it the node // from which the depth-first-search is being started. dfsStack.pushLong(state); dfsStack.pushInt(tidx); dfsStack.pushLong(loc); // Push the smallest possible link number (confusingly called // MAX_PTR here but only because file pointers are < MAX_PTR) as the // first link number. // [0, MAX_PTR) for file pointers // [MAX_PTR, MAX_LINK] for links dfsStack.pushLong(DiskGraph.MAX_PTR); long newLink = DiskGraph.MAX_PTR; while (dfsStack.size() >= 7) { final long lowLink = dfsStack.popLong(); final long curLoc = dfsStack.popLong(); final int curTidx = dfsStack.popInt(); final long curState = dfsStack.popLong(); // At this point curLoc is still a file pointer (small MAX_PTR) // and not yet replaced by a link (MAX_PTR < curLoc < MAX_LINK). assert DiskGraph.isFilePointer(curLoc); // The current node is explored iff curLoc < 0. If it is indeed fully explored, // it means it has potentially found an SCC. Thus, check if this is the case // for the current GraphNode. // A node is fully explored if the nested loop over its // successors down below in the else branch has not revealed any // unexplored successors. if (curLoc == SCC_MARKER) { // Check if the current node's link is lowLink which // indicates that the nodes on comStack up to <<curState, // curTidx>> form an SCC. // If curLink # lowLink, continue by pop'ing the next node // from dfsStack. It can either be: // - unexplored in which case the else branch is taken and // DFS continues. // - be an intermediate node of the SCC and thus curLink // lowLink for it too. // - can be the start of the SCC (curLink = lowLink). final long curLink = this.dg.getLink(curState, curTidx); assert curLink < AbstractDiskGraph.MAX_LINK; if (curLink == lowLink) { // The states on the comStack from "top" to <<curState, // curTidx>> form an SCC, thus check for "bad" cycle. // The cycle does not necessarily include all states in // comStack. "top" might very well be curState in which // case only a single state is checked by // checkComponent. // The aforementioned case happens regularly when the // behaviors to check don't have cycles at all (leaving // single node cycles aside for the moment). The DFS // followed each behavior from its initial state (see // nodeQueue) all the way to the behavior's end state at // which point DFS halts. Since DFS cannot continue // (there are no successors) it calls checkComponent now // with the current comStack and the end state as // <<curState, curTidx>> effectively checking the // topmost element of comStack. Unless this single state // violates any liveness properties, it gets removed // from comStack and DFS continues. Iff DFS still cannot // continue because the predecessor to endstate // (endstate - 1) has no more successors to explore // either, it again calls checkComponent for the single // element (endstate - 1). This goes on until either the // initial state is reached or an intermediate state has // unexplored successors with DFS. final boolean isOK = this.checkComponent(curState, curTidx, comStack); if (!isOK) { // Found a "bad" cycle of one to comStack.size() // nodes, no point in searching for more SCCs as we // are only interested in one counter-example at a // time. // checkComponent will have printed the // counter-example by now. return; } } // Replace previous lowLink (plowLink) with the minimum of // the current lowLink and plowLink on the stack. final long plowLink = dfsStack.popLong(); dfsStack.pushLong(Math.min(plowLink, lowLink)); // No SCC found yet } else { // Assign newLink to curState: final long link = this.dg.putLink(curState, curTidx, newLink); // link is -1 if newLink has been assigned to pair // <<curState, curTidx>>. If the pair had been assigned a // link before, the previous link in range [MAX_PTR, // MAX_LINK] is returned. If the link is not -1, it means // the node has been explored by this DFS search before. if (link == -1) { // Push curState back onto dfsStack, but make curState // explored: dfsStack.pushLong(lowLink); dfsStack.pushLong(curState); dfsStack.pushInt(curTidx); // Push a marker onto the stack that, if pop'ed as // curLoc above causes branching to enter the true case // of the if block. dfsStack.pushLong(SCC_MARKER); // Add the tuple <<curState, curTidx, curLoc>> to comStack: comStack.pushLong(curLoc); comStack.pushInt(curTidx); comStack.pushLong(curState); // Look at all the successors of curState: final GraphNode gnode = this.dg.getNode(curState, curTidx, curLoc); final int succCnt = gnode.succSize(); long nextLowLink = newLink; // DFS moved on to a new node, thus increment the newLink // number by 1 for subsequent exploration. newLink = newLink + 1; for (int i = 0; i < succCnt; i++) { final long nextState = gnode.getStateFP(i); final int nextTidx = gnode.getTidx(i); final long nextLink = this.dg.getLink(nextState, nextTidx); // If <<nextState, nextTidx>> node's link is < 0 it // means the node isn't "done" yet (see // tlc2.tool.liveness.TableauNodePtrTable.UNDONE). // A successor node t of gnode is undone if it is: // - An initial state which hasn't been explored yet // - t has not been added to the liveness disk graph // itself (only as the successor (transition) of // gnode). // If it is >= 0, it either is a: // - file pointer location // - a previously assigned link (>= MAX_PTR) // Iff nextLink == MAX_PTR, it means that the // <<nextState, nextTidx>> successor node has been // processed by checkComponent. The checks below // will result in the successor node being skipped. // It is possible that <<nextState, nextTidx>> = // <<curState, curTid>> due to self loops. This is // intended, as checkAction has to be evaluated for // self loops too. if (nextLink >= 0) { // Check if the arc/transition from <<curState, // curTidx>> to <<nextState, nextTidx>> // satisfies ("P-satisfiable" MP page 422ff) // its PEM's EAAction. If it does, 1/3 of the // conditions for P-satisfiability are // satisfied. Thus it makes sense to check the // other 2/3 in checkComponent (AEAction & // Fulfilling promises). If the EAAction does // not hold, there is no point in checking the // other 2/3. All must hold for // P-satisfiability. // This check is related to the fairness spec. // Usually, it evals to true when no or weak // fairness have been specified. False on strong // fairness. if (gnode.getCheckAction(slen, alen, i, eaaction)) { // If the node's nextLink still points to // disk, it means it has no link assigned // yet which is the case if this node gets // explored during DFS search the first // time. Since it is new, add it to dfsStack // to have it explored subsequently by DFS. if (DiskGraph.isFilePointer(nextLink)) { dfsStack.pushLong(nextState); dfsStack.pushInt(nextTidx); dfsStack.pushLong(nextLink); // nextLink is logically a ptr/loc here // One would expect a (logical) lowLink // being pushed (additionally to the // ptr/loc in previous line) onto the // stack here. However, it is pushed // down below after all successors are // on the stack and valid for the // topmost successor. For the other // successors below the topmost, a link // number will be assigned subsequently. } else { // The node has been processed // already, thus use the minimum of its link // (nextLink) and nextLowLink. nextLowLink = Math.min(nextLowLink, nextLink); } } else { // The transition from <<curState, curTidx>> // to <<nextState, nextTidx>> is not // P-satisfiable and thus does not need to // be checkComponent'ed. However, since we // only added initial but no intermediate // states to nodeQueue above, we have to add // <<nextState, nextTidx>> to nodeQueue if // it's still unprocessed (indicated by its // on disk state). The current path // potentially might be the only one by // which DFS can reach it. if (DiskGraph.isFilePointer(nextLink)) { nodeQueue.enqueueLong(nextState); nodeQueue.enqueueInt(nextTidx); nodeQueue.enqueueLong(nextLink); // nextLink is logically a ptr/loc here } } } else { // If this is the final check on the complete // graph, no node is allowed to be undone. If // it's not the final check, nextLink has to be // UNDONE (a non-UNDONE negative nextLink is // probably a bug). // isFinalCheck => nextLink # UNDONE assert !isFinalCheck || nextLink != TableauNodePtrTable.UNDONE; } } // Push the next lowLink onto stack on top of all // successors. It is assigned to the topmost // successor only though. dfsStack.pushLong(nextLowLink); } else { // link above wasn't "-1", thus it has to be a valid // link in the known interval. assert AbstractDiskGraph.MAX_PTR <= link && link <= AbstractDiskGraph.MAX_LINK; // Push the minimum of the two links onto the stack. If // link == DiskGraph.MAX_PTR lowLink will always be the // minimum (unless this graph has a gigantic amount of // SCCs exceeding (MAX_LINK - MAX_PTR). dfsStack.pushLong(Math.min(lowLink, link)); } } } } // Make sure all nodes on comStack have been checkComponent()'ed assert comStack.size() == 0; } private IntStack getStack(final String metaDir, final String name) throws IOException { // Synchronize all LiveWorker instances to consistently read free // memory. This method is only called during initialization of SCC // search, thus synchronization should not cause significant thread // contention. synchronized (LiveWorker.class) { // It is unlikely that the stacks will fit into memory if the // size of the behavior graph is larger relative to the available // memory. Also take the total number of simultaneously running // workers into account that have to share the available memory // among each other. final double freeMemoryInBytes = (Runtime.getRuntime().freeMemory() / (numWorkers * 1d)); final long graphSizeInBytes = this.dg.getSizeOnDisk(); final double ratio = graphSizeInBytes / freeMemoryInBytes; if (ratio > TLCGlobals.livenessGraphSizeThreshold) { // Double SDIS's bufSize/pageSize by how much the graph size // overshoots the free memory size, but limit page size to 1gb. // Also, don't allocate more than what is available. final int capacityInBytes = SynchronousDiskIntStack.BufSize << Math.min((int) ratio, 5); if (capacityInBytes < freeMemoryInBytes) { return new SynchronousDiskIntStack(metaDir, name, capacityInBytes); } else { // Use default SDIS which is 32mb of in-memory size return new SynchronousDiskIntStack(metaDir, name); } } // If the disk graph as a whole fits into memory, do not use a // disk-backed SynchronousDiskIntStack. return new MemIntStack(metaDir, name); } } private boolean checkComponent(final long state, final int tidx, final IntStack comStack) throws IOException { final long comStackSize = comStack.size(); // There is something to pop and each is a well formed tuple <<fp, tidx, loc>> assert comStackSize >= 5 && comStackSize % 5 == 0; // long + int + long long state1 = comStack.popLong(); int tidx1 = comStack.popInt(); long loc1 = comStack.popLong(); // Simply return if the component is trivial: It is trivial iff the component // has a single node AND this node is *no* stuttering node. if (state1 == state && tidx1 == tidx && !isStuttering(state1, tidx1, loc1)) { this.dg.setMaxLink(state, tidx); return true; } // Now, we know we are working on a non-trivial component // We first put all the nodes in this component in a hashtable. // The nodes in this component do not correspond to // all elements on the comStack though. Only the nodes up to // the given one are copied to NodePtrTable. // The NodePtrTable would ideally be initialized with the number of // nodes in the comStack. This is the upper limit of elements going // to be kept in com. However, it would destroy NodePtrTable's // collision handling. NodePtrTable uses open addressing (see // Initializing the NTPT with 128 buckets/slows is a significant memory // overhead (especially when comStack contains < 10 elements) which // regularly results in OutOfMemoryErrors being thrown. To alleviate the // problem the key-space of the comStack elements could be checked and // the minimum possible collision-free TNPT size be calculated. // (Btw. the implementation uses a TNPT in the first place because it is // passed on to printTrace iff an error is found. The implementation // here could use a simple java.util.Map or HashTable technically.) final TableauNodePtrTable com = new TableauNodePtrTable(128); while (true) { // Add <state1, tidx1> into com: com.put(state1, tidx1, loc1); this.dg.setMaxLink(state1, tidx1); // Get the next node of the component: if (state == state1 && tidx == tidx1) { break; } state1 = comStack.popLong(); tidx1 = comStack.popInt(); loc1 = comStack.popLong(); } // Just parameter node in com OR com subset of comStack assert com.size() <= (comStackSize / 5); STATS.addSample(com.size()); // Check this component: final int slen = this.oos.getCheckState().length; final int alen = this.oos.getCheckAction().length; final int aeslen = this.pem.AEState.length; final int aealen = this.pem.AEAction.length; final int plen = this.oos.getPromises().length; final boolean[] AEStateRes = new boolean[aeslen]; final boolean[] AEActionRes = new boolean[aealen]; final boolean[] promiseRes = new boolean[plen]; // Extract a node from the nodePtrTable "com". // Note the upper limit is NodePtrTable#getSize() instead of // the more obvious NodePtrTable#size(). // NodePtrTable internally hashes the elements to buckets // and isn't filled start to end. Thus, the code // below iterates NodePtrTable front to end skipping null buckets. // Note that the nodes are processed in random order (depending on a // node's hash in TableauNodePtrTbl) and not in the order given by // comStack. This is fine because the all checks have been evaluated // eagerly during insertion into the liveness graph long before the // SCC search started. Thus, the code here only has to check the // check results which can happen in any order. final int tsz = com.getSize(); for (int ci = 0; ci < tsz; ci++) { final int[] nodes = com.getNodesByLoc(ci); if (nodes == null) { // miss in NotePtrTable (null bucket) continue; } state1 = TableauNodePtrTable.getKey(nodes); for (int nidx = 2; nidx < nodes.length; nidx += com.getElemLength()) { // nidx starts with 2 because [0][1] are the long fingerprint state1. tidx1 = TableauNodePtrTable.getTidx(nodes, nidx); loc1 = TableauNodePtrTable.getElem(nodes, nidx); final GraphNode curNode = this.dg.getNode(state1, tidx1, loc1); // Check AEState: for (int i = 0; i < aeslen; i++) { // Only ever set AEStateRes[i] to true, but never to false // once it was true. It only matters if one state in com // the inversion of <>[]p). // It obviously has to check all nodes in the component // (com) if either of them violates AEState unless all // elements of AEStateRes are true. From that point onwards, // checking further states wouldn't make a difference. if (!AEStateRes[i]) { int idx = this.pem.AEState[i]; AEStateRes[i] = curNode.getCheckState(idx); // Can stop checking AEStates the moment AEStateRes // is completely set to true. However, most of the time // aeslen is small and the compiler will probably optimize // out. } } // All EAAction have already been checked as part of checkSccs! // Check AEAction: A TLA+ temporal action represents the // relationship between the current node and a successor state // in the scope of the behavior. The current node has n // successor states. final int succCnt = aealen > 0 ? curNode.succSize() : 0; // No point in looping successors if there are no AEActions to check on them. for (int i = 0; i < succCnt; i++) { final long nextState = curNode.getStateFP(i); final int nextTidx = curNode.getTidx(i); // For each successor <<nextState, nextTdix>> of curNode's // successors check, if it is part of the currently // processed SCC (com). Successors, which are not part of // the current SCC have obviously no relevance here. After // all, we check the SCC. if (com.getLoc(nextState, nextTidx) != -1) { for (int j = 0; j < aealen; j++) { // Only set false to true, but never true to false. if (!AEActionRes[j]) { final int idx = this.pem.AEAction[j]; AEActionRes[j] = curNode.getCheckAction(slen, alen, i, idx); } } } } // Check that the component is fulfilling. (See MP page 453.) // Note that the promises are precomputed and stored in oos. for (int i = 0; i < plen; i++) { final LNEven promise = this.oos.getPromises()[i]; final TBPar par = curNode.getTNode(this.oos.getTableau()).getPar(); if (par.isFulfilling(promise)) { promiseRes[i] = true; } } } } // We find a counterexample if all three conditions are satisfied. If // either of the conditions is false, it means the PEM does not hold and // thus the liveness properties are not violated by the SCC. // All AEState properties, AEActions and promises of PEM must be // satisfied. If a single one isn't satisfied, the PEM as a whole isn't // P-satisfiable. That's why it returns on the first false. As stated // before, EAAction have already been checked if satisfiable. // checkComponent is only called if the EA actions are satisfiable. for (int i = 0; i < aeslen; i++) { if (!AEStateRes[i]) { return true; } } for (int i = 0; i < aealen; i++) { if (!AEActionRes[i]) { return true; } } for (int i = 0; i < plen; i++) { if (!promiseRes[i]) { return true; } } // This component must contain a counter-example because all three // conditions are satisfied. So, print a counter-example (if this thread // is the first one to find a counter-example)! if (setErrFound()) { this.printTrace(state, tidx, com); } return false; } /* Check if the node <state, tidx> stutters. */ private boolean isStuttering(long state, int tidx, long loc) throws IOException { final int slen = this.oos.getCheckState().length; final int alen = this.oos.getCheckAction().length; // Find the self loop and check its <>[]action final GraphNode gnode = this.dg.getNode(state, tidx, loc); final int succCnt = gnode.succSize(); for (int i = 0; i < succCnt; i++) { final long nextState = gnode.getStateFP(i); final int nextTidx = gnode.getTidx(i); if (state == nextState && tidx == nextTidx) { return gnode.getCheckAction(slen, alen, i, this.pem.EAAction); } } // <state, tidx> has no self loop, thus cannot stutter return false; } /** * Print out the error state trace. The method first generates a "bad" cycle * from the current scc, and then generates a prefix path from some initial * state to the "bad" cycle in the state graph. The prefix path and the * "bad" cycle together forms a counter-example. * <p> * Additionally, the first part can be divided into the two while loops A) * and B). A) re-creates the sub-path of the error trace starting at the * start state of the SCC as given by the parameters and ends when all * states have be accumulated that -combined- violate the liveness * properties. Iff the last state after termination of A) is not equal to * the start state, there is a gap in the cycle. Thus, B) task is to close * the gap. * <p> * * @see tlatools/test-model/symmetry/ErrorTraceConstructionPhases.png for a * sketch. * @see tlc2.tool.liveness.ErrorTraceConstructionTest which runs a spec that * exemplifies the three staged error trace composition */ private void printTrace(final long state, final int tidx, final TableauNodePtrTable nodeTbl) throws IOException { MP.printError(EC.TLC_TEMPORAL_PROPERTY_VIOLATED); MP.printError(EC.TLC_COUNTER_EXAMPLE); // First, find a "bad" cycle from the "bad" scc. final int slen = this.oos.getCheckState().length; final int alen = this.oos.getCheckAction().length; // The 3 boolean arrays are used to make sure that the same check result // is exactly counted once. final boolean[] AEStateRes = new boolean[this.pem.AEState.length]; final boolean[] AEActionRes = new boolean[this.pem.AEAction.length]; final boolean[] promiseRes = new boolean[this.oos.getPromises().length]; // The number/count of all liveness checks. The while loop A) terminates // once it has accumulated all states that violate all checks (we know // that the states in nodeTbl have to violate the liveness property // because we are in printTrace already. checkComponent has already // determined that there is a violation). int cnt = AEStateRes.length + AEActionRes.length + promiseRes.length; final MemIntStack cycleStack = new MemIntStack(liveCheck.getMetaDir(), "cycle"); // Mark state as visited: int[] nodes = nodeTbl.getNodes(state); int tloc = nodeTbl.getIdx(nodes, tidx); final long ptr = TableauNodePtrTable.getElem(nodes, tloc); TableauNodePtrTable.setSeen(nodes, tloc); GraphNode curNode = this.dg.getNode(state, tidx, ptr); while (cnt > 0) { int cnt0 = cnt; _next: while (true) { // Check AEState: for (int i = 0; i < this.pem.AEState.length; i++) { int idx = this.pem.AEState[i]; if (!AEStateRes[i] && curNode.getCheckState(idx)) { AEStateRes[i] = true; cnt } } // Check if the component is fulfilling. (See MP page 453.) // Note that the promises are precomputed and stored in oos. for (int i = 0; i < this.oos.getPromises().length; i++) { LNEven promise = this.oos.getPromises()[i]; TBPar par = curNode.getTNode(this.oos.getTableau()).getPar(); if (!promiseRes[i] && par.isFulfilling(promise)) { promiseRes[i] = true; cnt } } if (cnt <= 0) { break; } // Check AEAction (which is a check of the out-arc of curNode to // one of its successors): long nextState1 = 0, nextState2 = 0; int nextTidx1 = 0, nextTidx2 = 0; int tloc1 = -1, tloc2 = -1; int[] nodes1 = null, nodes2 = null; boolean hasUnvisitedSucc = false; int cnt1 = cnt; int succCnt = curNode.succSize(); for (int i = 0; i < succCnt; i++) { long nextState = curNode.getStateFP(i); int nextTidx = curNode.getTidx(i); nodes = nodeTbl.getNodes(nextState); if (nodes != null) { tloc = nodeTbl.getIdx(nodes, nextTidx); if (tloc != -1) { // <nextState, nextTidx> is in nodeTbl. nextState1 = nextState; nextTidx1 = nextTidx; tloc1 = tloc; nodes1 = nodes; for (int j = 0; j < this.pem.AEAction.length; j++) { int idx = this.pem.AEAction[j]; if (!AEActionRes[j] && curNode.getCheckAction(slen, alen, i, idx)) { AEActionRes[j] = true; cnt } } } } if (cnt < cnt1) { // Take curNode -> <nextState, nextTidx>: cycleStack.pushInt(curNode.tindex); cycleStack.pushLong(curNode.stateFP); long nextPtr = TableauNodePtrTable.getPtr(TableauNodePtrTable.getElem(nodes, tloc)); curNode = this.dg.getNode(nextState, nextTidx, nextPtr); nodeTbl.resetElems(); break _next; } if (nodes != null && tloc != -1 && !TableauNodePtrTable.isSeen(nodes, tloc)) { // <nextState, nextTidx> is an unvisited successor of // curNode: hasUnvisitedSucc = true; nextState2 = nextState; nextTidx2 = nextTidx; tloc2 = tloc; nodes2 = nodes; } } if (cnt < cnt0) { // Take curNode -> <nextState1, nextTidx1>: cycleStack.pushInt(curNode.tindex); cycleStack.pushLong(curNode.stateFP); long nextPtr = TableauNodePtrTable.getPtr(TableauNodePtrTable.getElem(nodes1, tloc1)); curNode = this.dg.getNode(nextState1, nextTidx1, nextPtr); nodeTbl.resetElems(); break; } // Backtrack if all successors of curNode have been visited // and no successor can reduce cnt. while (!hasUnvisitedSucc) { long curState = cycleStack.popLong(); int curTidx = cycleStack.popInt(); long curPtr = TableauNodePtrTable.getPtr(nodeTbl.get(curState, curTidx)); curNode = this.dg.getNode(curState, curTidx, curPtr); succCnt = curNode.succSize(); for (int i = 0; i < succCnt; i++) { nextState2 = curNode.getStateFP(i); nextTidx2 = curNode.getTidx(i); nodes2 = nodeTbl.getNodes(nextState2); if (nodes2 != null) { tloc2 = nodeTbl.getIdx(nodes2, nextTidx2); if (tloc2 != -1 && !TableauNodePtrTable.isSeen(nodes2, tloc2)) { hasUnvisitedSucc = true; break; } } } } // Take curNode -> <nextState2, nextTidx2>. Set nextState2 // visited. cycleStack.pushInt(curNode.tindex); cycleStack.pushLong(curNode.stateFP); long nextPtr = TableauNodePtrTable.getPtr(TableauNodePtrTable.getElem(nodes2, tloc2)); curNode = this.dg.getNode(nextState2, nextTidx2, nextPtr); TableauNodePtrTable.setSeen(nodes2, tloc2); } } // All the conditions are satisfied. Find a path from curNode // to state to form a cycle. Note that: // 1. curNode has not been pushed on cycleStack. // 2. nodeTbl is trashed after this operation. nodeTbl.resetElems(); final LongVec postfix = new LongVec(16); long startState = curNode.stateFP; /* * If the cycle is not closed/completed (complete when startState == * state), continue from the curNode at which the previous while loop * terminated and follow its successors until the start state shows up. */ if (startState != state) { MemIntQueue queue = new MemIntQueue(liveCheck.getMetaDir(), null); long curState = startState; int ploc = -1; int curLoc = nodeTbl.getNodesLoc(curState); nodes = nodeTbl.getNodesByLoc(curLoc); TableauNodePtrTable.setSeen(nodes); _done: while (true) { tloc = TableauNodePtrTable.startLoc(nodes); while (tloc != -1) { int curTidx = TableauNodePtrTable.getTidx(nodes, tloc); long curPtr = TableauNodePtrTable.getPtr(TableauNodePtrTable.getElem(nodes, tloc)); curNode = this.dg.getNode(curState, curTidx, curPtr); int succCnt = curNode.succSize(); for (int j = 0; j < succCnt; j++) { long nextState = curNode.getStateFP(j); if (nextState == state) { // We have found a path from startState to state, // now backtrack the path the outer loop took to get // us here and add each state to postfix. while (curState != startState) { postfix.addElement(curState); nodes = nodeTbl.getNodesByLoc(ploc); curState = TableauNodePtrTable.getKey(nodes); ploc = TableauNodePtrTable.getParent(nodes); } postfix.addElement(startState); break _done; } int[] nodes1 = nodeTbl.getNodes(nextState); if (nodes1 != null && !TableauNodePtrTable.isSeen(nodes1)) { TableauNodePtrTable.setSeen(nodes1); queue.enqueueLong(nextState); queue.enqueueInt(curLoc); } } tloc = TableauNodePtrTable.nextLoc(nodes, tloc); } TableauNodePtrTable.setParent(nodes, ploc); curState = queue.dequeueLong(); ploc = queue.dequeueInt(); curLoc = nodeTbl.getNodesLoc(curState); nodes = nodeTbl.getNodesByLoc(curLoc); } } /* * At this point 2/3 of the error trace have been constructed. * cycleStack contains the states from the start state of the SCC up to * the state that violates all liveness properties. postfix contains the * suffix from the violating state back to the start state of the SCC. * The next step is to get the last third which is the prefix from an * initial node to the start node of the SCC. */ // Now, print the error trace. We first construct the prefix that // led to the bad cycle. The nodes on prefix and cycleStack then // form the complete counter example. int stateNum = 0; LongVec prefix = this.dg.getPath(state, tidx); int plen = prefix.size(); TLCStateInfo[] states = new TLCStateInfo[plen]; // Recover the initial state: //TODO This throws an ArrayIndexOutOfBounds if getPath returned a // LongVec with just a single element. This happens when the parameter // state is one of the init states already. long fp = prefix.elementAt(plen - 1); TLCStateInfo sinfo = liveCheck.getTool().getState(fp); if (sinfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_INIT); } states[stateNum++] = sinfo; // Recover the successor states: //TODO Check if path.size has elements for (int i = plen - 2; i >= 0; i long curFP = prefix.elementAt(i); // The prefix might contain duplicates if the path happens to walk // along two distinct states which differ in the tableau idx only // (same fingerprint). From the counterexample perspective, this is // irrelevant. if (curFP != fp) { sinfo = liveCheck.getTool().getState(curFP, sinfo.state); if (sinfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT); } states[stateNum++] = sinfo; fp = curFP; } } // Print the prefix: TLCState lastState = null; for (int i = 0; i < stateNum; i++) { StatePrinter.printState(states[i], lastState, i + 1); lastState = states[i].state; } /* * At this point everything from the initial state up to the start state * of the SCC has been printed. */ // Print the cycle: int cyclePos = stateNum; long cycleFP = fp; while (cycleStack.size() > 0) { postfix.addElement(cycleStack.popLong()); cycleStack.popInt(); // ignore tableau idx } // Assert.assert(fps.length > 0); for (int i = postfix.size() - 1; i >= 0; i long curFP = postfix.elementAt(i); if (curFP != fp) { sinfo = liveCheck.getTool().getState(curFP, sinfo.state); if (sinfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT); } StatePrinter.printState(sinfo, lastState, ++stateNum); lastState = sinfo.state; fp = curFP; } } /* All error trace states have been printed (prefix + cycleStack + * postfix). What is left is to print either the stuttering or the * back-to-cyclePos marker. */ if (fp == cycleFP) { StatePrinter.printStutteringState(++stateNum); } else { sinfo = liveCheck.getTool().getState(cycleFP, sinfo.state); if (sinfo == null) { throw new EvalException(EC.TLC_FAILED_TO_RECOVER_NEXT); } // The print stmts below claim there is a cycle, thus assert that // there is indeed one. Index-based lookup into states array is // reduced by one because cyclePos is human-readable. assert states[cyclePos - 1].state.equals(sinfo.state); if (TLCGlobals.tool) { MP.printState(EC.TLC_BACK_TO_STATE, new String[] { "" + cyclePos }, (TLCState) null, -1); } else { MP.printMessage(EC.TLC_BACK_TO_STATE, "" + cyclePos); } } } /* (non-Javadoc) * @see java.lang.Thread#run() */ public final void run() { try { while (true) { // Use poll() to get the next checker from the queue or null if // there is none. Do *not* block when there are no more checkers // available. Nobody is going to add new checkers to the queue. final ILiveChecker checker = queue.poll(); if (checker == null || hasErrFound()) { // Another thread has either found an error (violation of a // liveness property) OR there is no more work (checker) to // be done. break; } this.oos = checker.getSolution(); this.dg = checker.getDiskGraph(); this.dg.createCache(); PossibleErrorModel[] pems = this.oos.getPems(); for (int i = 0; i < pems.length; i++) { if (!hasErrFound()) { this.pem = pems[i]; this.checkSccs(); } } this.dg.destroyCache(); // Record the size of the disk graph at the time its checked. This // information is later used to decide if it it makes sense to // run the next check on the larger but still *partial* graph. this.dg.recordSize(); } } catch (Exception e) { MP.printError(EC.GENERAL, "checking liveness", e); // LL changed // call 7 April // 2012 // Assert.printStack(e); return; } } /* * The detailed formatter below can be activated in Eclipse's variable view * by choosing "New detailed formatter" from the MemIntQueue context menu. * Insert "LiveWorker.DetailedFormatter.toString(this);". */ public static class DetailedFormatter { public static String toString(final MemIntStack comStack) { final int size = (int) comStack.size(); final StringBuffer buf = new StringBuffer(size / 5); for (int i = 0; i < comStack.size(); i+=5) { long loc = comStack.peakLong(size - i - 5); int tidx = comStack.peakInt(size - i - 3); long state = comStack.peakLong(size - i - 2); buf.append("state: "); buf.append(state); buf.append(" tidx: "); buf.append(tidx); buf.append(" loc: "); buf.append(loc); buf.append("\n"); } return buf.toString(); } } /* * The detailed formatter below can be activated in Eclipse's variable view * by choosing "New detailed formatter" from the MemIntQueue context menu. * Insert "LiveWorker.DFSStackDetailedFormatter.toString(this);". * Unfortunately it collides with the comStack DetailedFormatter as both use * the same type MemIntStack. So you have to chose what you want to look at * while debugging. * Note that toString treats pops/pushes of nodes and * states atomically. If called during a node is only partially pushed onto * the stack, the detailed formatter will crash. */ public static class DFSStackDetailedFormatter { public static String toString(final MemIntStack dfsStack) { final int size = (int) dfsStack.size(); final StringBuffer buf = new StringBuffer(size / 7); // approximate the size needed (buf will grow or shrink if needed) int i = 0; for (; i < dfsStack.size();) { // Peak element to see if it's a marker or not final long topElement = dfsStack.peakLong(size - i - 2); if (topElement == SCC_MARKER) { // It is the marker element buf.append("node ["); buf.append(" fp: "); buf.append(dfsStack.peakLong(size - i - 5)); buf.append(" tidx: "); buf.append(dfsStack.peakInt(size - i - 3)); buf.append(" lowLink: "); buf.append(dfsStack.peakLong(size - i - 7) - DiskGraph.MAX_PTR); buf.append("]\n"); // Increase i by the number of elements peaked i += 7; } else if (DiskGraph.isFilePointer(topElement)) { final long location = topElement; buf.append("succ ["); buf.append(" fp: "); buf.append(dfsStack.peakLong(size - i - 5)); buf.append(" tidx: "); buf.append(dfsStack.peakInt(size - i - 3)); buf.append(" location: "); buf.append(location); buf.append("]\n"); // Increase i by the number of elements peaked i += 5; } else if (topElement >= DiskGraph.MAX_PTR) { final long pLowLink = topElement - DiskGraph.MAX_PTR; buf.append("pLowLink: "); buf.append(pLowLink); buf.append("\n"); i += 2; } } // Assert all elements are used up assert i == size; return buf.toString(); } } }
package br.edu.unisinos.main; import java.io.IOException; /** * @author LCRO * */ public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //System.getProperty("java -Xmx500m -cp /path/to/stanford-parser.jar edu.stanford.nlp.parser.lexparser.LexicalizedParser -tokenized -sentences newline -outputFormat oneline -uwModel edu.stanford.nlp.parser.lexparser.BaseUnknownWordModel cintil.ser.gz input.txt"); System.out.println("Commit and Push ::::::: !!!!!!! "); } }
package installer; import java.io.*; import java.util.*; import java.util.jar.*; import java.net.URL; import java.net.JarURLConnection; import javax.swing.*; /** * * * @author Aidan Butler */ public class XmlUpdater extends Thread { private String classesPath = null; private String jarfilename; private String installPath; private JLabel statusLabel; private Vector listeners; private Thread internalThread; private boolean threadSuspended; private JProgressBar progressBar; public XmlUpdater(String installPath, JLabel statusLabel,JProgressBar pBar) { this.installPath = installPath; this.statusLabel = statusLabel; listeners = new Vector(); threadSuspended = false; progressBar=pBar; progressBar.setStringPainted(true); }// XmlUpdater public boolean checkStop() { if (internalThread == Thread.currentThread()) return false; return true; }// checkStop public void checkSuspend() { if (threadSuspended) { synchronized(this) { while (threadSuspended) { try { wait(); } catch (InterruptedException eInt) { } } } } }// checkSuspend public void setSuspend() { threadSuspended = true; }// setSuspend public void setResume() { threadSuspended = false; notify(); }// setResume public void setStop() { internalThread = null; }// setStop public void run() { InputStream istream; //InputSource isource; //DocumentBuilderFactory builderFactory; //DocumentBuilder builder = null; URL url; String fileName = null; internalThread = Thread.currentThread(); //System.out.println("\n\n\n\nFileName: "+installPath); classesPath= installPath.concat(File.separator+"program"+File.separator+"classes"+File.separator); String opSys =System.getProperty("os.name"); //System.out.println("\n System "+opSys); String progpath=installPath; progpath= progpath.concat(File.separator+"program"+File.separator); //System.out.println("Office progpath" + progpath ); //System.out.println("\nModifying Installation "+installPath); String configPath=installPath; configPath= configPath.concat(File.separator+"user"+File.separator+"config"+File.separator+"soffice.cfg"+File.separator); //System.out.println( "Office configuration path: " + configPath ); String starBasicPath=installPath; starBasicPath= starBasicPath.concat(File.separator+"user"+File.separator+"basic"+File.separator+"ScriptBindingLibrary"+File.separator); //System.out.println( "Office StarBasic path: " + starBasicPath ); String scriptsPath=installPath; scriptsPath= scriptsPath.concat(File.separator+"user"+File.separator+"Scripts"+File.separator+"java"+File.separator); //System.out.println( " Office Scripts Path: " + scriptsPath ); // Get the NetBeans installation //String netbeansPath= progressBar.setString("Unzipping Required Files"); ZipData zd = new ZipData("SFrameworkInstall.jar"); // Adding new directories to Office // Adding <Office>/user/basic/ScriptBindingLibrary/ File scriptBindingLib = new File( starBasicPath ); if( !scriptBindingLib.isDirectory() ) { if( !scriptBindingLib.mkdir() ) { System.out.println( "ScriptBindingLibrary failed"); } else { System.out.println( "ScriptBindingLibrary directory created"); } } else System.out.println( "ScriptBindingLibrary exists" ); //Adding <Office>/user/config/soffice.cfg/ File configDir = new File( configPath ); if( !configDir.isDirectory() ) { if( !configDir.mkdir() ) { System.out.println( "soffice.cfg directory failed"); } else { System.out.println( "soffice.cfg directory created"); } } else System.out.println( "soffice.cfg exists" ); // Robert Kinsella test 1 //Adding <Office>/user/Scripts/java/ File scriptsDir = new File( scriptsPath ); File highlightDir = new File( scriptsPath+"Highlight" ); File memoryDir = new File( scriptsPath+"MemoryUsage" ); if( !highlightDir.mkdirs() ) { System.out.println( "Highlight script directory failed"); } if( !memoryDir.mkdirs() ) { System.out.println( "MemoryUsage script directory failed"); } else { System.out.println( "Scripts/java directory created"); } //Robert Kinsella test 1 end // Adding Scripting Framework and tools if (!zd.extractEntry("sframework/ooscriptframe.zip",progpath, statusLabel)) { onInstallComplete(); return; } // Check for OpenOffice Scxripting Security Resource if (!zd.extractEntry("sframework/scripting64301.res",progpath+"resource"+File.separator, statusLabel)) { // No OpenOffice Scxripting Security Resource - check for Star Office one if (!zd.extractEntry("sframework/scripting64401.res",progpath+"resource"+File.separator, statusLabel)) { onInstallComplete(); return; } } if (opSys.indexOf("Windows")!=-1){ if (!zd.extractEntry("windows/regsingleton.exe",progpath, statusLabel)) { onInstallComplete(); return; } } else if (opSys.indexOf("Linux")!=-1){ if (!zd.extractEntry("linux_x86/regsingleton",progpath, statusLabel)) { onInstallComplete(); return; } } else if (opSys.indexOf("SunOS")!=-1){ if (!zd.extractEntry("solaris_sparc/regsingleton",progpath, statusLabel)) { onInstallComplete(); return; } } // Robert Kinsella test 2 // adding (JAVA) script examples File highlightScript = new File( scriptsPath+File.separator+"Highlight"+File.separator+"HighlightUtil.java" ); if( !highlightScript.exists() ) { if (!zd.extractEntry("examples/Highlight/HighlightUtil.java",scriptsPath+File.separator+"Highlight"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/Highlight/HighlightText.java",scriptsPath+File.separator+"Highlight"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/Highlight/Highlight.jar",scriptsPath+File.separator+"Highlight"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/Highlight/parcel-descriptor.xml",scriptsPath+File.separator+"Highlight"+File.separator, statusLabel)) { onInstallComplete(); return; } } else { System.out.println( "Highlight script already deployed" ); } File memoryScript = new File( scriptsPath+File.separator+"MemoryUsage"+File.separator+"MemoryUsage.java" ); if( !memoryScript.exists() ) { if (!zd.extractEntry("examples/MemoryUsage/MemoryUsage.java",scriptsPath+File.separator+"MemoryUsage"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/MemoryUsage/MemoryUsage.class",scriptsPath+File.separator+"MemoryUsage"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/MemoryUsage/parcel-descriptor.xml",scriptsPath+File.separator+"MemoryUsage"+File.separator, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("examples/MemoryUsage/ExampleSpreadSheet.sxc",scriptsPath+File.separator+"MemoryUsage"+File.separator, statusLabel)) { onInstallComplete(); return; } } else { System.out.println( "MemoryUsage script already deployed" ); } // Robert Kinsella test 2 end // Adding binding dialog if (!zd.extractEntry("bindingdialog/ScriptBinding.xba",starBasicPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/MenuBinding.xdl",starBasicPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/KeyBinding.xdl",starBasicPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/HelpBinding.xdl",starBasicPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/dialog.xlb",starBasicPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/script.xlb",starBasicPath, statusLabel)) { onInstallComplete(); return; } // Adding Office configuration files if (!zd.extractEntry("bindingdialog/writermenubar.xml",configPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/writerkeybinding.xml",configPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/calcmenubar.xml",configPath, statusLabel)) { onInstallComplete(); return; } if (!zd.extractEntry("bindingdialog/calckeybinding.xml",configPath, statusLabel)) { onInstallComplete(); return; } //System.out.println("About to call register"); if(!Register.register(installPath+File.separator, statusLabel, progressBar) ) { onInstallComplete(); return; } statusLabel.setText("Installation Complete"); progressBar.setString("Installation Complete"); progressBar.setValue(10); onInstallComplete(); }// run public void addInstallListener(InstallListener listener) { listeners.addElement(listener); }// addInstallListener private void onInstallComplete() { Enumeration e = listeners.elements(); while (e.hasMoreElements()) { InstallListener listener = (InstallListener)e.nextElement(); listener.installationComplete(null); } }// onInstallComplete }// XmlUpdater class
package cgeo.geocaching; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class cgCompass extends View { private changeThread watchdog = null; private boolean wantStop = false; private boolean lock = false; private boolean drawing = false; private Context context = null; private Bitmap compassUnderlay = null; private Bitmap compassRose = null; private Bitmap compassArrow = null; private Bitmap compassOverlay = null; private double azimuth = 0.0; private double heading = 0.0; private double cacheHeading = 0.0; private double northHeading = 0.0; private PaintFlagsDrawFilter setfil = null; private PaintFlagsDrawFilter remfil = null; private int compassUnderlayWidth = 0; private int compassUnderlayHeight = 0; private int compassRoseWidth = 0; private int compassRoseHeight = 0; private int compassArrowWidth = 0; private int compassArrowHeight = 0; private int compassOverlayWidth = 0; private int compassOverlayHeight = 0; private Handler changeHandler = new Handler() { @Override public void handleMessage(Message message) { try { invalidate(); } catch (Exception e) { Log.e(cgSettings.tag, "cgCompass.changeHandler: " + e.toString()); } } }; public cgCompass(Context contextIn) { super(contextIn); context = contextIn; } public cgCompass(Context contextIn, AttributeSet attrs) { super(contextIn, attrs); context = contextIn; } @Override public void onAttachedToWindow() { compassUnderlay = BitmapFactory.decodeResource(context.getResources(), R.drawable.compass_underlay); compassRose = BitmapFactory.decodeResource(context.getResources(), R.drawable.compass_rose); compassArrow = BitmapFactory.decodeResource(context.getResources(), R.drawable.compass_arrow); compassOverlay = BitmapFactory.decodeResource(context.getResources(), R.drawable.compass_overlay); compassUnderlayWidth = compassUnderlay.getWidth(); compassUnderlayHeight = compassUnderlay.getWidth(); compassRoseWidth = compassRose.getWidth(); compassRoseHeight = compassRose.getWidth(); compassArrowWidth = compassArrow.getWidth(); compassArrowHeight = compassArrow.getWidth(); compassOverlayWidth = compassOverlay.getWidth(); compassOverlayHeight = compassOverlay.getWidth(); setfil = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG); remfil = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG, 0); wantStop = false; watchdog = new changeThread(); watchdog.start(); } @Override public void onDetachedFromWindow() { wantStop = true; if (compassUnderlay != null) { compassUnderlay.recycle(); } if (compassRose != null) { compassRose.recycle(); } if (compassArrow != null) { compassArrow.recycle(); } if (compassOverlay != null) { compassOverlay.recycle(); } } protected void updateNorth(double northHeadingIn, double cacheHeadingIn) { northHeading = northHeadingIn; cacheHeading = cacheHeadingIn; } private class changeThread extends Thread { @Override public void run() { while (wantStop == false) { try { sleep(50); } catch (Exception e) { // nothing } if (Math.abs(azimuth - northHeading) < 2 && Math.abs(heading - cacheHeading) < 2) { continue; } lock = true; double diff = 0.0; double diffAbs = 0.0; double tempAzimuth = 0.0; double tempHeading = 0.0; final double actualAzimuth = azimuth; final double actualHeading = heading; diff = northHeading - actualAzimuth; diffAbs = Math.abs(northHeading - actualAzimuth); if (diff < 0) { diff = diff + 360; } else if (diff >= 360) { diff = diff - 360; } if (diff > 0 && diff <= 180) { if (diffAbs > 5) { tempAzimuth = actualAzimuth + 2; } else if (diffAbs > 1) { tempAzimuth = actualAzimuth + 1; } else { tempAzimuth = actualAzimuth; } } else if (diff > 180 && diff < 360) { if (diffAbs > 5) { tempAzimuth = actualAzimuth - 2; } else if (diffAbs > 1) { tempAzimuth = actualAzimuth - 1; } else { tempAzimuth = actualAzimuth; } } else { tempAzimuth = actualAzimuth; } diff = cacheHeading - actualHeading; diffAbs = Math.abs(cacheHeading - actualHeading); if (diff < 0) { diff = diff + 360; } else if (diff >= 360) { diff = diff - 360; } if (diff > 0 && diff <= 180) { if (diffAbs > 5) { tempHeading = actualHeading + 2; } else if (diffAbs > 1) { tempHeading = actualHeading + 1; } else { tempHeading = actualHeading; } } else if (diff > 180 && diff < 360) { if (diffAbs > 5) { tempHeading = actualHeading - 2; } else if (diffAbs > 1) { tempHeading = actualHeading - 1; } else { tempHeading = actualHeading; } } else { tempHeading = actualHeading; } if (tempAzimuth >= 360) { tempAzimuth = tempAzimuth - 360; } else if (tempAzimuth < 0) { tempAzimuth = tempAzimuth + 360; } if (tempHeading >= 360) { tempHeading = tempHeading - 360; } else if (tempHeading < 0) { tempHeading = tempHeading + 360; } azimuth = tempAzimuth; heading = tempHeading; lock = false; changeHandler.sendMessage(new Message()); } } } @Override protected void onDraw(Canvas canvas) { if (lock) { return; } if (drawing) { return; } double azimuthTemp = azimuth; double azimuthRelative = azimuthTemp - heading; if (azimuthRelative < 0) { azimuthRelative = azimuthRelative + 360; } else if (azimuthRelative >= 360) { azimuthRelative = azimuthRelative - 360; } // compass margins int canvasCenterX = (compassRoseWidth / 2) + ((getWidth() - compassRoseWidth) / 2); int canvasCenterY = (compassRoseHeight / 2) + ((getHeight() - compassRoseHeight) / 2); int marginLeftTemp = 0; int marginTopTemp = 0; drawing = true; super.onDraw(canvas); canvas.save(); canvas.setDrawFilter(setfil); marginLeftTemp = (getWidth() - compassUnderlayWidth) / 2; marginTopTemp = (getHeight() - compassUnderlayHeight) / 2; canvas.drawBitmap(compassUnderlay, marginLeftTemp, marginTopTemp, null); marginLeftTemp = (getWidth() - compassRoseWidth) / 2; marginTopTemp = (getHeight() - compassRoseHeight) / 2; canvas.rotate((float) -azimuthTemp, canvasCenterX, canvasCenterY); canvas.drawBitmap(compassRose, marginLeftTemp, marginTopTemp, null); canvas.rotate((float) azimuthTemp, canvasCenterX, canvasCenterY); marginLeftTemp = (getWidth() - compassArrowWidth) / 2; marginTopTemp = (getHeight() - compassArrowHeight) / 2; canvas.rotate((float) -azimuthRelative, canvasCenterX, canvasCenterY); canvas.drawBitmap(compassArrow, marginLeftTemp, marginTopTemp, null); canvas.rotate((float) azimuthRelative, canvasCenterX, canvasCenterY); marginLeftTemp = (getWidth() - compassOverlayWidth) / 2; marginTopTemp = (getHeight() - compassOverlayHeight) / 2; canvas.drawBitmap(compassOverlay, marginLeftTemp, marginTopTemp, null); canvas.setDrawFilter(remfil); canvas.restore(); drawing = false; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = compassArrow.getWidth() + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = compassArrow.getHeight() + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } }
package mteam; /* Import standard Java classes. */ import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TimeZone; /* Import classes from metrics-lib. */ import org.torproject.descriptor.Descriptor; import org.torproject.descriptor.DescriptorFile; import org.torproject.descriptor.DescriptorReader; import org.torproject.descriptor.DescriptorSourceFactory; import org.torproject.descriptor.ServerDescriptor; /* Import classes from Google's Gson library. */ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class ConvertToJson { /* Read all descriptors in the provided (decompressed) tarball and * convert all server descriptors to the JSON format. */ public static void main(String[] args) throws IOException { DescriptorReader descriptorReader = DescriptorSourceFactory.createDescriptorReader(); descriptorReader.addTarball( new File("in/bridge-server-descriptors-2015-10.tar")); Iterator<DescriptorFile> descriptorFiles = descriptorReader.readDescriptors(); int written = 0; BufferedWriter bw = new BufferedWriter(new FileWriter( "bridge-server-descriptors-2015-10.json")); bw.write("{\"descriptors\": [\n"); while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); for (Descriptor descriptor : descriptorFile.getDescriptors()) { String jsonDescriptor = null; if (descriptor instanceof ServerDescriptor) { jsonDescriptor = convertServerDescriptor((ServerDescriptor) descriptor); } /* Could add more else-if statements here. */ if (jsonDescriptor != null) { bw.write((written++ > 0 ? ",\n" : "") + jsonDescriptor); } } } bw.write("\n]\n}\n"); bw.close(); } /* Inner class to serialize all entries of a descriptor's "router" * line. */ static class Router { String nickname; // required, can be mixed-case String address; // required, changed to lower-case int or_port; // required int socks_port; // required, most likely 0 except for *very* old descs int dir_port; // required } /* Inner class to serialize "bandwidth" lines. */ static class Bandwidth { Integer bandwidth_avg; // required Integer bandwidth_burst; // required Integer bandwidth_observed; // optional, missing in older descriptors! } /* Inner class to serialize address/port combinations in "or-address" * lines or others. In theory, we could also include those as * strings. */ static class AddressAndPort { String address; // always lower-case int port; AddressAndPort(String address, int port) { this.address = address; this.port = port; } } /* Inner class to serialize "read-history" and "write-history" lines. */ static class BandwidthHistory { String date; // required, format is YYYY-MM-DD HH:MM:SS long interval; // required, seconds Collection<Long> bytes; // required } /* Inner class to serialize bridge server descriptors. */ static class JsonBridgeServerDescriptor { String descriptor_type; // set to bridge-server-descriptor $VERSION Router router; // required Bandwidth bandwidth; // required List<AddressAndPort> or_addresses; // addresses sanitized! String platform; // optional, though usually set String published; // format YYYY-MM-DD HH:MM:SS String fingerprint; // always upper-case hex Boolean hibernating; // optional Long uptime; // optional, though usually set Boolean onion_key; // required; usually false b/c sanitization Boolean signing_key; // required; usually false b/c sanitization List<String> exit_policy; // required String ipv6_policy; // optional String contact; // optional List<String> family; // optional, apparently not used at all BandwidthHistory read_history; // optional BandwidthHistory write_history; // optional Boolean eventdns; Boolean caches_extra_info; String extra_info_digest; // optional!, upper-case hex List<Integer> hidden_service_dir_versions; List<Integer> link_protocol_versions; List<Integer> circuit_protocol_versions; Boolean allow_single_hop_exits; Boolean ntor_onion_key; String router_digest; // upper-case hex } /* Date/time formatter. */ static final String dateTimePattern = "yyyy-MM-dd HH:mm:ss"; static final Locale dateTimeLocale = Locale.US; static final TimeZone dateTimezone = TimeZone.getTimeZone("UTC"); static DateFormat dateTimeFormat; static { dateTimeFormat = new SimpleDateFormat(dateTimePattern, dateTimeLocale); dateTimeFormat.setLenient(false); dateTimeFormat.setTimeZone(dateTimezone); } /* Take a single server descriptor, assume it's a *bridge* server * descriptor, and return a JSON string representation for it. */ static String convertServerDescriptor(ServerDescriptor desc) { JsonBridgeServerDescriptor json = new JsonBridgeServerDescriptor(); /* Find the @type annotation and include its content. */ for (String annotation : desc.getAnnotations()) { if (annotation.startsWith("@type ")) { json.descriptor_type = annotation.substring("@type ".length()); } } /* Put together the router object with nickname, address, etc. */ Router router = new Router(); router.nickname = desc.getNickname(); router.address = desc.getAddress(); router.or_port = desc.getOrPort(); router.socks_port = desc.getSocksPort(); router.dir_port = desc.getDirPort(); json.router = router; /* If there are any or-addresses, include them in a list. */ if (desc.getOrAddresses() != null && !desc.getOrAddresses().isEmpty()) { json.or_addresses = new ArrayList<AddressAndPort>(); for (String orAddress : desc.getOrAddresses()) { if (!orAddress.contains(":")) { continue; } int lastColon = orAddress.lastIndexOf(":"); try { int port = Integer.parseInt(orAddress.substring( lastColon + 1)); json.or_addresses.add( new AddressAndPort(orAddress.substring(0, lastColon), port)); } catch (NumberFormatException e) { continue; } } } /* Include a bandwidth object with average, burst, and possibly * observed bandwidth. */ Bandwidth bandwidth = new Bandwidth(); bandwidth.bandwidth_avg = desc.getBandwidthRate(); bandwidth.bandwidth_burst = desc.getBandwidthBurst(); if (desc.getBandwidthObserved() >= 0) { bandwidth.bandwidth_observed = desc.getBandwidthObserved(); } json.bandwidth = bandwidth; /* Include a few more fields, some of them only if they're not * null. */ if (desc.getExtraInfoDigest() != null) { json.extra_info_digest = desc.getExtraInfoDigest().toUpperCase(); } if (desc.getPlatform() != null) { json.platform = desc.getPlatform(); } json.published = dateTimeFormat.format(desc.getPublishedMillis()); json.fingerprint = desc.getFingerprint().toUpperCase(); if (desc.isHibernating()) { json.hibernating = desc.isHibernating(); } if (desc.getUptime() != null) { json.uptime = desc.getUptime(); } json.onion_key = desc.getOnionKey() != null; json.signing_key = desc.getSigningKey() != null; if (desc.getExitPolicyLines() != null && !desc.getExitPolicyLines().isEmpty()) { json.exit_policy = desc.getExitPolicyLines(); } if (desc.getIpv6DefaultPolicy() != null && !desc.getIpv6DefaultPolicy().isEmpty()) { json.ipv6_policy = desc.getIpv6DefaultPolicy(); } /* Include bandwidth histories using their own helper method. */ if (desc.getWriteHistory() != null) { json.write_history = convertBandwidthHistory( desc.getWriteHistory()); } if (desc.getReadHistory() != null) { json.read_history = convertBandwidthHistory( desc.getReadHistory()); } /* Include more fields. */ json.contact = desc.getContact(); json.family = desc.getFamilyEntries(); json.eventdns = desc.getUsesEnhancedDnsLogic(); json.caches_extra_info = desc.getCachesExtraInfo(); json.hidden_service_dir_versions = desc.getHiddenServiceDirVersions(); json.link_protocol_versions = desc.getLinkProtocolVersions(); json.circuit_protocol_versions = desc.getCircuitProtocolVersions(); json.allow_single_hop_exits = desc.getAllowSingleHopExits(); json.ntor_onion_key = desc.getNtorOnionKey() != null; json.router_digest = desc.getServerDescriptorDigest().toUpperCase(); /* Convert everything to a JSON string and return that. */ Gson gson = new GsonBuilder().serializeNulls().create(); return gson.toJson(json); } /* Convert a read or write history to an inner class that can later be * serialized to JSON. */ static BandwidthHistory convertBandwidthHistory( org.torproject.descriptor.BandwidthHistory hist) { BandwidthHistory bandwidthHistory = new BandwidthHistory(); bandwidthHistory.date = dateTimeFormat.format( hist.getHistoryEndMillis()); bandwidthHistory.interval = hist.getIntervalLength(); bandwidthHistory.bytes = hist.getBandwidthValues().values(); return bandwidthHistory; } }
package org.xins.common; import org.xins.common.text.FastStringBuffer; import org.xins.common.text.TextUtils; /** * General utility functions. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.1.0 */ public final class Utils extends Object { // Class fields // Class functions // Class functions /** * Retrieves the actual (major) Java version. * * @return * the actual Java version. * * @since XINS 1.2.0 */ public static final double getJavaVersion() { return Double.parseDouble(System.getProperty("java.version").substring(0, 3)); } /** * Retrieves the name of the calling class. If it cannot be determined, * then a special string (e.g. <code>"&lt;unknown&gt;"</code>) is returned. * * @return * the class name of the caller of the caller of this method, never an * empty string and never <code>null</code>. */ public static final String getCallingClass() { if (getJavaVersion() >= 1.4) { Throwable exception = new Throwable(); StackTraceElement[] trace = exception.getStackTrace(); if (trace != null && trace.length >= 3) { StackTraceElement caller = trace[2]; if (caller != null) { String callingClass = caller.getClassName(); if (! TextUtils.isEmpty(callingClass)) { return callingClass; } } } } // Fallback return "<unknown>"; } /** * Retrieves the name of the calling method. If it cannot be determined, * then a special string (e.g. <code>"&lt;unknown&gt;"</code>) is returned. * * @return * the method name of the caller of the caller of this method, never an * empty string and never <code>null</code>. */ public static final String getCallingMethod() { if (getJavaVersion() >= 1.4) { Throwable exception = new Throwable(); StackTraceElement[] trace = exception.getStackTrace(); if (trace != null && trace.length >= 3) { StackTraceElement caller = trace[2]; if (caller != null) { String callingMethod = caller.getMethodName(); if (! TextUtils.isEmpty(callingMethod)) { return callingMethod; } } } } // Fallback return "<unknown>"; } /** * Logs a programming error with an optional cause exception, and returns a * <code>ProgrammingException</code> object for it. * * <p>The class and method that call this method will be considered to be * the detecting class and calling class for the programming error. * * @param detail * the detail message, can be <code>null</code>. * * @return * an appropriate {@link ProgrammingException} that can be thrown by the * calling method, never <code>null</code>. */ public static final ProgrammingException logProgrammingError(String detail) { return logProgrammingError(getCallingClass(), getCallingMethod(), getCallingClass(), getCallingMethod(), detail); } /** * Logs a programming error with an optional cause exception, and returns a * <code>ProgrammingException</code> object for it. * * @param cause * the cause exception, cannot be <code>null</code>. * * @return * an appropriate {@link ProgrammingException} that can be thrown by the * calling method, never <code>null</code>. */ public static final ProgrammingException logProgrammingError(Throwable cause) { String sourceClass; String sourceMethod; try { // Determine the source of the exception StackTraceElement[] trace = cause.getStackTrace(); StackTraceElement source = trace[trace.length - 1]; // Determine source class and method sourceClass = source.getClassName(); sourceMethod = source.getMethodName(); // If there's any exception, then fallback to default values } catch (Throwable t) { sourceClass = "<unknown>"; sourceMethod = "<unknown>"; } // Determine detecting class and method String detectingClass = getCallingClass(); String detectingMethod = getCallingMethod(); // Log the programming error return logProgrammingError(detectingClass, detectingMethod, sourceClass, sourceMethod, null, cause); } /** * Logs a programming error with an optional cause exception, and returns a * <code>ProgrammingException</code> object for it. * * @param detectingClass * the name of the class that detected the problem, or * <code>null</code> if unknown. * * @param detectingMethod * the name of the method within the <code>detectingClass</code> that * detected the problem, or <code>null</code> if unknown. * * @param subjectClass * the name of the class which exposes the programming error, or * <code>null</code> if unknown. * * @param subjectMethod * the name of the method (within the <code>subjectClass</code>) which * exposes the programming error, or <code>null</code> if unknown. * * @param detail * the detail message, can be <code>null</code>. * * @param cause * the cause exception, can be <code>null</code>. * * @return * an appropriate {@link ProgrammingException} that can be thrown by the * calling method, never <code>null</code>. */ public static final ProgrammingException logProgrammingError(String detectingClass, String detectingMethod, String subjectClass, String subjectMethod, String detail, Throwable cause) { // Log programming error (not due to exception) if (cause == null) { Log.log_1050(detectingClass, detectingMethod, subjectClass, subjectMethod, detail); // Log programming error (due to exception) } else { Log.log_1052(cause, detectingClass, detectingMethod, subjectClass, subjectMethod, detail); } // Construct and return ProgrammingException object return new ProgrammingException(detectingClass, detectingMethod, subjectClass, subjectMethod, detail, cause); } /** * Logs a programming error with no cause exception, and returns a * <code>ProgrammingException</code> object for it. * * @param detectingClass * the name of the class that detected the problem, or * <code>null</code> if unknown. * * @param detectingMethod * the name of the method within the <code>detectingClass</code> that * detected the problem, or <code>null</code> if unknown. * * @param subjectClass * the name of the class which exposes the programming error, or * <code>null</code> if unknown. * * @param subjectMethod * the name of the method (within the <code>subjectClass</code>) which * exposes the programming error, or <code>null</code> if unknown. * * @param detail * the detail message, can be <code>null</code>. * * @return * an appropriate {@link ProgrammingException} that can be thrown by the * calling method, never <code>null</code>. */ public static final ProgrammingException logProgrammingError(String detectingClass, String detectingMethod, String subjectClass, String subjectMethod, String detail) { return logProgrammingError(detectingClass, detectingMethod, subjectClass, subjectMethod, detail, null); } public static final String getNameOfClass(Class c) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("c", c); // TODO: if (c.isPrimitive()) { if (c.isArray()) { FastStringBuffer buffer = new FastStringBuffer(137); Class comp = c.getComponentType(); buffer.append(getNameOfClass(comp)); if (c.getName().charAt(0) == '[') { buffer.append("[]"); } return buffer.toString(); } else { return c.getName(); } } public static final String getClassName(Object object) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("object", object); return getNameOfClass(object.getClass()); } /** * Generic method for tracing a method call, either while entering or while * leaving the method. * * @param enter * <code>true</code> if this is about entering a method, otherwise * <code>false</code> if this is about leaving a method. * * @param detail * the optional object representing the detail message, or * <code>null</code> if none. */ private static final void traceMethod(boolean enter, Object detail) { String callingClass = "<unknown>"; String callingMethod = "<unknown>"; // Determine calling class and calling method, but only on Java 1.4+ if (getJavaVersion() >= 1.4) { // Create an exception so we can look at the stack trace Throwable exception = new Throwable(); // Get the stack trace StackTraceElement[] trace = exception.getStackTrace(); if (trace != null && trace.length >= 3) { StackTraceElement caller = trace[2]; if (caller != null) { // Determine class name String s = caller.getClassName(); if (! TextUtils.isEmpty(s)) { callingClass = s; } // Determine method name s = caller.getMethodName(); if (! TextUtils.isEmpty(s)) { callingMethod = s; } } } } // Determine detail message String detailString = (detail == null) ? null : detail.toString(); // Actually log if (enter) { Log.log_1003(callingClass, callingMethod, detailString); } else { Log.log_1005(callingClass, callingMethod, detailString); } } /** * Traces the entering of a method using a log message. The calling class * and method are assumed to be the ones to log. * * @since XINS 1.2.0 */ public static final void traceEnterMethod() { traceMethod(true, null); } /** * Traces the entering of a method using a log message, with an optional * detail message. The calling class and method are assumed to be the ones * to log. * * @param detail * the optional object representing the detail message, or * <code>null</code> if none. * * @since XINS 1.2.0 */ public static final void traceEnterMethod(Object detail) { traceMethod(true, detail); } /** * Traces the leaving of a method using a log message. The calling class * and method are assumed to be the ones to log. * * @since XINS 1.2.0 */ public static final void traceLeaveMethod() { traceMethod(false, null); } /** * Traces the leaving of a method using a log message, with an optional * detail message. The calling class and method are assumed to be the ones * to log. * * @param detail * the optional object representing the detail message, or * <code>null</code> if none. * * @since XINS 1.2.0 */ public static final void traceLeaveMethod(Object detail) { traceMethod(false, detail); } // Constructors /** * Constructs a new <code>Utils</code> object. */ private Utils() { // empty } // Fields // Methods }
package org.apache.log4j.lbel; import java.io.IOException; import java.util.Stack; import org.apache.log4j.Level; import org.apache.log4j.lbel.comparator.LevelComparator; import org.apache.log4j.lbel.comparator.LoggerComparator; import org.apache.log4j.lbel.comparator.MessageComparator; class Parser { // The core of LBEL can be summarized by the following grammar. // <bexp> ::= <bexp> 'OR' <bterm> // <bexp> ::= <bterm> // <bterm> ::= <bterm> 'AND' <bfactor> // <bterm> ::= <bfactor> // <bfactor> ::= NOT <bfactor> // <bfactor> ::= '(' <bexp> ')' // <bfactor> ::= true // <bfactor> ::= false // In reality <bfactor> takes more varied forms then just true|false but // from a conceptual point of view, the variations are quite easy to deal with. // By eliminating left-recursion, th above grammar can be transformed into the // following LL(1) form. '#' stands for lambda, that is an empty sequence. // <bexp> ::= <bterm> <bexpTail> // <bexpTail> ::= 'OR' <bterm> // <bexpTail> ::= // <bterm> ::= <bfactor> <btermTail> // <btermTail> ::= 'AND' <bfactor> <btermTail> // <btermTail> ::= // <bfactor> ::= NOT <bfactor> // <bfactor> ::= '(' <bexp> ')' // <bfactor> ::= true // <bfactor> ::= false // Which is implemented almost directly by the following top-down parser. TokenStream ts; Stack stack = new Stack(); Parser(TokenStream bexpTS) { ts = bexpTS; } Node parse() throws IOException, ScanError { ts.next(); return bexp(); } Node bexp() throws IOException, ScanError { Node result; Node bterm = bterm(); Node bexpTail = bexpTail(); if(bexpTail == null) { result = bterm; } else { result = bexpTail; result.setLeft(bterm); } return result; } Node bexpTail() throws IOException, ScanError { Token token = ts.getCurrent(); switch(token.getType()) { case Token.OR: ts.next(); Node or = new Node(Node.OR, "OR"); Node bterm = bterm(); Node bexpTail = bexpTail(); if(bexpTail == null) { or.setRight(bterm); } else { or.setRight(bexpTail); bexpTail.setLeft(bterm); } return or; default: return null; } } Node bterm() throws IOException, ScanError { Node result; Node bfactor = bfactor(); Node btermTail = btermTail(); if(btermTail == null) { result = bfactor; } else { result = btermTail; btermTail.setLeft(bfactor); } return result; } Node btermTail() throws IOException, ScanError { Token token = ts.getCurrent(); switch(token.getType()) { case Token.AND: ts.next(); Node and = new Node(Node.AND, "AND"); Node bfactor = bfactor(); Node btermTail = btermTail(); if(btermTail == null) { and.setRight(bfactor); } else { and.setRight(btermTail); btermTail.setLeft(bfactor); } return and; default: return null; } } Node bfactor() throws IOException, ScanError { Token token = ts.getCurrent(); switch(token.getType()) { case Token.NOT: ts.next(); Node result = new Node(Node.NOT, "NOT"); Node bsubfactor = bsubfactor(); result.setLeft(bsubfactor); return result; default: return bsubfactor(); } } Node bsubfactor() throws IOException, ScanError { Token token = ts.getCurrent(); Operator operator; String literal; switch(token.getType()) { case Token.TRUE: ts.next(); return new Node(Node.TRUE, "TRUE"); case Token.FALSE: ts.next(); return new Node(Node.FALSE, "FALSE"); case Token.LP: ts.next(); Node result = bexp(); Token token2 = ts.getCurrent(); if(token2.getType() == Token.RP) { ts.next(); } else { throw new IllegalStateException("Expected right parantheses but got" +token); } return result; case Token.LOGGER: ts.next(); operator = getOperator(); ts.next(); literal = getLiteral(); return new Node(Node.COMPARATOR, new LoggerComparator(operator, literal)); case Token.LEVEL: ts.next(); operator = getOperator(); ts.next(); int levelInt = getLevelInt(); return new Node(Node.COMPARATOR, new LevelComparator(operator, levelInt)); default: throw new IllegalStateException("Unexpected token " +token); } } Operator getOperator() throws ScanError { Token token = ts.getCurrent(); if(token.getType() == Token.OPERATOR) { String value = (String) token.getValue(); if("=".equals(value)) { return new Operator(Operator.EQUAL); } else if("!=".equals(value)) { return new Operator(Operator.NOT_EQUAL); } else if(">".equals(value)) { return new Operator(Operator.GREATER); } else if(">=".equals(value)) { return new Operator(Operator.GREATER_OR_EQUAL); } else if("<".equals(value)) { return new Operator(Operator.LESS); } else if(">=".equals(value)) { return new Operator(Operator.LESS_OR_EQUAL); } else if("~".equals(value)) { return new Operator(Operator.REGEX_MATCH); } else if("!~".equals(value)) { return new Operator(Operator.NOT_REGEX_MATCH); } else if("childof".equals(value)) { return new Operator(Operator.CHILDOF); } else { throw new ScanError("Unknown operator type ["+value+"]"); } } else { throw new ScanError("Expected operator token"); } } String getLiteral() throws ScanError { Token token = ts.getCurrent(); if(token.getType() == Token.LITERAL) { return (String) token.getValue(); } else { throw new ScanError("Expected LITERAL but got "+token); } } int getLevelInt() throws ScanError { String levelStr = getLiteral(); if("DEBUG".equalsIgnoreCase(levelStr)) { return Level.DEBUG_INT; } else if("INFO".equalsIgnoreCase(levelStr)) { return Level.INFO_INT; } else if("WARN".equalsIgnoreCase(levelStr)) { return Level.WARN_INT; } else if("ERROR".equalsIgnoreCase(levelStr)) { return Level.ERROR_INT; } else { throw new ScanError("Expected a level stirng got "+levelStr); } } }
package javarepl.console.commands; import com.googlecode.totallylazy.Option; import com.googlecode.totallylazy.Pair; import com.googlecode.totallylazy.Predicate; import com.googlecode.totallylazy.Sequence; import javarepl.Evaluator; import javarepl.console.ConsoleLogger; import jline.console.completer.Completer; import static com.googlecode.totallylazy.Option.none; import static com.googlecode.totallylazy.Option.some; import static com.googlecode.totallylazy.Sequences.sequence; import static java.lang.Integer.parseInt; public abstract class Command { public static final String COMMAND_SEPARATOR = " "; private final String description; private final Predicate<String> predicate; private final Completer completer; private final ConsoleLogger logger; private final Evaluator evaluator; protected Command(Evaluator evaluator, ConsoleLogger logger, String description, Predicate<String> predicate, Completer completer) { this.description = description; this.predicate = predicate; this.completer = completer; this.logger = logger; this.evaluator = evaluator; } abstract void execute(String expression, CommandResultCollector result); public final CommandResult execute(String expression) { CommandResultCollector resultCollector = new CommandResultCollector(logger, expression); execute(expression, resultCollector); return resultCollector.result(); } public final Evaluator evaluator() { return evaluator; } public final String description() { return description; } public final Predicate<String> predicate() { return predicate; } public final Completer completer() { return completer; } @Override public final String toString() { return description(); } public static final Pair<String, Option<String>> parseStringCommand(String input) { final Sequence<String> splitInput = sequence(input.split(COMMAND_SEPARATOR)); String command = splitInput.first(); String value = splitInput.tail().toString(COMMAND_SEPARATOR); return Pair.pair(command, value.isEmpty() ? Option.none(String.class) : some(value)); } public static final Pair<String, Option<Integer>> parseNumericCommand(String input) { final Sequence<String> splitInput = sequence(input.split(COMMAND_SEPARATOR)); try { return Pair.pair(splitInput.first(), some(parseInt(splitInput.tail().toString(COMMAND_SEPARATOR)))); } catch (Exception e) { return Pair.pair(splitInput.first(), none(Integer.class)); } } }
package net.ihypo.work; public class Work { private int id; private String title; private int userId; private String data; //rank1= 2= 3= 4= private int rank; private boolean finash; public Work(int id){ this.id = id; } public Work(int id,String title,int userId,String data,int rank){ this.id = id; this.title = title; this.userId = userId; this.data = data; this.rank = rank; this.finash = false; } public int getId() { return id; } public String getTitle() { return title; } public int getUserId() { return userId; } public String getData() { return data; } public int getRank() { return rank; } public void setRank(int rank){ this.rank = rank; } public boolean isFinash() { return finash; } public void finash(){ this.finash = true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Work other = (Work) obj; if (id != other.id) return false; return true; } }
package org.eddy.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; @Aspect @Component public class LoginCheckAspect { public static final String FORBIDDEN = "forbidden"; @Pointcut("execution(* org.eddy.web..*(..)) && (@annotation(org.eddy.annotation.LoginCheck))") public void loginCheckPointcut(){} @Around("loginCheckPointcut()") public Object check(ProceedingJoinPoint point) throws Throwable { if (!loginCheck()) { return checkFailAndReturn(point); } return point.proceed(); } private Object checkFailAndReturn(ProceedingJoinPoint point) throws Throwable { if (! MethodSignature.class.isAssignableFrom(point.getSignature().getClass())) { return point.proceed(); } MethodSignature methodSignature = (MethodSignature) point.getSignature(); Class r = methodSignature.getReturnType(); if (r == String.class) { return FORBIDDEN; } else { return point.proceed(); } } /** * * @return true: */ private boolean loginCheck() { return true; } }
package yiida.httpresponser.net; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory; public class HttpsServer extends HttpServer { /* comment in and modify values if you want to fix SSL environment. static { System.setProperty("javax.net.ssl.keyStore", "/path/your_keystore"); System.setProperty("javax.net.ssl.keyStoreType", "JKS"); System.setProperty("javax.net.ssl.keyStorePassword", "password"); } */ public HttpsServer() {} public HttpsServer(int connectionCount, int port) { super(connectionCount, port); } @Override protected ServerSocketFactory getServerSocketFactory() { return SSLServerSocketFactory.getDefault(); } }
package addressbook; public class InputValidation { /* Validation for user inputs * The static field indexes can be found in Field.java */ public static boolean isValidStringForFieldIndex(String input, int index) { // Checks for empty inputs and of course those are valid. // Removed .trim() on input so any input with trailing spaces is probably going to return false if (input.equals("")) return true; switch(index) { case Field.CITY: // City case Field.LASTNAME: // Last name case Field.FIRSTNAME: // First name return input.matches( "^[a-zA-Z-]+$" ); case Field.STATE: // State return input.matches( "^[a-zA-Z]{2}$" ); case Field.ZIP: // Zipcode return input.matches( "^[0-9]{5}(-[0-9]{4})?$" ); case Field.DELIVERY: // First Address case Field.SECOND: // Second Address return input.matches("^[a-zA-Z0-9. \\/-]+$"); // This is for email validation, but we aren't using that // return input.matches( "\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b" ); case Field.PHONE: // Phone number return input.matches( "^[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}$" ); default: // No validation for indexes above our default 8 // Always returns true return true; } } public static String getValidationWarningForIndex(int index) { switch (index) { case Field.CITY: // City return "The city usually are composed of letters only."; case Field.STATE: // State return "The state usually are composed of letters only."; case Field.ZIP: // Zipcode return "Zipcodes usually match a pattern such as case Field.DELIVERY: // First Address return "Your address has characters that are not usually in an address."; case Field.SECOND: // Second Address return "Your second address has characters that are not usually in an address."; case Field.LASTNAME: // Last name return "Last names are usually composed of letters and/or hyphens."; case Field.FIRSTNAME: // First name return "First names are usually composed of letters and/or hyphens."; case Field.PHONE: // Phone number return "Phone numbers usually match a pattern such as default: System.err.println("Default hit in switch statement while getting validation warning."); return "Have a wonderful day!"; } } }
package cop5555sp15.ast; import static cop5555sp15.TokenStream.Kind.AND; import static cop5555sp15.TokenStream.Kind.BAR; import static cop5555sp15.TokenStream.Kind.DIV; import static cop5555sp15.TokenStream.Kind.EQUAL; import static cop5555sp15.TokenStream.Kind.GE; import static cop5555sp15.TokenStream.Kind.GT; import static cop5555sp15.TokenStream.Kind.LE; import static cop5555sp15.TokenStream.Kind.LSHIFT; import static cop5555sp15.TokenStream.Kind.LT; import static cop5555sp15.TokenStream.Kind.MINUS; import static cop5555sp15.TokenStream.Kind.NOT; import static cop5555sp15.TokenStream.Kind.NOTEQUAL; import static cop5555sp15.TokenStream.Kind.PLUS; import static cop5555sp15.TokenStream.Kind.RSHIFT; import static cop5555sp15.TokenStream.Kind.TIMES; import org.objectweb.asm.*; import cop5555sp15.TokenStream.Kind; import cop5555sp15.ast.TypeCheckVisitor.TypeCheckException; import cop5555sp15.TypeConstants; public class CodeGenVisitor implements ASTVisitor, Opcodes, TypeConstants { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); // Because we used the COMPUTE_FRAMES flag, we do not need to // insert the mv.visitFrame calls that you will see in some of the // asmifier examples. ASM will insert those for us. // FYI, the purpose of those instructions is to provide information // about what is on the stack just before each branch target in order // to speed up class verification. FieldVisitor fv; String className; String classDescriptor; // This class holds all attributes that need to be passed downwards as the // AST is traversed. Initially, it only holds the current MethodVisitor. // Later, we may add more attributes. static class InheritedAttributes { public InheritedAttributes(MethodVisitor mv) { super(); this.mv = mv; } MethodVisitor mv; } @Override public Object visitVarDec(VarDec varDec, Object arg) throws Exception { String varName = varDec.identToken.getText(); String varType = (String) varDec.type.visit(this, arg); { fv = cw.visitField(0, varName, varType, null, null); fv.visitEnd(); } return null; } @Override public Object visitAssignmentStatement( AssignmentStatement assignmentStatement, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; String varName = (String) assignmentStatement.lvalue.visit(this, arg); mv.visitVarInsn(ALOAD, 0); assignmentStatement.expression.visit(this, arg); String varType = assignmentStatement.expression.getType(); mv.visitFieldInsn(PUTFIELD, className, varName, varType); return null; } @Override public Object visitIdentLValue(IdentLValue identLValue, Object arg) throws Exception { return identLValue.identToken.getText(); } @Override public Object visitIdentExpression(IdentExpression identExpression, Object arg) throws Exception { String varName = identExpression.identToken.getText(); String varType = identExpression.getType(); MethodVisitor mv = ((InheritedAttributes) arg).mv; mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, className, varName, varType); return null; } @Override public Object visitIntLitExpression(IntLitExpression intLitExpression, Object arg) throws Exception { // this should be the first statement of all visit methods that generate instructions MethodVisitor mv = ((InheritedAttributes) arg).mv; mv.visitLdcInsn(intLitExpression.value); return null; } @Override public Object visitBinaryExpression(BinaryExpression binaryExpression, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; String exprType = (String) binaryExpression.expression0.getType(); Kind op = binaryExpression.op.kind; if (op == PLUS && exprType == stringType) { mv.visitTypeInsn(NEW, "java/lang/StringBuilder"); mv.visitInsn(DUP); binaryExpression.expression0.visit(this,arg); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "(Ljava/lang/String;)V", false); binaryExpression.expression1.visit(this,arg); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); } else if ((op == PLUS || op == MINUS || op == TIMES || op == DIV) && exprType == intType) { binaryExpression.expression0.visit(this,arg); binaryExpression.expression1.visit(this,arg); switch(op) { case PLUS: mv.visitInsn(IADD); break; case MINUS: mv.visitInsn(ISUB); break; case TIMES: mv.visitInsn(IMUL); break; case DIV: mv.visitInsn(IDIV); break; default: throw new UnsupportedOperationException("code generation not yet implemented"); } } else if (op == EQUAL) { binaryExpression.expression0.visit(this,arg); binaryExpression.expression1.visit(this,arg); Label le1 = new Label(); if(exprType == booleanType || exprType == intType) { mv.visitJumpInsn(IF_ICMPNE, le1); } else if(exprType == stringType) { mv.visitJumpInsn(IF_ACMPNE, le1); } mv.visitInsn(ICONST_1); Label le2 = new Label(); mv.visitJumpInsn(GOTO, le2); mv.visitLabel(le1); mv.visitInsn(ICONST_0); mv.visitLabel(le2); } else if (op == NOTEQUAL) { binaryExpression.expression0.visit(this,arg); binaryExpression.expression1.visit(this,arg); Label l1 = new Label(); if(exprType == booleanType || exprType == intType) { mv.visitJumpInsn(IF_ICMPEQ, l1); } else if(exprType == stringType) { mv.visitJumpInsn(IF_ACMPEQ, l1); } mv.visitInsn(ICONST_1); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); } else if (op == LT || op == GT || op == LE || op == GE) { binaryExpression.expression0.visit(this,arg); binaryExpression.expression1.visit(this,arg); Label l1 = new Label(); switch(op) { case LT: mv.visitJumpInsn(IF_ICMPGE, l1); break; case GT: mv.visitJumpInsn(IF_ICMPLE, l1); break; case LE: mv.visitJumpInsn(IF_ICMPGT, l1); break; case GE: mv.visitJumpInsn(IF_ICMPLT, l1); break; default: throw new UnsupportedOperationException("code generation not yet implemented"); } mv.visitInsn(ICONST_1); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); } else if (op == AND) { binaryExpression.expression0.visit(this, arg); Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); binaryExpression.expression1.visit(this,arg); mv.visitJumpInsn(IFEQ, l1); mv.visitInsn(ICONST_1); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); } else if (op == BAR) { binaryExpression.expression0.visit(this, arg); Label l1 = new Label(); mv.visitJumpInsn(IFNE, l1); binaryExpression.expression1.visit(this,arg); mv.visitJumpInsn(IFNE, l1); mv.visitInsn(ICONST_0); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_1); mv.visitLabel(l2); } else { throw new UnsupportedOperationException("code generation not yet implemented"); } return null; } @Override public Object visitBlock(Block block, Object arg) throws Exception { for (BlockElem elem : block.elems) { elem.visit(this, arg); } return null; } @Override public Object visitBooleanLitExpression( BooleanLitExpression booleanLitExpression, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; if (booleanLitExpression.value == true) { mv.visitInsn(ICONST_1); } else { mv.visitInsn(ICONST_0); } return null; } @Override public Object visitClosure(Closure closure, Object arg) throws Exception { for (VarDec dec : closure.formalArgList) { dec.visit(this, arg); } for (Statement statement : closure.statementList) { statement.visit(this, arg); } throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitClosureDec(ClosureDec closureDeclaration, Object arg) throws Exception { closureDeclaration.closure.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitClosureEvalExpression( ClosureEvalExpression closureExpression, Object arg) throws Exception { for (Expression e : closureExpression.expressionList) { e.visit(this, arg); } throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitClosureExpression(ClosureExpression closureExpression, Object arg) throws Exception { closureExpression.closure.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitExpressionLValue(ExpressionLValue expressionLValue, Object arg) throws Exception { throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitExpressionStatement( ExpressionStatement expressionStatement, Object arg) throws Exception { expressionStatement.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitIfElseStatement(IfElseStatement ifElseStatement, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; Label l1 = new Label(); ifElseStatement.expression.visit(this, arg); mv.visitJumpInsn(IFEQ, l1); ifElseStatement.ifBlock.visit(this, arg); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); ifElseStatement.elseBlock.visit(this, arg); mv.visitLabel(l2); return null; } @Override public Object visitIfStatement(IfStatement ifStatement, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; Label l1 = new Label(); ifStatement.expression.visit(this, arg); mv.visitJumpInsn(IFEQ, l1); ifStatement.block.visit(this, arg); mv.visitLabel(l1); return null; } @Override public Object visitKeyExpression(KeyExpression keyExpression, Object arg) throws Exception { keyExpression.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitKeyValueExpression( KeyValueExpression keyValueExpression, Object arg) throws Exception { keyValueExpression.key.visit(this, arg); keyValueExpression.value.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitKeyValueType(KeyValueType keyValueType, Object arg) throws Exception { keyValueType.keyType.visit(this, arg); keyValueType.valueType.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitListExpression(ListExpression listExpression, Object arg) throws Exception { for (Expression e : listExpression.expressionList) { e.visit(this, arg); } throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitListOrMapElemExpression( ListOrMapElemExpression listOrMapElemExpression, Object arg) throws Exception { listOrMapElemExpression.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitListType(ListType listType, Object arg) throws Exception { listType.type.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitMapListExpression(MapListExpression mapListExpression, Object arg) throws Exception { for (Expression e : mapListExpression.mapList) { e.visit(this, arg); } throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitPrintStatement(PrintStatement printStatement, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(printStatement.firstToken.getLineNumber(), l0); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); printStatement.expression.visit(this, arg); // adds code to leave value // of expression on top of // stack. // Unless there is a good // reason to do otherwise, // pass arg down the tree String etype = printStatement.expression.getType(); if (etype.equals("I") || etype.equals("Z") || etype.equals("Ljava/lang/String;")) { String desc = "(" + etype + ")V"; mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", desc, false); } else throw new UnsupportedOperationException( "printing list or map not yet implemented"); return null; } @Override public Object visitProgram(Program program, Object arg) throws Exception { className = program.JVMName; classDescriptor = 'L' + className + ';'; cw.visit(52, // version ACC_PUBLIC + ACC_SUPER, // access codes className, // fully qualified classname null, // signature "java/lang/Object", // superclass new String[] { "cop5555sp15/Codelet" } // implemented interfaces ); cw.visitSource(null, null); // maybe replace first argument with source // file name // create init method { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(3, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", classDescriptor, null, l0, l1, 0); mv.visitMaxs(1, 1); mv.visitEnd(); } // generate the execute method MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "execute", // name of top // level // method "()V", // descriptor: this method is parameterless with no // return value null, // signature. This is null for us, it has to do with generic types null // array of strings containing exceptions ); mv.visitCode(); Label lbeg = new Label(); mv.visitLabel(lbeg); mv.visitLineNumber(program.firstToken.lineNumber, lbeg); program.block.visit(this, new InheritedAttributes(mv)); mv.visitInsn(RETURN); Label lend = new Label(); mv.visitLabel(lend); mv.visitLocalVariable("this", classDescriptor, null, lbeg, lend, 0); mv.visitMaxs(0, 0); //this is required just before the end of a method. //It causes asm to calculate information about the //stack usage of this method. mv.visitEnd(); cw.visitEnd(); return cw.toByteArray(); } @Override public Object visitQualifiedName(QualifiedName qualifiedName, Object arg) { throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitRangeExpression(RangeExpression rangeExpression, Object arg) throws Exception { rangeExpression.lower.visit(this, arg); rangeExpression.upper.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitReturnStatement(ReturnStatement returnStatement, Object arg) throws Exception { returnStatement.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitSimpleType(SimpleType simpleType, Object arg) throws Exception { return simpleType.getJVMType(); } @Override public Object visitSizeExpression(SizeExpression sizeExpression, Object arg) throws Exception { sizeExpression.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitStringLitExpression( StringLitExpression stringLitExpression, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; mv.visitLdcInsn(stringLitExpression.value); return null; } @Override public Object visitUnaryExpression(UnaryExpression unaryExpression, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; unaryExpression.expression.visit(this, arg); if(unaryExpression.op.kind == NOT) { Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); mv.visitInsn(ICONST_0); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_1); mv.visitLabel(l2); } else if (unaryExpression.op.kind == MINUS) { mv.visitInsn(INEG); } return null; } @Override public Object visitValueExpression(ValueExpression valueExpression, Object arg) throws Exception { valueExpression.expression.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitWhileRangeStatement( WhileRangeStatement whileRangeStatement, Object arg) throws Exception { whileRangeStatement.rangeExpression.visit(this, arg); whileRangeStatement.block.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitWhileStarStatement(WhileStarStatement whileStarStatement, Object arg) throws Exception { whileStarStatement.expression.visit(this, arg); whileStarStatement.block.visit(this, arg); throw new UnsupportedOperationException( "code generation not yet implemented"); } @Override public Object visitWhileStatement(WhileStatement whileStatement, Object arg) throws Exception { MethodVisitor mv = ((InheritedAttributes) arg).mv; Label l1 = new Label(); whileStatement.expression.visit(this, arg); mv.visitJumpInsn(IFEQ, l1); whileStatement.block.visit(this, arg); mv.visitLabel(l1); return null; } @Override public Object visitUndeclaredType(UndeclaredType undeclaredType, Object arg) throws Exception { throw new UnsupportedOperationException( "code generation not yet implemented"); } }
package net.hearthstats; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ColorConvertOp; import java.awt.image.RescaleOp; import java.io.File; import java.io.IOException; import java.util.Observable; import javax.imageio.ImageIO; public class HearthstoneAnalyzer extends Observable { private boolean _coin; private BufferedImage _image; private String _mode; private String _opponentClass; private String _opponentName; private String _result; private String _screen; private String _yourClass; private int _deckSlot; private boolean _isNewArena = false; private float _ratio; private int _xOffset; private int _width; private int _height; private float _screenRatio; private boolean _arenaRunEndDetected = false; public HearthstoneAnalyzer() { } public void analyze(BufferedImage image) { _image = image; _calculateResolutionRatios(); if(getScreen() != "Main Menu" && getScreen() != "Playing") { _testForMainMenuScreen(); } if(getScreen() != "Play") { if(getMode() != "Practice") { _testForPracticeScreen(); } _testForPlayScreen(); } if(getScreen() != "Arena") { _testForArenaModeScreen(); } if((getScreen() == "Play" || getScreen() == "Arena") && getMode() != "Practice") { _testForFindingOpponent(); if (getScreen() == "Play") { if(getMode() != "Casual") _testForCasualMode(); if(getMode() != "Ranked") _testForRankedMode(); _testForDeckSlot(); } } if((getScreen() == "Match Start" || getScreen() == "Opponent Name") && getMode() != "Practice") { if(getYourClass() == null) _testForYourClass(); if(getOpponentClass() == null) _testForOpponentClass(); if(!getCoin()) _testForCoin(); if(getScreen() != "Opponent Name") _testForOpponentName(); } else { if(getScreen() != "Playing" && getMode() != "Practice") _testForMatchStartScreen(); } if((getScreen() == "Result" || getScreen() == "Arena") && !_arenaRunEndDetected ) { _testForArenaEnd(); } if(getMode() != "Practice") { if(getScreen() == "Playing") { _testForVictory(); _testForDefeat(); } else { if(getScreen() != "Result") _testForPlayingScreen(); } } if(getScreen() == "Arena" && !isNewArena()) { _testForNewArenaRun(); } _image.flush(); } private void _calculateResolutionRatios() { // handle 4:3 screen ratios _ratio = _image.getHeight() / (float) 768; _xOffset = 0; _width = _image.getWidth(); _height = _image.getHeight(); _screenRatio = (float) _width / _height; // handle widescreen x offsets if(_screenRatio > 1.4) { _xOffset = 107; _xOffset = (int) (((float) _width - (_ratio * 1024)) / 2); } } public void reset() { _coin = false; _yourClass = null; _opponentClass = null; _opponentName = null; _screen = null; _mode = null; _deckSlot = 0; _arenaRunEndDetected = false; } public boolean getCoin() { return _coin; } public int getDeckSlot() { return _deckSlot; } public String getMode() { return _mode; } public String getOpponentClass() { return _opponentClass; } public String getOpponentName() { return _opponentName; } public String getResult() { return _result; } public String getScreen() { return _screen; } public String getYourClass() { return _yourClass; } public boolean isNewArena() { return _isNewArena; } private void _notifyObserversOfChangeTo(String property) { setChanged(); notifyObservers(property); } public void setIsNewArena(boolean isNew) { _isNewArena = isNew; _notifyObserversOfChangeTo("newArena"); } private void _setDeckSlot(int deckSlot) { _deckSlot = deckSlot; _notifyObserversOfChangeTo("deckSlot"); } private void _setCoin(boolean coin) { _coin = coin; _notifyObserversOfChangeTo("coin"); } private void _setMode(String screen) { _mode = screen; _notifyObserversOfChangeTo("mode"); } private void _setOpponentClass(String opponentClass) { _opponentClass = opponentClass; _notifyObserversOfChangeTo("opponentClass"); } private void _setOpponentName(String opponentName) { _opponentName = opponentName; _notifyObserversOfChangeTo("opponentName"); } private void _setResult(String result) { _result = result; _notifyObserversOfChangeTo("result"); } private void _setScreen(String screen) { _screen = screen; _notifyObserversOfChangeTo("screen"); } private void _setYourClass(String yourClass) { _yourClass = yourClass; _notifyObserversOfChangeTo("yourClass"); } private void _testForArenaEnd() { int[][] tests = { { 315, 387, 239, 32, 39 }, { 399, 404, 237, 41, 33 }, { 448, 408, 223, 8, 16 } }; if((new PixelGroupTest(_image, tests)).passed()) { _screen = "Arena"; _arenaRunEndDetected = true; _notifyObserversOfChangeTo("arenaEnd"); } } private void _testForArenaModeScreen() { int[][] tests = { { 807, 707, 95, 84, 111 }, { 324, 665, 77, 114, 169 }, { 120, 685, 255, 215, 115 }, { 697, 504, 78, 62, 56 } }; if((new PixelGroupTest(_image, tests)).passed()) { _setScreen("Arena"); _setMode("Arena"); } } private void _testForCasualMode() { int[][] tests = { { 833, 94, 100, 22, 16 }, // ranked off { 698, 128, 200, 255, 255 } // casual blue }; PixelGroupTest testOne = new PixelGroupTest(_image, tests); int[][] testsTwo = { { 812, 178, 255, 255, 255}, { 758, 202, 215, 255, 255 } }; PixelGroupTest testTwo = new PixelGroupTest(_image, testsTwo); if(testOne.passed() || testTwo.passed()) _setMode("Casual"); } private void _testForCoin() { int[][] tests = { // fourth card right edge { 869, 389, 155, 250, 103 }, { 864, 328, 130, 255, 85 }, { 870, 340, 127, 255, 83 }, { 769, 280, 125, 255, 82 }, { 864, 379, 126, 255, 82 } }; if((new PixelGroupTest(_image, tests)).passedOr()) _setCoin(true); } private void _testForDeckSlot() { if(getDeckSlot() != 1) { int[][] slotOnePixels = { { 163, 178, 33, 129, 242}, { 183, 178, 33, 129, 242} }; if((new PixelGroupTest(_image, slotOnePixels)).passedOr()) _setDeckSlot(1); } if(getDeckSlot() != 2) { int[][] slotTwoPixels = { { 348, 178, 36, 144, 247 }, { 368, 178, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(2); } if(getDeckSlot() != 3) { int[][] slotTwoPixels = { { 506, 178, 36, 144, 247 }, { 526, 178, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(3); } if(getDeckSlot() != 4) { int[][] slotOnePixels = { { 163, 339, 33, 129, 242}, { 183, 339, 33, 129, 242} }; if((new PixelGroupTest(_image, slotOnePixels)).passedOr()) _setDeckSlot(4); } if(getDeckSlot() != 5) { int[][] slotTwoPixels = { { 348, 339, 36, 144, 247 }, { 368, 339, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(5); } if(getDeckSlot() != 6) { int[][] slotTwoPixels = { { 506, 339, 36, 144, 247 }, { 526, 339, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(6); } if(getDeckSlot() != 7) { int[][] slotOnePixels = { { 163, 497, 33, 129, 242}, { 183, 497, 33, 129, 242} }; if((new PixelGroupTest(_image, slotOnePixels)).passedOr()) _setDeckSlot(7); } if(getDeckSlot() != 8) { int[][] slotTwoPixels = { { 348, 497, 36, 144, 247 }, { 368, 497, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(8); } if(getDeckSlot() != 9) { int[][] slotTwoPixels = { { 506, 497, 36, 144, 247 }, { 526, 497, 36, 144, 247 } }; if((new PixelGroupTest(_image, slotTwoPixels)).passedOr()) _setDeckSlot(9); } } private void _testForDefeat() { int[][] tests = { { 745, 219, 164, 162, 155 }, { 344, 383, 134, 153, 239 }, { 696, 357, 201, 197, 188 } }; PixelGroupTest pxTest = new PixelGroupTest(_image, tests); int[][] testsTwo = { { 347, 382, 129, 148, 236 }, { 275, 345, 137, 138, 134 }, { 537, 155, 235, 226, 67 } }; PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo); int[][] testsThree = { { 347, 382, 129, 148, 236 }, { 275, 345, 137, 138, 134 }, { 537, 155, 235, 226, 67 } }; PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree); if (pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) { _setScreen("Result"); _setResult("Defeat"); } } private void _testForClass(String className, int[][] pixelTests, boolean isYours) { if((new PixelGroupTest(_image, pixelTests)).passed()) { if(isYours) _setYourClass(className); else _setOpponentClass(className); } } private void _testForFindingOpponent() { int[][] tests = { { 401, 143, 180, 122, 145 }, // title bar { 765, 583, 121, 72, 100 } // bottom bar }; PixelGroupTest pxTest = new PixelGroupTest(_image, tests); int[][] arenaTests = { { 393, 145, 205, 166, 135 }, // title bar { 819, 235, 109, 87, 79 }, { 839, 585, 139, 113, 77 } }; PixelGroupTest arenaPxTest = new PixelGroupTest(_image, arenaTests); if (pxTest.passed() || arenaPxTest.passed()) { _coin = false; _yourClass = null; _opponentClass = null; _opponentName = null; _arenaRunEndDetected = false; _setScreen("Finding Opponent"); } } private void _testForOpponentName() { int[][] tests = { { 383, 116, 187, 147, 79 }, // title banner left { 631, 107, 173, 130, 70 }, // title banner right { 505, 595, 129, 199, 255 } // confirm button }; PixelGroupTest pxTest = new PixelGroupTest(_image, tests); int[][] testsTwo = { { 379, 118, 189, 146, 82 }, // title banner left { 641, 119, 197, 154, 86 }, // title banner right { 515, 622, 121, 191, 255 } // confirm button }; PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo); if(pxTest.passed() || pxTestTwo.passed()) { _setScreen("Opponent Name"); _analyzeOpponnentName(); } } private void _analyzeOpponnentName() { int x = (int) ((getMode() == "Ranked" ? 76 : 6) * _ratio); int y = (int) (34 * _ratio); // with class name underneath // int y = (int) (40 * ratio); int imageWidth = (int) (150 * _ratio); int imageHeight = (int) (19 * _ratio); int bigWidth = imageWidth * 3; int bigHeight = imageHeight * 3; // get cropped image of name BufferedImage opponentNameImg = _image.getSubimage(x, y, imageWidth, imageHeight); // to gray scale BufferedImage grayscale = new BufferedImage(opponentNameImg.getWidth(), opponentNameImg.getHeight(), BufferedImage.TYPE_INT_RGB); BufferedImageOp grayscaleConv = new ColorConvertOp(opponentNameImg.getColorModel().getColorSpace(), grayscale.getColorModel().getColorSpace(), null); grayscaleConv.filter(opponentNameImg, grayscale); // blow it up for ocr BufferedImage newImage = new BufferedImage(bigWidth, bigHeight, BufferedImage.TYPE_INT_RGB); Graphics g = newImage.createGraphics(); g.drawImage(grayscale, 0, 0, bigWidth, bigHeight, null); g.dispose(); // invert image for (x = 0; x < newImage.getWidth(); x++) { for (y = 0; y < newImage.getHeight(); y++) { int rgba = newImage.getRGB(x, y); Color col = new Color(rgba, true); col = new Color(255 - col.getRed(), 255 - col.getGreen(), 255 - col.getBlue()); newImage.setRGB(x, y, col.getRGB()); } } // increase contrast RescaleOp rescaleOp = new RescaleOp(1.8f, -30, null); rescaleOp.filter(newImage, newImage); // Source and destination are the same. // save it to a file File outputfile = new File(Main.getExtractionFolder() + "/opponentname.jpg"); try { ImageIO.write(newImage, "jpg", outputfile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); _notifyObserversOfChangeTo("Exception: " + e.getMessage()); } _setOpponentName(OCR.process(Main.getExtractionFolder() + "/opponentname.jpg")); } private void _testForMainMenuScreen() { int[][] tests = { { 338, 453, 159, 96, 42 }, // box top { 211, 658, 228, 211, 116 }, // quest button exclamation mark { 513, 148, 36, 23, 24 } // dark vertical line in top center }; if((new PixelGroupTest(_image, tests)).passed()) _setScreen("Main Menu"); } private void _testForMatchStartScreen() { int[][] tests = { { 403, 487, 201, 173, 94 }, // title bar { 946, 149, 203, 174, 96 } // bottom bar }; if ((new PixelGroupTest(_image, tests)).passed()) { _setScreen("Match Start"); } } private void _testForNewArenaRun() { int[][] tests = { { 298, 170, 255, 239, 148 }, // key //{ 492, 204, 128, 79, 47 }, // key stem { 382, 294, 255, 255, 255 }, // zero { 393, 281, 255, 255, 255 }, // zero { 321, 399, 209, 179, 127 }, // no red x }; if ((new PixelGroupTest(_image, tests)).passed()) { setIsNewArena(true); } } private void _testForOpponentClass() { // Druid Test int[][] druidTests = { { 743, 118, 205, 255, 242 }, { 882, 141, 231, 255, 252 }, { 766, 215, 203, 160, 198 } }; _testForClass("Druid", druidTests, false); // Hunter Test int[][] hunterTests = { { 825, 66, 173, 178, 183 }, { 818, 175, 141, 37, 0 }, { 739, 309, 216, 214, 211 } }; _testForClass("Hunter", hunterTests, false); // Mage Test int[][] mageTests = { { 790, 68, 88, 23, 99 }, { 788, 312, 215, 188, 177 }, { 820, 247, 53, 64, 82 } }; _testForClass("Mage", mageTests, false); // Paladin Test int[][] paladinTests = { { 895, 213, 255, 247, 147 }, { 816, 301, 125, 237, 255 }, { 767, 82, 133, 107, 168 } }; _testForClass("Paladin", paladinTests, false); // Priest Test int[][] priestTests = { { 724, 189, 255, 236, 101 }, { 796, 243, 58, 72, 138 }, { 882, 148, 27, 20, 38 } }; _testForClass("Priest", priestTests, false); // Rogue Test int[][] rogueTests = { { 889, 254, 132, 196, 72 }, { 790, 273, 88, 21, 34 }, { 841, 73, 100, 109, 183 } }; _testForClass("Rogue", rogueTests, false); // Shaman Test int[][] shamanTests = { { 748, 94, 5, 50, 100 }, { 887, 169, 234, 50, 32 }, { 733, 206, 186, 255, 255 } }; _testForClass("Shaman", shamanTests, false); // Warlock Test int[][] warlockTests = { { 711, 203, 127, 142, 36 }, { 832, 264, 240, 244, 252 }, { 832, 65, 98, 129, 0 } }; _testForClass("Warlock", warlockTests, false); // Warrior Test int[][] warriorTests = { { 795, 64, 37, 4, 0 }, { 780, 83, 167, 23, 4 }, { 809, 92, 255, 247, 227 } }; _testForClass("Warrior", warriorTests, false); } private void _testForPlayingScreen() { // check for normal play boards int[][] tests = { { 336, 203, 231, 198, 124 }, { 763, 440, 234, 198, 124 } }; PixelGroupTest normalPxTest = new PixelGroupTest(_image, tests); // check for lighter orc board int[][] orcBoardTests = { { 906, 283, 222, 158, 94 }, { 120, 468, 195, 134, 78 } }; PixelGroupTest orcPxTest = new PixelGroupTest(_image, orcBoardTests); if (normalPxTest.passed() || orcPxTest.passed()) { _setScreen("Playing"); // _analyzeOpponnentName(); } } private void _testForPlayScreen() { int[][] tests = { { 543, 130, 121, 32, 22 }, // play mode red background { 254, 33, 197, 173, 132 }, // mode title light brown background { 956, 553, 24, 8, 8 }, { 489, 688, 68, 65, 63 } }; if((new PixelGroupTest(_image, tests)).passed()) _setScreen("Play"); } private void _testForPracticeScreen() { int[][] tests = { { 583, 120, 100, 99, 50 }, // practice mode green background { 255, 628, 87, 91, 45 }, // practice mode green background { 244, 28, 222, 199, 157 }, // section heading { 262, 695, 217, 193, 151 } // bottom label }; if((new PixelGroupTest(_image, tests)).passed()) { _setScreen("Practice"); _setMode("Practice"); } } private void _testForRankedMode() { int[][] tests = { { 833, 88, 220, 255, 255 }, // ranked blue { 698, 120, 56, 16, 8 } // casual off }; PixelGroupTest testOne = new PixelGroupTest(_image, tests); int[][] testsTwo = { { 840, 184, 199, 255, 255 }, { 948, 167, 192, 255, 255 } }; PixelGroupTest testTwo = new PixelGroupTest(_image, testsTwo); if(testOne.passed() || testTwo.passed()) _setMode("Ranked"); } private void _testForVictory() { int[][] tests = { { 334, 504, 88, 101, 192 }, { 683, 510, 74, 88, 173 }, { 549, 162, 255, 224, 119 } }; PixelGroupTest pxTest = new PixelGroupTest(_image, tests); int[][] testsTwo = { { 347, 469, 85, 102, 203 }, { 737, 339, 63, 76, 148 }, { 774, 214, 253, 243, 185 } }; PixelGroupTest pxTestTwo = new PixelGroupTest(_image, testsTwo); int[][] testsThree = { { 370, 528, 66, 81, 165 }, { 690, 553, 63, 76, 162 }, { 761, 228, 249, 234, 163 } }; PixelGroupTest pxTestThree = new PixelGroupTest(_image, testsThree); if(pxTest.passed() || pxTestTwo.passed() || pxTestThree.passed()) { _setScreen("Result"); _setResult("Victory"); } } private void _testForYourClass() { // Druid Test int[][] druidTests = { { 225, 480, 210, 255, 246 }, { 348, 510, 234, 255, 251 }, { 237, 607, 193, 155, 195 } }; _testForClass("Druid", druidTests, true); // Hunter Test int[][] hunterTests = { { 289, 438, 173, 161, 147 }, { 366, 554, 250, 200, 81 }, { 210, 675, 209, 209, 211 } }; _testForClass("Hunter", hunterTests, true); // Mage Test int[][] mageTests = { { 259, 439, 96, 31, 102 }, { 294, 677, 219, 210, 193 }, { 216, 591, 0, 0, 56 } }; _testForClass("Mage", mageTests, true); // Paladin Test int[][] paladinTests = { { 249, 447, 133, 105, 165 }, { 304, 671, 74, 146, 234 }, { 368, 581, 244, 238, 141 } }; _testForClass("Paladin", paladinTests, true); // Priest Test int[][] priestTests = { { 229, 491, 180, 178, 166 }, { 256, 602, 82, 104, 204 }, { 350, 611, 22, 23, 27 } }; _testForClass("Priest", priestTests, true); // Rogue Test int[][] rogueTests = { { 309, 446, 91, 107, 175 }, { 291, 468, 187, 37, 25 }, { 362, 623, 122, 186, 67 } }; _testForClass("Rogue", rogueTests, true); // Shaman Test int[][] shamanTests = { { 223, 458, 4, 46, 93 }, { 360, 533, 213, 32, 6 }, { 207, 578, 177, 245, 249 } }; _testForClass("Shaman", shamanTests, true); // Warlock Test int[][] warlockTests = { { 301, 435, 104, 138, 8 }, { 265, 493, 221, 51, 32 }, { 294, 680, 60, 75, 182 } }; _testForClass("Warlock", warlockTests, true); // Warrior Test int[][] warriorTests = { { 252, 452, 163, 10, 0 }, { 291, 579, 234, 192, 53 }, { 280, 461, 255, 245, 225 } }; _testForClass("Warrior", warriorTests, true); } }
package cogmac.draw3d.util; import static javax.media.opengl.GL.*; import java.awt.*; import java.awt.image.*; import java.nio.*; /** * @author decamp */ public class Images { public static final int RED = 0; public static final int GREEN = 1; public static final int BLUE = 2; public static final int ALPHA = 3; /** * Returns equivalent OpenGL internalFormat, format and data types for a BufferedImage. * (e.g., GL_BGRA and GL_UNSIGNED_BYTE). It will also specify if the ordering of * the DataBuffer component values must be reversed to achieve a GL-compatible format. * * @param image Some image * @param out4 Length-4 array to hold output. On return: <br/> * out3[0] will hold INPUT FORMAT for image. <br/> * out3[1] will hold FORMAT for image. <br/> * out3[2] will hold DATA TYPE for image. * out3[3] will equal 1 if component values must be swapped (reverse-ordered), otherwise 0. * @return true if equivalent format and data type were found */ public static boolean glFormatFor( BufferedImage image, int[] out4 ) { int bufType = image.getData().getDataBuffer().getDataType(); switch( image.getType() ) { case BufferedImage.TYPE_USHORT_GRAY: out4[0] = GL_RED; out4[1] = GL_RED; out4[2] = GL_UNSIGNED_SHORT; out4[3] = 0; return true; case BufferedImage.TYPE_BYTE_GRAY: out4[0] = GL_RED; out4[1] = GL_RED; out4[2] = GL_UNSIGNED_BYTE; out4[3] = 0; return true; case BufferedImage.TYPE_INT_BGR: out4[0] = GL_RGBA; out4[1] = GL_BGRA; out4[2] = GL_UNSIGNED_BYTE; out4[3] = 0; return true; case BufferedImage.TYPE_3BYTE_BGR: out4[0] = GL_RGB; out4[1] = GL_BGR; out4[2] = GL_UNSIGNED_BYTE; out4[3] = 0; return true; case BufferedImage.TYPE_INT_RGB: out4[0] = GL_RGBA; out4[1] = GL_RGBA; out4[2] = GL_UNSIGNED_BYTE; out4[3] = 0; return true; case BufferedImage.TYPE_USHORT_555_RGB: out4[0] = GL_RGB; out4[1] = GL_RGB; out4[2] = GL_UNSIGNED_SHORT_5_5_5_1; out4[3] = 0; return true; case BufferedImage.TYPE_USHORT_565_RGB: out4[0] = GL_RGB; out4[1] = GL_RGB; out4[2] = GL_UNSIGNED_SHORT_5_5_5_1; out4[3] = 0; return true; case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: return false; case BufferedImage.TYPE_INT_ARGB: case BufferedImage.TYPE_INT_ARGB_PRE: out4[0] = GL_RGBA; out4[1] = GL_BGRA; out4[2] = GL_UNSIGNED_BYTE; out4[3] = 1; return true; case BufferedImage.TYPE_BYTE_BINARY: case BufferedImage.TYPE_BYTE_INDEXED: case BufferedImage.TYPE_CUSTOM: default: return false; } } /** * Converts a BufferedImage to a 32-bit BGRA format and places it into * a directly allocated java.nio.ByteBuffer. * * @param image Input image to convert. * @param workSpace Optional array that may be used if <code>workSpace.length &gt;= image.getWidth()</code>. * @return Directly allocated ByteBuffer containing pixels in BGRA format and sRGB color space. */ public static ByteBuffer imageToBgraBuffer( BufferedImage image, int[] workSpace ) { int w = image.getWidth(); int h = image.getHeight(); int[] row = workSpace != null && workSpace.length >= w ? workSpace : new int[w]; ByteBuffer ret = ByteBuffer.allocateDirect( ( w * h ) * 4 ); ret.order( ByteOrder.LITTLE_ENDIAN ); IntBuffer ib = ret.asIntBuffer(); for( int i = 0; i < h; i++ ) { image.getRGB( 0, i, w, 1, row, 0, w ); ib.put( row, 0, w ); } return ret; } /** * Converts a BufferedImage to a directly allocated java.nio.ByteBuffer. * This method will first check to see if the image can be ported directly to a * GL compatible format. If so, it will dump the data directly without conversion * via <code>dataToByteBuffer</code>. If not, it will convert the image via * <code>imageToBgraBuffer</code>. * * @param image * @return */ public static ByteBuffer imageToByteBuffer( BufferedImage image, int[] outFormat ) { if( outFormat == null ) { outFormat = new int[4]; } if( !glFormatFor( image, outFormat ) ) { outFormat[0] = GL_RGBA; outFormat[1] = GL_BGRA; outFormat[2] = GL_UNSIGNED_BYTE; outFormat[3] = 0; return imageToBgraBuffer( image, null ); } ByteOrder order; if( outFormat[2] == GL_UNSIGNED_BYTE || outFormat[2] == GL_BYTE ) { order = outFormat[3] == 0 ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; } else { if( outFormat[3] == 0 ) { order = ByteOrder.nativeOrder(); } else { outFormat[0] = GL_RGBA; outFormat[1] = GL_BGRA; outFormat[2] = GL_UNSIGNED_BYTE; outFormat[3] = 0; return imageToBgraBuffer( image, null ); } } return dataToByteBuffer( image.getData().getDataBuffer(), order ); } /** * Converts a DataBuffer to a directly allocated java.nio.ByteBuffer. * @param image * @return */ public static ByteBuffer dataToByteBuffer( DataBuffer in, ByteOrder order ) { int type = in.getDataType(); int elSize = DataBuffer.getDataTypeSize( type ); int count = in.getSize(); ByteBuffer ret = ByteBuffer.allocateDirect( ( count * elSize + 7 ) / 8 ); ret.order( order ); switch( type ) { case DataBuffer.TYPE_BYTE: { for( int i = 0; i < in.getNumBanks(); i++ ) { ret.put( ( (DataBufferByte)in ).getData( i ) ); } ret.flip(); break; } case DataBuffer.TYPE_INT: { IntBuffer b = ret.asIntBuffer(); for( int i = 0; i < in.getNumBanks(); i++ ) { b.put( ( (DataBufferInt)in ).getData(i) ); } break; } case DataBuffer.TYPE_FLOAT: { FloatBuffer b = ret.asFloatBuffer(); for( int i = 0; i < in.getNumBanks(); i++ ) { b.put( ( (DataBufferFloat)in ).getData(i) ); } break; } case DataBuffer.TYPE_DOUBLE: { DoubleBuffer b = ret.asDoubleBuffer(); for( int i = 0; i < in.getNumBanks(); i++ ) { b.put( ( (DataBufferDouble)in ).getData( i ) ); } break; } case DataBuffer.TYPE_SHORT: { ShortBuffer b = ret.asShortBuffer(); for( int i = 0; i < in.getNumBanks(); i++ ) { b.put( ((DataBufferShort)in ).getData( i ) ); } break; } case DataBuffer.TYPE_USHORT: { ShortBuffer b = ret.asShortBuffer(); for( int i = 0; i < in.getNumBanks(); i++ ) { b.put( ( (DataBufferUShort)in ).getData( i ) ); } break; } default: throw new IllegalArgumentException( "Unknown data buffer type: " + type ); } return ret; } public static float[][] imageToRgbPlanes( BufferedImage image, int[] optWork, float[][] optOut ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } if( optOut == null ) { optOut = new float[3][w*h]; } final float[] cr = optOut[0]; final float[] cg = optOut[1]; final float[] cb = optOut[2]; final float scale = 1f / 255f; for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int i = x + y * w; int v = optWork[x]; cr[i] = ( v >> 16 & 0xFF ) * scale; cg[i] = ( v >> 8 & 0xFF ) * scale; cb[i] = ( v & 0xFF ) * scale; } } return optOut; } public static float[][] imageToRgbaPlanes( BufferedImage image, int[] optWork, float[][] optOut ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } if( optOut == null ) { optOut = new float[4][w*h]; } final float[] cr = optOut[0]; final float[] cg = optOut[1]; final float[] cb = optOut[2]; final float[] ca = optOut[3]; final float scale = 1f / 255f; for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int i = x + y * w; int v = optWork[x]; cr[i] = ( v >> 16 & 0xFF ) * scale; cg[i] = ( v >> 8 & 0xFF ) * scale; cb[i] = ( v & 0xFF ) * scale; ca[i] = ( v >> 24 & 0xFF ) * scale; } } return optOut; } public static float[] imageToPlane( BufferedImage image, int component, int[] optWork, float[] optOut ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } if( optOut == null ) { optOut = new float[w*h]; } final int shift; switch( component ) { case RED: shift = 16; break; case GREEN: shift = 8; break; case BLUE: shift = 0; break; default: shift = 24; break; } final float scale = 1f / 255f; for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { optOut[ x + y * w ] = ( optWork[x] >> shift & 0xFF ) * scale; } } return optOut; } public static BufferedImage rgbPlanesToImage( float[][] planes, int w, int h, int[] optWork, BufferedImage optOut ) { if( optOut == null ) { optOut = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB ); } if( optWork == null || optWork.length < w ) { optWork = new int[w]; } final float[] pr = planes[0]; final float[] pg = planes[1]; final float[] pb = planes[2]; for( int y = 0; y < h; y++ ) { for( int x = 0; x < w; x++ ) { int i = x + y * w; int cr = (int)( pr[i] * 255f + 0.5f ) & 0xFF; int cg = (int)( pg[i] * 255f + 0.5f ) & 0xFF; int cb = (int)( pb[i] * 255f + 0.5f ) & 0xFF; optWork[x] = 0xFF000000 | cr << 16 | cg << 8 | cb; } optOut.setRGB( 0, y, w, 1, optWork, 0, w ); } return optOut; } public static BufferedImage rgbaPlanesToImage( float[][] planes, int w, int h, int[] optWork, BufferedImage optOut ) { if( optOut == null ) { optOut = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB ); } if( optWork == null || optWork.length < w ) { optWork = new int[w]; } final float[] pr = planes[0]; final float[] pg = planes[1]; final float[] pb = planes[2]; final float[] pa = planes[3]; for( int y = 0; y < h; y++ ) { for( int x = 0; x < w; x++ ) { int i = x + y * w; int cr = (int)( pr[i] * 255f + 0.5f ) & 0xFF; int cg = (int)( pg[i] * 255f + 0.5f ) & 0xFF; int cb = (int)( pb[i] * 255f + 0.5f ) & 0xFF; int ca = (int)( pa[i] * 255f + 0.5f ) & 0xFF; optWork[x] = ca << 24 | cr << 16 | cg << 8 | cb; } optOut.setRGB( 0, y, w, 1, optWork, 0, w ); } return optOut; } public static void invert( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; int a = 0xFF - ( v >>> 24 ); int r = 0xFF - ( v >> 16 & 0xFF ); int g = 0xFF - ( v >> 8 & 0xFF ); int b = 0xFF - ( v & 0xFF ); optWork[x] = a | r << 16 | g << 8 | b; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void invertRgb( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; int a = v & 0xFF000000; int r = 0xFF - ( v >> 16 & 0xFF); int g = 0xFF - ( v >> 8 & 0xFF); int b = 0xFF - ( v & 0xFF); optWork[x] = a | r << 16 | g << 8 | b; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void invertAlpha( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; int a = 0xFF - ( v >>> 24 ); optWork[x] = v & 0x00FFFFFF | a << 24; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void meanRgbToAlpha( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; int r = v >> 16 & 0xFF; int g = v >> 8 & 0xFF; int b = v & 0xFF; optWork[x] = v & 0x00FFFFFF | ( r + g + b ) / 3 << 24; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void alphaToRgb( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { optWork[x] = ( optWork[x] >>> 24 ) * 0x01010101; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void multRgbByAlpha( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; int a = v >>> 24; int r = ( v >> 16 & 0xFF ) * a / 0xFF; int g = ( v >> 8 & 0xFF ) * a / 0xFF; int b = ( v & 0xFF ) * a / 0xFF; optWork[x] = a << 24 | r << 16 | g << 8 | b; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void fillRgb( BufferedImage image, int rgb, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } rgb &= 0x00FFFFFF; for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { optWork[x] = optWork[x] & 0xFF000000 | rgb; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void fillAlpha( BufferedImage image, int alpha, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } alpha = ( alpha & 0xFF ) << 24; for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { optWork[x] = optWork[x] & 0x00FFFFFF | alpha; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static void swapRedBlue( BufferedImage image, int[] optWork ) { final int w = image.getWidth(); final int h = image.getHeight(); if( optWork == null || optWork.length < w ) { optWork = new int[w]; } for( int y = 0; y < h; y++ ) { image.getRGB( 0, y, w, 1, optWork, 0, w ); for( int x = 0; x < w; x++ ) { int v = optWork[x]; optWork[x] = v & 0xFF00FF00 | v >> 16 & 0xFF | v << 16 & 0x00FF0000; } image.setRGB( 0, y, w, 1, optWork, 0, w ); } } public static BufferedImage toArgb( BufferedImage im ) { if( im.getType() == BufferedImage.TYPE_INT_ARGB ) { return im; } final int w = im.getWidth(); final int h = im.getHeight(); BufferedImage ret = new BufferedImage( w, h, BufferedImage.TYPE_INT_ARGB ); Graphics2D g = (Graphics2D)ret.getGraphics(); g.setComposite( AlphaComposite.Src ); g.drawImage( im, 0, 0, null ); return ret; } public static BufferedImage toGrayscale( BufferedImage im ) { if( im.getType() == BufferedImage.TYPE_BYTE_GRAY ) { return im; } final int w = im.getWidth(); final int h = im.getHeight(); BufferedImage ret = new BufferedImage( w, h, BufferedImage.TYPE_BYTE_GRAY ); Graphics2D g = (Graphics2D)ret.getGraphics(); g.setComposite( AlphaComposite.Src ); g.drawImage( im, 0, 0, null ); return ret; } public static BufferedImage resizeBilinear( BufferedImage im, int w, int h ) { BufferedImage ret = new BufferedImage(w, h, im.getType()); Graphics2D g = (Graphics2D)ret.getGraphics(); g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); g.drawImage( im, 0, 0, w, h, null ); return ret; } public static BufferedImage resizeBicubic( BufferedImage im, int w, int h ) { BufferedImage ret = new BufferedImage(w, h, im.getType()); Graphics2D g = (Graphics2D)ret.getGraphics(); g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR ); g.drawImage( im, 0, 0, w, h, null ); return ret; } }
package edu.umd.cs.findbugs.detect; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.GotoInstruction; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.LOOKUPSWITCH; import org.apache.bcel.generic.TABLESWITCH; import org.apache.bcel.util.ByteSequence; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.EdgeTypes; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class DuplicateBranches extends PreorderVisitor implements Detector, StatelessDetector { private ClassContext classContext; private BugReporter bugReporter; public DuplicateBranches(BugReporter bugReporter) { this.bugReporter = bugReporter; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public void visitClassContext(ClassContext classContext) { this.classContext = classContext; classContext.getJavaClass().accept(this); } public void visitMethod(Method method) { try { if (method.getCode() == null) return; CFG cfg = classContext.getCFG(method); Iterator<BasicBlock> bbi = cfg.blockIterator(); while (bbi.hasNext()) { BasicBlock bb = bbi.next(); int numOutgoing = cfg.getNumOutgoingEdges(bb); if (numOutgoing == 2) findIfElseDuplicates(cfg, method, bb); else if (numOutgoing > 2) findSwitchDuplicates(cfg, method, bb); } } catch (Exception e) { bugReporter.logError("Failure examining basic blocks in Duplicate Branches detector", e); } } private void findIfElseDuplicates(CFG cfg, Method method, BasicBlock bb) { BasicBlock thenBB = null, elseBB = null; Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); while (iei.hasNext()) { Edge e = iei.next(); if (e.getType() == EdgeTypes.IFCMP_EDGE) { elseBB = e.getTarget(); } else if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) { thenBB = e.getTarget(); } } if ((thenBB == null) || (elseBB == null) || (thenBB.getFirstInstruction() == null) || (elseBB.getFirstInstruction() == null)) return; int thenStartPos = thenBB.getFirstInstruction().getPosition(); int elseStartPos = elseBB.getFirstInstruction().getPosition(); InstructionHandle thenFinishIns = findThenFinish(cfg, thenBB, elseStartPos); int thenFinishPos = thenFinishIns.getPosition(); if (!(thenFinishIns.getInstruction() instanceof GotoInstruction)) return; int elseFinishPos = ((GotoInstruction) thenFinishIns.getInstruction()).getTarget().getPosition(); if (thenFinishPos >= elseStartPos) return; if ((thenFinishPos - thenStartPos) != (elseFinishPos - elseStartPos)) return; byte[] thenBytes = getCodeBytes(method, thenStartPos, thenFinishPos); byte[] elseBytes = getCodeBytes(method, elseStartPos, elseFinishPos); if (!Arrays.equals(thenBytes, elseBytes)) return; bugReporter.reportBug(new BugInstance(this, "DB_DUPLICATE_BRANCHES", NORMAL_PRIORITY) .addClass(classContext.getJavaClass()) .addMethod(classContext.getJavaClass(), method) .addSourceLineRange(this.classContext, this, thenBB.getFirstInstruction().getPosition(), thenBB.getLastInstruction().getPosition()) .addSourceLineRange(this.classContext, this, elseBB.getFirstInstruction().getPosition(), elseBB.getLastInstruction().getPosition())); } private void findSwitchDuplicates(CFG cfg, Method method, BasicBlock bb) { Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); int[] switchPos = new int[cfg.getNumOutgoingEdges(bb)+1]; int idx = 0; while (iei.hasNext()) { Edge e = iei.next(); if (EdgeTypes.SWITCH_EDGE == e.getType()) { BasicBlock target = e.getTarget(); InstructionHandle firstIns = target.getFirstInstruction(); if (firstIns == null) return; switchPos[idx++] = firstIns.getPosition(); } else if (EdgeTypes.SWITCH_DEFAULT_EDGE == e.getType()) { BasicBlock target = e.getTarget(); InstructionHandle firstIns = target.getFirstInstruction(); if (firstIns == null) return; switchPos[idx++] = firstIns.getPosition(); } else return; } Arrays.sort(switchPos); if (switchPos.length < 2) return; HashMap<BigInteger, Collection<Integer>> map = new HashMap<BigInteger,Collection<Integer>>(); for (int i = 0; i < switchPos.length-1; i++) { if (switchPos[i] +1 >= switchPos[i+1]) continue; byte[] clause = getCodeBytes(method, switchPos[i], switchPos[i+1]); BigInteger clauseAsInt = new BigInteger(clause); Collection<Integer> values = map.get(clauseAsInt); if (values == null) { values = new LinkedList<Integer>(); map.put(clauseAsInt,values); } values.add((Integer)i); } for(Collection<Integer> clauses : map.values()) { if (clauses.size() > 1) { BugInstance bug = new BugInstance(this, "DB_DUPLICATE_SWITCH_CLAUSES", LOW_PRIORITY) .addClass(classContext.getJavaClass()) .addMethod(classContext.getJavaClass(), method); for(int i : clauses) bug.addSourceLineRange(this.classContext, this, switchPos[i], switchPos[i+1]-1); bugReporter.reportBug(bug); } } } private byte[] getCodeBytes(Method m, int start, int end) { byte[] code = m.getCode().getCode(); byte[] bytes = new byte[end-start]; System.arraycopy( code, start, bytes, 0, end - start); try { ByteSequence sequence = new ByteSequence(code); while ((sequence.available() > 0) && (sequence.getIndex() < start)) { Instruction.readInstruction(sequence); } int pos; while (sequence.available() > 0 && ((pos = sequence.getIndex()) < end)) { Instruction ins = Instruction.readInstruction(sequence); if ((ins instanceof BranchInstruction) && !(ins instanceof TABLESWITCH) && !(ins instanceof LOOKUPSWITCH)) { BranchInstruction bi = (BranchInstruction)ins; int offset = bi.getIndex(); int target = offset + pos; if (target >= end) { byte hiByte = (byte)((target >> 8) & 0x000000FF); byte loByte = (byte)(target & 0x000000FF); bytes[pos+bi.getLength()-2 - start] = hiByte; bytes[pos+bi.getLength()-1 - start] = loByte; } } } } catch (IOException ioe) { } return bytes; } private InstructionHandle findThenFinish(CFG cfg, BasicBlock thenBB, int elsePos) { InstructionHandle inst = thenBB.getFirstInstruction(); while (inst == null) { Iterator<Edge> ie = cfg.outgoingEdgeIterator(thenBB); while (ie.hasNext()) { Edge e = ie.next(); if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) { thenBB = e.getTarget(); break; } } inst = thenBB.getFirstInstruction(); } InstructionHandle lastIns = inst; while (inst.getPosition() < elsePos) { lastIns = inst; inst = inst.getNext(); } return lastIns; } public void report() { } }
package edu.umd.cs.pugh.visitclass; import java.io.PrintStream; import org.apache.bcel.classfile.*; public abstract class BetterVisitor implements Visitor { public ConstantPool constant_pool; protected String className = "none"; protected String betterClassName = "none"; protected String packageName = "none"; protected String sourceFile = "none"; protected JavaClass thisClass; protected String methodSig = "none"; protected String betterMethodSig = "none"; protected String methodName = "none"; protected String betterMethodName = "none"; protected String betterFieldName = "none"; protected String fieldName = "none"; protected String fieldSig = "none"; protected String betterFieldSig = "none"; protected boolean fieldIsStatic; protected String superclassName = "none"; protected String betterSuperclassName = "none"; protected String getStringFromIndex(int i) { ConstantUtf8 name = (ConstantUtf8)constant_pool.getConstant(i); return name.getBytes().intern(); } protected int asUnsignedByte(byte b) { return 0xff & b; } // Accessors public String getBetterClassName() { return betterClassName; } public String getPackageName() { return packageName; } public String getSourceFile() { return sourceFile; } public String getBetterMethodName() { return betterMethodName; } public String getSuperclassName() { return superclassName; } public String getBetterSuperclassName() { return betterSuperclassName; } public String getFieldName() { return fieldName; } public String getFieldSig() { return fieldSig; } public boolean getFieldIsStatic() { return fieldIsStatic; } public String getMethodName() { return methodName; } public String getMethodSig() { return methodSig; } ////////////////// In short form ////////////////////// // General classes public void visit(JavaClass obj) {} public void visit(ConstantPool obj) {} public void visit(Field obj) {} public void visit(Method obj) { } // Constants public void visit(Constant obj) {} public void visit(ConstantCP obj) { visit((Constant)obj); } public void visit(ConstantMethodref obj) { visit((ConstantCP)obj); } public void visit(ConstantFieldref obj) { visit((ConstantCP)obj); } public void visit(ConstantInterfaceMethodref obj) { visit((ConstantCP)obj); } public void visit(ConstantClass obj) { visit((Constant)obj); } public void visit(ConstantDouble obj) { visit((Constant)obj); } public void visit(ConstantFloat obj) { visit((Constant)obj); } public void visit(ConstantInteger obj) { visit((Constant)obj); } public void visit(ConstantLong obj) { visit((Constant)obj); } public void visit(ConstantNameAndType obj) { visit((Constant)obj); } public void visit(ConstantString obj) { visit((Constant)obj); } public void visit(ConstantUtf8 obj) { visit((Constant)obj); } // Attributes public void visit(Attribute obj) {} public void visit(Code obj) { visit((Attribute) obj); } public void visit(ConstantValue obj) { visit((Attribute) obj); } public void visit(ExceptionTable obj) { visit((Attribute) obj); } public void visit(InnerClasses obj) { visit((Attribute) obj); } public void visit(LineNumberTable obj) { visit((Attribute) obj); } public void visit(LocalVariableTable obj) { visit((Attribute) obj); } public void visit(SourceFile obj) { visit((Attribute) obj); } public void visit(Synthetic obj) { visit((Attribute) obj); } public void visit(Deprecated obj) { visit((Attribute) obj); } public void visit(Unknown obj) { visit((Attribute) obj); } // Extra classes (i.e. leaves in this context) public void visit(InnerClass obj) {} public void visit(LocalVariable obj) {} public void visit(LineNumber obj) {} public void visit(CodeException obj) {} public void visit(StackMapEntry obj) {} // Attributes public void visitCode(Code obj) { visit(obj); } public void visitCodeException(CodeException obj) { visit(obj); } // Constants public void visitConstantClass(ConstantClass obj) { visit(obj); } public void visitConstantDouble(ConstantDouble obj) { visit(obj); } public void visitConstantFieldref(ConstantFieldref obj) { visit(obj); } public void visitConstantFloat(ConstantFloat obj) { visit(obj); } public void visitConstantInteger(ConstantInteger obj) { visit(obj); } public void visitConstantInterfaceMethodref(ConstantInterfaceMethodref obj) { visit(obj); } public void visitConstantLong(ConstantLong obj) { visit(obj); } public void visitConstantMethodref(ConstantMethodref obj) { visit(obj); } public void visitConstantNameAndType(ConstantNameAndType obj) { visit(obj); } public void visitConstantPool(ConstantPool obj) { visit(obj); } public void visitConstantString(ConstantString obj) { visit(obj); } public void visitConstantUtf8(ConstantUtf8 obj) { visit(obj); } public void visitConstantValue(ConstantValue obj) { visit(obj); } public void visitDeprecated(Deprecated obj) { visit(obj); } public void visitExceptionTable(ExceptionTable obj) { visit(obj); } public void visitField(Field obj) { fieldName = getStringFromIndex(obj.getNameIndex()); fieldSig = getStringFromIndex(obj.getSignatureIndex()); betterFieldSig = fieldSig.replace('/','.'); betterFieldName = betterClassName + "." + fieldName + " : " + betterFieldSig; fieldIsStatic = obj.isStatic(); visit(obj); } // Extra classes (i.e. leaves in this context) public void visitInnerClass(InnerClass obj) { visit(obj); } public void visitInnerClasses(InnerClasses obj) { visit(obj); } // General classes public void visitJavaClass(JavaClass obj) { constant_pool = obj.getConstantPool(); thisClass = obj; ConstantClass c = (ConstantClass)constant_pool.getConstant(obj.getClassNameIndex()); className = getStringFromIndex(c.getNameIndex()); betterClassName = className.replace('/','.'); packageName = obj.getPackageName(); sourceFile = obj.getSourceFileName(); superclassName = obj.getSuperclassName(); betterSuperclassName = superclassName.replace('/','.'); visit(obj); } public void visitLineNumber(LineNumber obj) { visit(obj); } public void visitLineNumberTable(LineNumberTable obj) { visit(obj); } public void visitLocalVariable(LocalVariable obj) { visit(obj); } public void visitLocalVariableTable(LocalVariableTable obj) { visit(obj); } public void visitMethod(Method obj) { methodName = getStringFromIndex(obj.getNameIndex()); methodSig = getStringFromIndex(obj.getSignatureIndex()); betterMethodSig = methodSig.replace('/','.'); betterMethodName = betterClassName + "." + methodName + " : " + betterMethodSig; visit(obj); } public void visitSourceFile(SourceFile obj) { visit(obj); } public void visitSynthetic(Synthetic obj) { visit(obj); } public void visitUnknown(Unknown obj) { visit(obj); } public void visitStackMapEntry(StackMapEntry obj) { visit(obj); } public void visitStackMap(StackMap obj) { visit(obj); } // public void report(PrintStream out) {} }
package edu.umd.cs.findbugs.tools; import java.io.File; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; /** * @author pugh */ public class ComparePerfomance { final int num; final Map<String, int[]> performance = new TreeMap<String, int[]>(); ComparePerfomance(String [] args) throws DocumentException { num = args.length; for(int i = 0; i < args.length; i++) { foo(new File(args[i]), i); } } public int[] getRecord(String className) { int [] result = performance.get(className); if (result != null) return result; result = new int[num]; performance.put(className, result); return result; } public void foo(File f, int i) throws DocumentException { Document doc; SAXReader reader = new SAXReader(); doc = reader.read(f); Node summary = doc.selectSingleNode("/BugCollection/FindBugsSummary"); double cpu_seconds = Double.parseDouble(summary.valueOf("@cpu_seconds")); putStats("cpu_seconds", i, (int) (cpu_seconds * 1000)); double gc_seconds = Double.parseDouble(summary.valueOf("@gc_seconds")); putStats("gc_seconds", i, (int) (gc_seconds * 1000)); List<Node> profileNodes = doc.selectNodes("/BugCollection/FindBugsSummary/FindBugsProfile/ClassProfile"); for(Node n : profileNodes) { String name = n.valueOf("@name"); int totalMilliseconds = Integer.parseInt(n.valueOf("@totalMilliseconds")); int invocations = Integer.parseInt(n.valueOf("@invocations")); putStats(name, i, totalMilliseconds); // System.out.printf("%6d %10d %s%n", invocations, totalMilliseconds, simpleName); } } /** * @param name * @param i * @param totalMilliseconds */ public void putStats(String name, int i, int totalMilliseconds) { int [] stats = getRecord(name); stats[i] = totalMilliseconds; } public void print() { for(Map.Entry<String, int[]> e : performance.entrySet()) { String name = e.getKey(); int lastDot = name.lastIndexOf('.'); String simpleName = name.substring(lastDot+1); System.out.printf("%s,%s", name, simpleName); for(int x : e.getValue()) System.out.printf(",%d", x); System.out.println(); } } public static void main(String args[]) throws Exception { ComparePerfomance p = new ComparePerfomance(args); p.print(); } }
package com.firefly.utils.pattern; import com.firefly.utils.StringUtils; public abstract class Pattern { private static final AllMatch ALL_MATCH = new AllMatch(); /** * Matches a string according to the specified pattern * @param str Target string * @return If it returns null, that represents matching failure, * else it returns an array contains all strings are matched. */ abstract public String[] match(String str); public static Pattern compile(String pattern, String wildcard) { final boolean startWith = pattern.startsWith(wildcard); final boolean endWith = pattern.endsWith(wildcard); final String[] array = StringUtils.split(pattern, wildcard); switch (array.length) { case 0: return ALL_MATCH; case 1: if (startWith && endWith) return new HeadAndTailMatch(array[0]); if (startWith) return new HeadMatch(array[0]); if (endWith) return new TailMatch(array[0]); return new EqualsMatch(pattern); default: return new MultipartMatch(startWith, endWith, array); } } private static class MultipartMatch extends Pattern { private final boolean startWith, endWith; private final String[] parts; private int num; public MultipartMatch(boolean startWith, boolean endWith, String[] parts) { super(); this.startWith = startWith; this.endWith = endWith; this.parts = parts; num = parts.length - 1; if(startWith) num++; if(endWith) num++; } @Override public String[] match(String str) { int currentIndex = -1; int lastIndex = -1; String[] ret = new String[num]; for (int i = 0; i < parts.length; i++) { String part = parts[i]; int j = startWith ? i : i - 1; currentIndex = str.indexOf(part, lastIndex + 1); if (currentIndex > lastIndex) { if(i != 0 || startWith) ret[j] = str.substring(lastIndex + 1, currentIndex); lastIndex = currentIndex + part.length() - 1; continue; } return null; } if(endWith) ret[num - 1] = str.substring(lastIndex + 1); return ret; } } private static class TailMatch extends Pattern { private final String part; public TailMatch(String part) { this.part = part; } @Override public String[] match(String str) { int currentIndex = str.indexOf(part); if(currentIndex == 0) { return new String[] { str.substring(part.length()) }; } return null; } } private static class HeadMatch extends Pattern { private final String part; public HeadMatch(String part) { this.part = part; } @Override public String[] match(String str) { int currentIndex = str.indexOf(part); if(currentIndex + part.length() == str.length()) { return new String[] { str.substring(0, currentIndex) }; } return null; } } private static class HeadAndTailMatch extends Pattern { private final String part; public HeadAndTailMatch(String part) { this.part = part; } @Override public String[] match(String str) { int currentIndex = str.indexOf(part); if(currentIndex >= 0) { String[] ret = new String[]{str.substring(0, currentIndex), str.substring(currentIndex + part.length(), str.length()) }; return ret; } return null; } } private static class EqualsMatch extends Pattern { private final String pattern; public EqualsMatch(String pattern) { this.pattern = pattern; } @Override public String[] match(String str) { return pattern.equals(str) ? new String[0] : null; } } private static class AllMatch extends Pattern { @Override public String[] match(String str) { return new String[]{str}; } } }
package net.mcft.copy.core.util; import java.util.HashMap; import java.util.Map; import net.minecraft.entity.Entity; import net.minecraftforge.common.IExtendedEntityProperties; public final class EntityUtils { private static Map<Class, String> propertiesLookup = new HashMap<Class, String>(); private EntityUtils() { } // These functions expect a static field IDENTIFIER in the class. public static String getIdentifier(Class<? extends IExtendedEntityProperties> propertiesClass) { String identifier = propertiesLookup.get(propertiesClass); if (identifier == null) { try { identifier = (String)propertiesClass.getField("IDENTIFIER").get(null); } catch (Exception e) { throw new Error(e); } propertiesLookup.put(propertiesClass, identifier); } return identifier; } public static <T extends IExtendedEntityProperties> T getProperties(Entity entity, Class<T> propertiesClass) { IExtendedEntityProperties properties = entity.getExtendedProperties(getIdentifier(propertiesClass)); return (propertiesClass.isInstance(properties) ? (T)properties : null); } public static <T extends IExtendedEntityProperties> T createProperties(Entity entity, Class<T> propertiesClass) { try { T properties = propertiesClass.getConstructor().newInstance(); entity.registerExtendedProperties(getIdentifier(propertiesClass), properties); return properties; } catch (Exception e) { throw new Error(e); } } public static <T extends IExtendedEntityProperties> T getOrCreateProperties(Entity entity, Class<T> propertiesClass) { T properties = getProperties(entity, propertiesClass); return ((properties != null) ? properties : createProperties(entity, propertiesClass)); } }
package com.eirb.projets9; import android.app.Activity; import android.app.Fragment; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; public class ScanBLE extends Fragment implements BluetoothAdapter.LeScanCallback{ public ScanBLE(){} private BluetoothAdapter mBluetoothAdapter; private Activity a; private Button button; private boolean isRunning = false; private TextView logs; private TextView status; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_scan, container, false); a = getActivity(); button = (Button) rootView.findViewById(R.id.button); logs = (TextView) rootView.findViewById(R.id.logs); status = (TextView) rootView.findViewById(R.id.status); BluetoothManager manager = (BluetoothManager) a.getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = manager.getAdapter(); if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 0); } button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isRunning){ mBluetoothAdapter.startLeScan(ScanBLE.this); logs.setText(logs.getText().toString()+"\n SCAN STARTED"); status.setText("SCAN RUNNING"); status.setTextColor(Color.GREEN); } else{ mBluetoothAdapter.stopLeScan(ScanBLE.this); logs.setText(logs.getText().toString()+"\n SCAN STOPPED"); status.setText("SCAN STOPPED"); status.setTextColor(Color.RED); } isRunning = !isRunning; } }); return rootView; } @Override public void onLeScan(final BluetoothDevice arg0, final int arg1, final byte[] arg2) { System.out.println(logs.getText()); // To be updated, the setText needs to be done in the main UI new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { logs.setText(logs.getText().toString()+"\n " + " name : " + arg0.getName() + " | addr : " + arg0.getAddress() + " | rssi : " + Integer.toString(arg1) + "\n" + " | major : " + bytesToHex(arg2).substring(80,84) + "\n" + " | minor : " + bytesToHex(arg2).substring(75,79) + "\n" + " | UUID : " + bytesToHex(arg2).substring(42,74) + "\n" + bytesToHex(arg2) + "\n"); } }); } final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
package modules; import java.util.Map; import java.util.TreeMap; import org.skyve.domain.Bean; import org.skyve.domain.PersistentBean; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Reference; import org.skyve.metadata.model.document.Relation; import org.skyve.wildcat.bind.BindUtil; import org.skyve.wildcat.util.BeanVisitor; import org.skyve.wildcat.util.JSONUtil; public class AuditJSONGenerator extends BeanVisitor { private Map<String, Object> audit = new TreeMap<>(); private Customer customer; public AuditJSONGenerator(Customer customer) { this.customer = customer; } public String toJSON() throws Exception { return JSONUtil.marshall(customer, audit, null); } @Override protected boolean accept(String binding, Document document, Document owningDocument, Reference owningReference, Bean bean, boolean visitingInheritedDocument) throws Exception { Map<String, Object> node = new TreeMap<>(); node.put(Bean.DOCUMENT_ID, bean.getBizId()); for (Attribute attribute : document.getAttributes()) { if (! (attribute instanceof Relation)) { String name = attribute.getName(); node.put(name, BindUtil.getSerialized(customer, bean, name)); } } if (bean instanceof PersistentBean) { node.put(Bean.BIZ_KEY, ((PersistentBean) bean).getBizKey()); } audit.put(binding, node); return true; } }
package com.gmail.robmadeyou; import java.util.Random; import com.gmail.robmadeyou.Block.BlockAir; import com.gmail.robmadeyou.Block.BlockStone; import com.gmail.robmadeyou.Effects.Color; import com.gmail.robmadeyou.Entity.Player; import com.gmail.robmadeyou.Gui.Text; import com.gmail.robmadeyou.World.World; public class Game { public static boolean isGameRunning = false; public static boolean isGameOver = false; public static boolean counterFinished = false; static Player player; static int counter = 0; static int counterMax = 20; static int currentX = 0; static int currentCounter; public static void init(){ generateWorld(); player = (Player) Engine.addEntity(new Player(64, Screen.getHeight() / 2, 32, 64)); currentCounter = 3; new Thread(startCounter).start(); } public static void generateWorld(){ Random random = new Random(); for(int i = 0; i < Screen.WorldWidth; i++){ for(int j = 0; j < Screen.WorldHeight; j++){ if(j != Screen.WorldHeight - 1 && j != Screen.WorldHeight - 2){ World.blockList[i][j] = new BlockAir(i, j); }else{ World.blockList[i][j] = new BlockStone(i,j); } } } for(int i = 0; i < Screen.WorldWidth; i++){ /* * Do random generation here, not really the prettiest but eh, should do for now */ int option = random.nextInt(10); if(option == 1){ System.out.println("yaay"); World.blockList[i][Screen.WorldHeight - 5] = new BlockStone(i, Screen.WorldHeight - 5); }else if(option == 2){ World.blockList[i][Screen.WorldHeight - 3] = new BlockStone(i, Screen.WorldHeight - 3); World.blockList[i][Screen.WorldHeight - 4] = new BlockStone(i, Screen.WorldHeight - 4); } } } public static void loop(){ if(!isGameOver){ Text.drawString(currentCounter +"", Screen.getWidth() / 2, Screen.getHeight() / 2, Layer.GUILayer(), 1, 1, Color.Black, true, false); if(currentCounter == 0){ counter++; if(counter >= counterMax){ counter = 0; for(int i = 0; i < Screen.WorldHeight; i++){ World.blockList[currentX][i] = new BlockStone(currentX, i); } currentX++; } if(player.getY() < 0){ isGameOver = true; gameOver(); } } }else{ if(currentCounter == 0){ counter++; counterMax if(counter >= counterMax){ counter = 0; for(int i = 0; i < Screen.WorldHeight; i++){ World.blockList[currentX][i] = new BlockStone(currentX, i); } currentX++; } } } } public static void gameOver(){ player = null; } public static void startGame(){ init(); } public static Runnable startCounter = new Runnable(){ public void run() { while(currentCounter > 0){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } currentCounter } } }; }
package org.openqa.selenium; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.mozilla.javascript.*; import org.w3c.dom.*; /** * Xlator * */ public class Xlator { private static final String PROPERTY_PREFIX = "selenium.options."; public static void main( String[] args ) throws Exception { if (args.length < 2) { System.err.println("usage: Xlator <formatter> <input.html> [output]\n" + "example: Xlator java-rc c:\\my\\TestFoo.html\n"); System.exit(1); } int i = 0; String outputFormat = args[i++]; File testCaseHTML = new File(args[i++]); File outputFile = null; if (args.length == 3) { outputFile = new File(args[i++]); } HashMap<String, String> options = extractOptions(); String testName = extractTestName(testCaseHTML); String output = xlateTestCase(testName, outputFormat, Xlator.loadFile(testCaseHTML), options); if (outputFile == null) { System.out.println(output); } else { FileWriter fw = new FileWriter(outputFile); fw.write(output); fw.flush(); fw.close(); } } public static HashMap<String, String> extractOptions() { HashMap<String, String> options = new HashMap<String, String>(); for (Iterator i = System.getProperties().keySet().iterator(); i.hasNext();) { String key = (String) i.next(); if (key.startsWith(PROPERTY_PREFIX)) { String optionName = key.substring(PROPERTY_PREFIX.length()); options.put(optionName, System.getProperty(key)); } } return options; } static String extractTestName(File testFile) { int dotIndex = testFile.getName().indexOf('.'); if (dotIndex == -1) return testFile.getName(); return testFile.getName().substring(0, dotIndex); } public static String xlateTestCase(String testName, String outputFormat, String htmlSource, HashMap<String, String> options) throws Exception { Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); loadJSSource(cx, scope, "/content/formats/html.js"); loadJSSource(cx, scope, "/content/testCase.js"); loadJSSource(cx, scope, "/content/tools.js"); // add window.editor.seleniumAPI InputStream stream = Xlator.class.getResourceAsStream("/core/iedoc.xml"); Document apiDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream); stream.close(); Object wrappedAPIDoc = Context.javaToJS(apiDoc, scope); Scriptable commandClass = (Scriptable) scope.get("Command", scope); ScriptableObject.putProperty(commandClass, "apiDocument", wrappedAPIDoc); Scriptable seleniumAPI = (Scriptable) cx.evaluateString(scope, "window = new Object(); window.editor = new Object(); window.editor.seleniumAPI = new Object();", "<JavaEval>", 1, null); loadJSSource(cx, seleniumAPI, "/core/scripts/selenium-api.js"); // add log.debug cx.evaluateString(scope, "Log.write = function(msg) { java.lang.System.out.println(msg) }; log = new Log('format');", "<JavaEval>", 1, null); Function parse = getFunction(scope, "parse"); Scriptable myTestCase = cx.newObject(scope, "TestCase"); parse.call(cx, scope, scope, new Object[] {myTestCase, htmlSource}); ScriptableObject.putProperty(myTestCase, "name", testName); Object wrappedResourceLoader = Context.javaToJS(new ResourceLoader(cx, scope), scope); ScriptableObject.putProperty(scope, "resourceLoader", wrappedResourceLoader); cx.evaluateString(scope, "function load(name) { " + "var source = resourceLoader.evalResource('/content/formats/' + name);" + "}", "<JavaEval>", 1, null); loadJSSource(cx, scope, "/content/formats/" + outputFormat + ".js"); if (options != null) { for (Iterator<String> i = options.keySet().iterator(); i.hasNext();) { String optionName = i.next(); Scriptable jsOptions = (Scriptable) scope.get("options", scope); ScriptableObject.putProperty(jsOptions, optionName, options.get(optionName)); } } Function format = getFunction(scope, "format"); Object result = format.call(cx, scope, scope, new Object[] {myTestCase, "foo"}); return (String) result; } finally { // Exit from the context. Context.exit(); } } static String loadFile(File file) throws IOException { Reader is = new FileReader(file); return readerToString(is); } static String readerToString(Reader is) throws IOException { StringBuffer sb = new StringBuffer( ); char[] b = new char[8192]; int n; // Read a block. If it gets any chars, append them. while ((n = is.read(b)) > 0) { sb.append(b, 0, n); } // Only construct the String object once, here. return sb.toString( ); } private static void loadJSSource(Context cx, Scriptable scope, String fileName) throws IOException { String source = Xlator.loadResource(fileName); cx.evaluateString(scope, source, fileName, 1, null); } private static Function getFunction(Scriptable scope, String functionName) { Object fObj = scope.get(functionName, scope); if (!(fObj instanceof Function)) { throw new RuntimeException(functionName + " is undefined or not a function."); } else { return (Function) fObj; } } static String loadResource(String resourceName) throws IOException { InputStream stream = Xlator.class.getResourceAsStream(resourceName); if (stream == null) throw new RuntimeException("Couldn't find resource " + resourceName); InputStreamReader reader = new InputStreamReader(stream); return readerToString(reader); } }
package opendap.wcs.v2_0; import opendap.wcs.v2_0.formats.*; import org.jdom.Element; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.Vector; import java.util.concurrent.ConcurrentHashMap; public class ServerCapabilities { private static ConcurrentHashMap<String, WcsResponseFormat> _responseFormats; static { _responseFormats = new ConcurrentHashMap<>(); WcsResponseFormat rf; rf = new NetCdfFormat(); _responseFormats.put(rf.name(),rf); rf = new GeotiffFormat(); _responseFormats.put(rf.name(),rf); rf = new Jpeg2000Format(); _responseFormats.put(rf.name(),rf); rf = new Dap2DataFormat(); _responseFormats.put(rf.name(),rf); } /** * Returns the names of the supported formats as the appear in the OperationsMetadata for GetCoverage. * @return * @param dapServer */ public static Vector<String> getSupportedFormatNames(URL dapServer){ Vector<String> supportedFormatNames = new Vector<>(); supportedFormatNames.addAll(Collections.list(_responseFormats.keys())); // Confines use of ConcurrentHashMap to Map Interface and is compatible with Java-7 jre // supportedFormatNames.addAll(_responseFormats.keySet()); // Utilizes Java-8 call that borks this when run on Java 7 JRE return supportedFormatNames; } /** * Makes a lenient attempt to locate the requested format. If it can't be * worked out a null is returned. * * * @param name * @return */ public static WcsResponseFormat getFormat(String name){ name = name.toLowerCase(); // If it's a slam dunk the woot. if(_responseFormats.containsKey(name)) return _responseFormats.get(name); // Otherwise we try to be lenient about it first for(WcsResponseFormat wrf: _responseFormats.values()){ // Case insensitive name match? if(wrf.name().equalsIgnoreCase(name)) return wrf; // Case insensitive mime-type match because people might request using mime-type if(wrf.mimeType().equalsIgnoreCase(name)) return wrf; // Hail Mary if(wrf.name().contains(name)) return wrf; // Hail Mary if(wrf.mimeType().contains(name)) return wrf; } // can't reach it... return null; } /** * Returns the wcs:ServiceMetadata section of the wcs:Capabilities response. * This section itemizes the return formats and we return the MIME types because * that makes sense, right? * * @return Returns the wcs:Contents section of the wcs:Capabilities response. * @throws WcsException When bad things happen. * @throws InterruptedException */ public static Element getServiceMetadata() throws InterruptedException, WcsException { Element serviceMetadata = new Element("ServiceMetadata",WCS.WCS_NS); for(WcsResponseFormat wrf: _responseFormats.values()){ Element formatSupported = new Element("formatSupported",WCS.WCS_NS); formatSupported.setText(wrf.mimeType()); serviceMetadata.addContent(formatSupported); } return serviceMetadata; } /** * * @param coverageID * @param fieldID * @return */ static String[] getInterpolationMethods(String coverageID, String fieldID){ String[] im = {"nearest"}; return im; } public static void main(String[] args) throws Exception{ Vector<String> sf = getSupportedFormatNames(null); for(String s : sf) System.out.println("Supported Format: "+s); String[] im = getInterpolationMethods(null,null); for(String s : im) System.out.println("InterpolationMethods: "+s); } }
package org.biojava.spice.Panel; import org.biojava.spice.SPICEFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JEditorPane; import javax.swing.BoxLayout; import javax.swing.JProgressBar; import javax.swing.BorderFactory; import javax.swing.Box; import java.awt.Dimension; import java.awt.BorderLayout; import java.awt.event.*; import java.net.URL; import java.util.Map; import java.util.HashMap; import javax.swing.JFrame; import java.awt.Component; import java.util.*; /** a class to display status information * contains * a status display to display arbitraty text * the PDB code of the currently displayed PDB file * the UniProt code of the currently displayed UniProt sequence * a progressBar to display ongoing progress */ public class StatusPanel extends JPanel { public static String PDBLINK = "http: public static String UNIPROTLINK = "http: Map pdbheader; JTextField pdbCode ; JTextField spCode ; JTextField status ; JTextField pdbDescription; JProgressBar progressBar ; SPICEFrame spice ; PDBDescMouseListener pdbdescMouseListener; public StatusPanel(SPICEFrame parent){ spice = parent; this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); this.setBorder(BorderFactory.createEmptyBorder()); Box hBox = Box.createHorizontalBox(); JTextField pdbtxt = new JTextField("PDB code:"); pdbtxt.setEditable(false); pdbtxt.setBorder(BorderFactory.createEmptyBorder()); hBox.add(pdbtxt); pdbCode = new JTextField(" "); pdbCode.setEditable(false); pdbCode.setBorder(BorderFactory.createEmptyBorder()); MouseListener mousiPdb = new PanelMouseListener(spice,this,PDBLINK); // mouse listener pdbCode.addMouseListener(mousiPdb); hBox.add(pdbCode); hBox.add(pdbCode,BorderLayout.WEST); JTextField sptxt = new JTextField("UniProt code:"); sptxt.setEditable(false); sptxt.setBorder(BorderFactory.createEmptyBorder()); hBox.add(sptxt); spCode = new JTextField(" "); spCode.setBorder(BorderFactory.createEmptyBorder()); spCode.setEditable(false); MouseListener mousiSp = new PanelMouseListener(spice,this,UNIPROTLINK); // mouse listener spCode.addMouseListener(mousiSp); hBox.add(spCode); // pdb description pdbDescription = new JTextField("pdbDesc"); pdbDescription.setBorder(BorderFactory.createEmptyBorder()); pdbDescription.setEditable(false); //pdbDescription.setMaximumSize(new Dimension(150,20)); pdbdescMouseListener = new PDBDescMouseListener(); //pdbdescMouseListener.setPDBHeader(new HashMap()); pdbdescMouseListener.setPDBHeader(pdbheader); pdbDescription.addMouseListener(pdbdescMouseListener); pdbDescription.addMouseMotionListener(pdbdescMouseListener); hBox.add(pdbDescription); progressBar = new JProgressBar(0,100); progressBar.setValue(0); progressBar.setStringPainted(false); progressBar.setString(""); progressBar.setMaximumSize(new Dimension(80,20)); progressBar.setIndeterminate(false); progressBar.setBorder(BorderFactory.createEmptyBorder()); hBox.add(progressBar,BorderLayout.EAST); this.add(hBox); } public void setPDBHeader(Map header){ pdbheader = header; pdbdescMouseListener.setPDBHeader(header); } public Map getPDBHeader(){ return pdbheader; } public void setStatus(String txt) { status.setText(txt); } public void setLoading(boolean flag){ progressBar.setIndeterminate(flag); } public void setPDB(String pdb) { if (pdb == null) pdb = "-"; pdbCode.setText(pdb); } public void setSP(String sp) { if (sp == null) sp = "-" ; spCode.setText(sp) ; } public void setPDBDescription(String desc){ pdbDescription.setText(desc); } } class PanelMouseListener implements MouseListener { SPICEFrame spice; StatusPanel parent; String caller; PanelMouseListener( SPICEFrame spice_, StatusPanel parent_,String caller_){ spice = spice_; parent=parent_; caller=caller_; } public void mouseClicked(MouseEvent e){ JTextField source = (JTextField) e.getSource(); try { URL url = new URL(caller+source.getText()); spice.showDocument(url); } catch ( Exception ex){ } } public void mouseExited(MouseEvent e){ // remove tooltip JTextField source = (JTextField)e.getSource(); source.setToolTipText(null); } public void mouseEntered(MouseEvent e){ // display tooltip JTextField source = (JTextField)e.getSource(); source.setToolTipText("click to open in browser"); } public void mouseReleased(MouseEvent e){} public void mousePressed(MouseEvent e){} } /** a class responsible of creating afloating frame * if the mouse is moved over the description of the PDB file */ class PDBDescMouseListener implements MouseListener, MouseMotionListener { Map pdbHeader ; boolean frameshown ; JFrame floatingFrame; public PDBDescMouseListener(){ super(); pdbHeader = new HashMap(); frameshown = false; } private void displayFrame() { if ( frameshown ) { return; } floatingFrame = new JFrame(); JFrame.setDefaultLookAndFeelDecorated(false); floatingFrame.setUndecorated(true); updateFrameContent(pdbHeader); floatingFrame.setVisible(true); frameshown = true; } private void disposeFrame(){ if ( ! frameshown ){ return; } floatingFrame.setVisible(false); floatingFrame.dispose(); frameshown = false; } private void updateFrameContent(Map h){ if ( h == null )h = new HashMap(); String t = "<html><body><table>"; Set s = h.keySet(); Iterator iter = s.iterator(); while (iter.hasNext()){ String key = (String) iter.next(); String value = (String)h.get(key); t+="<tr><td>"+key+"</td><td>"+value+"</td></tr>"; } t+="</table></body></html>"; JEditorPane txt = new JEditorPane("text/html",t); txt.setEditable(false); floatingFrame.getContentPane().add(txt); floatingFrame.pack(); } private void updateFramePosition(MouseEvent e){ if ( ! frameshown){ return; } int x = e.getX(); int y = e.getY(); // get parent components locations Component compo = e.getComponent(); int cx = compo.getX(); int cy = compo.getY(); //floatingFrame.setLocationRelativeTo(compo); // update the position of the frame, according to the mouse position //System.out.println((cx+x)+" " + (cy+ y)+" " + x + " " + y + " " + cx + " " + cy ); Dimension d = floatingFrame.getSize(); int dx = d.width; int dy = d.height; int posx = cx - dx ; int posy = cy - dy ; floatingFrame.setLocation(posx,posy); } public void setPDBHeader(Map h ){ pdbHeader = h; if ( frameshown){ updateFrameContent(h); } } // for mousemotion: public void mouseDragged(MouseEvent e){ } public void mouseMoved(MouseEvent e){ if ( frameshown) { updateFramePosition(e); } else { displayFrame(); } } // for mouselistener public void mouseEntered(MouseEvent e){ displayFrame(); //System.out.println("mouse entered"); } public void mousePressed(MouseEvent e){ } public void mouseClicked(MouseEvent e){ } public void mouseExited(MouseEvent e){ disposeFrame(); //System.out.println("mouse exited"); } public void mouseReleased(MouseEvent e){ } }
package org.bouncycastle.asn1.x509; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.Strings; /** * <pre> * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type OBJECT IDENTIFIER, * value ANY } * </pre> */ public class X509Name extends ASN1Encodable { /** * country code - StringType(SIZE(2)) */ public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6"); /** * organization - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10"); /** * organizational unit name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11"); /** * Title */ public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12"); /** * common name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5"); /** * street - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier STREET = new DERObjectIdentifier("2.5.4.9"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SERIALNUMBER = SN; /** * locality name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7"); /** * state, or province name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8"); /** * Naming attributes of type X520name */ public static final DERObjectIdentifier SURNAME = new DERObjectIdentifier("2.5.4.4"); public static final DERObjectIdentifier GIVENNAME = new DERObjectIdentifier("2.5.4.42"); public static final DERObjectIdentifier INITIALS = new DERObjectIdentifier("2.5.4.43"); public static final DERObjectIdentifier GENERATION = new DERObjectIdentifier("2.5.4.44"); public static final DERObjectIdentifier UNIQUE_IDENTIFIER = new DERObjectIdentifier("2.5.4.45"); /** * businessCategory - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier BUSINESS_CATEGORY = new DERObjectIdentifier( "2.5.4.15"); /** * postalCode - DirectoryString(SIZE(1..40) */ public static final DERObjectIdentifier POSTAL_CODE = new DERObjectIdentifier( "2.5.4.17"); /** * dnQualifier - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier DN_QUALIFIER = new DERObjectIdentifier( "2.5.4.46"); /** * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier PSEUDONYM = new DERObjectIdentifier( "2.5.4.65"); /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ public static final DERObjectIdentifier DATE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.1"); /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier PLACE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.2"); /** * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ public static final DERObjectIdentifier GENDER = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.3"); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_CITIZENSHIP = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.4"); /** * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_RESIDENCE = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.5"); /** * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier NAME_AT_BIRTH = new DERObjectIdentifier("1.3.36.8.3.14"); /** * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF * DirectoryString(SIZE(1..30)) */ public static final DERObjectIdentifier POSTAL_ADDRESS = new DERObjectIdentifier( "2.5.4.16"); /** * Email address (RSA PKCS#9 extension) - IA5String. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. */ public static final DERObjectIdentifier EmailAddress = PKCSObjectIdentifiers.pkcs_9_at_emailAddress; /** * more from PKCS#9 */ public static final DERObjectIdentifier UnstructuredName = PKCSObjectIdentifiers.pkcs_9_at_unstructuredName; public static final DERObjectIdentifier UnstructuredAddress = PKCSObjectIdentifiers.pkcs_9_at_unstructuredAddress; /** * email address in Verisign certificates */ public static final DERObjectIdentifier E = EmailAddress; /* * others... */ public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25"); /** * LDAP User id. */ public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1"); /** * look up table translating OID values into their common symbols - this static is scheduled for deletion */ public static Hashtable OIDLookUp = new Hashtable(); /** * determines whether or not strings should be processed and printed * from back to front. */ public static boolean DefaultReverse = false; /** * default look up table translating OID values into their common symbols following * the convention in RFC 2253 with a few extras */ public static Hashtable DefaultSymbols = OIDLookUp; /** * look up table translating OID values into their common symbols following the convention in RFC 2253 * */ public static Hashtable RFC2253Symbols = new Hashtable(); /** * look up table translating OID values into their common symbols following the convention in RFC 1779 * */ public static Hashtable RFC1779Symbols = new Hashtable(); /** * look up table translating string values into their OIDS - * this static is scheduled for deletion */ public static Hashtable SymbolLookUp = new Hashtable(); /** * look up table translating common symbols into their OIDS. */ public static Hashtable DefaultLookUp = SymbolLookUp; static { DefaultSymbols.put(C, "C"); DefaultSymbols.put(O, "O"); DefaultSymbols.put(T, "T"); DefaultSymbols.put(OU, "OU"); DefaultSymbols.put(CN, "CN"); DefaultSymbols.put(L, "L"); DefaultSymbols.put(ST, "ST"); DefaultSymbols.put(SN, "SN"); DefaultSymbols.put(EmailAddress, "E"); DefaultSymbols.put(DC, "DC"); DefaultSymbols.put(UID, "UID"); DefaultSymbols.put(STREET, "STREET"); DefaultSymbols.put(SURNAME, "SURNAME"); DefaultSymbols.put(GIVENNAME, "GIVENNAME"); DefaultSymbols.put(INITIALS, "INITIALS"); DefaultSymbols.put(GENERATION, "GENERATION"); DefaultSymbols.put(UnstructuredAddress, "unstructuredAddress"); DefaultSymbols.put(UnstructuredName, "unstructuredName"); DefaultSymbols.put(UNIQUE_IDENTIFIER, "UniqueIdentifier"); DefaultSymbols.put(DN_QUALIFIER, "DN"); DefaultSymbols.put(PSEUDONYM, "Pseudonym"); DefaultSymbols.put(POSTAL_ADDRESS, "PostalAddress"); DefaultSymbols.put(NAME_AT_BIRTH, "NameAtBirth"); DefaultSymbols.put(COUNTRY_OF_CITIZENSHIP, "CountryOfCitizenship"); DefaultSymbols.put(COUNTRY_OF_RESIDENCE, "CountryOfResidence"); DefaultSymbols.put(GENDER, "Gender"); DefaultSymbols.put(PLACE_OF_BIRTH, "PlaceOfBirth"); DefaultSymbols.put(DATE_OF_BIRTH, "DateOfBirth"); DefaultSymbols.put(POSTAL_CODE, "PostalCode"); DefaultSymbols.put(BUSINESS_CATEGORY, "BusinessCategory"); RFC2253Symbols.put(C, "C"); RFC2253Symbols.put(O, "O"); RFC2253Symbols.put(OU, "OU"); RFC2253Symbols.put(CN, "CN"); RFC2253Symbols.put(L, "L"); RFC2253Symbols.put(ST, "ST"); RFC2253Symbols.put(STREET, "STREET"); RFC2253Symbols.put(DC, "DC"); RFC2253Symbols.put(UID, "UID"); RFC1779Symbols.put(C, "C"); RFC1779Symbols.put(O, "O"); RFC1779Symbols.put(OU, "OU"); RFC1779Symbols.put(CN, "CN"); RFC1779Symbols.put(L, "L"); RFC1779Symbols.put(ST, "ST"); RFC1779Symbols.put(STREET, "STREET"); DefaultLookUp.put("c", C); DefaultLookUp.put("o", O); DefaultLookUp.put("t", T); DefaultLookUp.put("ou", OU); DefaultLookUp.put("cn", CN); DefaultLookUp.put("l", L); DefaultLookUp.put("st", ST); DefaultLookUp.put("sn", SN); DefaultLookUp.put("serialnumber", SN); DefaultLookUp.put("street", STREET); DefaultLookUp.put("emailaddress", E); DefaultLookUp.put("dc", DC); DefaultLookUp.put("e", E); DefaultLookUp.put("uid", UID); DefaultLookUp.put("surname", SURNAME); DefaultLookUp.put("givenname", GIVENNAME); DefaultLookUp.put("initials", INITIALS); DefaultLookUp.put("generation", GENERATION); DefaultLookUp.put("unstructuredaddress", UnstructuredAddress); DefaultLookUp.put("unstructuredname", UnstructuredName); DefaultLookUp.put("uniqueidentifier", UNIQUE_IDENTIFIER); DefaultLookUp.put("dn", DN_QUALIFIER); DefaultLookUp.put("pseudonym", PSEUDONYM); DefaultLookUp.put("postaladdress", POSTAL_ADDRESS); DefaultLookUp.put("nameofbirth", NAME_AT_BIRTH); DefaultLookUp.put("countryofcitizenship", COUNTRY_OF_CITIZENSHIP); DefaultLookUp.put("countryofresidence", COUNTRY_OF_RESIDENCE); DefaultLookUp.put("gender", GENDER); DefaultLookUp.put("placeofbirth", PLACE_OF_BIRTH); DefaultLookUp.put("dateofbirth", DATE_OF_BIRTH); DefaultLookUp.put("postalcode", POSTAL_CODE); DefaultLookUp.put("businesscategory", BUSINESS_CATEGORY); } private X509NameEntryConverter converter = null; private Vector ordering = new Vector(); private Vector values = new Vector(); private Vector added = new Vector(); private ASN1Sequence seq; /** * Return a X509Name based on the passed in tagged object. * * @param obj tag object holding name. * @param explicit true if explicitly tagged false otherwise. * @return the X509Name */ public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } public static X509Name getInstance( Object obj) { if (obj == null || obj instanceof X509Name) { return (X509Name)obj; } else if (obj instanceof ASN1Sequence) { return new X509Name((ASN1Sequence)obj); } throw new IllegalArgumentException("unknown object in factory \"" + obj.getClass().getName()+"\""); } /** * Constructor from ASN1Sequence * * the principal will be a list of constructed sets, each containing an (OID, String) pair. */ public X509Name( ASN1Sequence seq) { this.seq = seq; Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { ASN1Set set = (ASN1Set)e.nextElement(); for (int i = 0; i < set.size(); i++) { ASN1Sequence s = (ASN1Sequence)set.getObjectAt(i); ordering.addElement(s.getObjectAt(0)); DEREncodable value = s.getObjectAt(1); if (value instanceof DERString) { values.addElement(((DERString)value).getString()); } else { values.addElement("#" + bytesToString(Hex.encode(value.getDERObject().getDEREncoded()))); } added.addElement((i != 0) ? Boolean.TRUE : Boolean.FALSE); // to allow earlier JDK compatibility } } } /** * constructor from a table of attributes. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. * <p> * <b>Note:</b> if the name you are trying to generate should be * following a specific ordering, you should use the constructor * with the ordering specified below. */ public X509Name( Hashtable attributes) { this(null, attributes); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. */ public X509Name( Vector ordering, Hashtable attributes) { this(ordering, attributes, new X509DefaultEntryConverter()); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector ordering, Hashtable attributes, X509DefaultEntryConverter converter) { this.converter = converter; if (ordering != null) { for (int i = 0; i != ordering.size(); i++) { this.ordering.addElement(ordering.elementAt(i)); this.added.addElement(Boolean.FALSE); } } else { Enumeration e = attributes.keys(); while (e.hasMoreElements()) { this.ordering.addElement(e.nextElement()); this.added.addElement(Boolean.FALSE); } } for (int i = 0; i != this.ordering.size(); i++) { DERObjectIdentifier oid = (DERObjectIdentifier)this.ordering.elementAt(i); if (attributes.get(oid) == null) { throw new IllegalArgumentException("No attribute for object id - " + oid.getId() + " - passed to distinguished name"); } this.values.addElement(attributes.get(oid)); // copy the hash table } } /** * Takes two vectors one of the oids and the other of the values. */ public X509Name( Vector oids, Vector values) { this(oids, values, new X509DefaultEntryConverter()); } /** * Takes two vectors one of the oids and the other of the values. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector oids, Vector values, X509NameEntryConverter converter) { this.converter = converter; if (oids.size() != values.size()) { throw new IllegalArgumentException("oids vector must be same length as values."); } for (int i = 0; i < oids.size(); i++) { this.ordering.addElement(oids.elementAt(i)); this.values.addElement(values.elementAt(i)); this.added.addElement(Boolean.FALSE); } } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. */ public X509Name( String dirName) { this(DefaultReverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. */ public X509Name( String dirName, X509NameEntryConverter converter) { this(DefaultReverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. If reverse * is true, create the encoded version of the sequence starting from the * last element in the string. */ public X509Name( boolean reverse, String dirName) { this(reverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. If reverse is true the ASN.1 sequence representing the DN will * be built by starting at the end of the string, rather than the start. */ public X509Name( boolean reverse, String dirName, X509NameEntryConverter converter) { this(reverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. * <br> * If reverse is true, create the encoded version of the sequence * starting from the last element in the string. * @param reverse true if we should start scanning from the end (RFC 2553). * @param lookUp table of names and their oids. * @param dirName the X.500 string to be parsed. */ public X509Name( boolean reverse, Hashtable lookUp, String dirName) { this(reverse, lookUp, dirName, new X509DefaultEntryConverter()); } private DERObjectIdentifier decodeOID( String name, Hashtable lookUp) { if (Strings.toUpperCase(name).startsWith("OID.")) { return new DERObjectIdentifier(name.substring(4)); } else if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { return new DERObjectIdentifier(name); } DERObjectIdentifier oid = (DERObjectIdentifier)lookUp.get(Strings.toLowerCase(name)); if (oid == null) { throw new IllegalArgumentException("Unknown object id - " + name + " - passed to distinguished name"); } return oid; } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. The passed in converter is used to convert the * string values to the right of each equals sign to their ASN.1 counterparts. * <br> * @param reverse true if we should start scanning from the end, false otherwise. * @param lookUp table of names and oids. * @param dirName the string dirName * @param converter the converter to convert string values into their ASN.1 equivalents */ public X509Name( boolean reverse, Hashtable lookUp, String dirName, X509NameEntryConverter converter) { this.converter = converter; X509NameTokenizer nTok = new X509NameTokenizer(dirName); while (nTok.hasMoreTokens()) { String token = nTok.nextToken(); int index = token.indexOf('='); if (index == -1) { throw new IllegalArgumentException("badly formated directory string"); } String name = token.substring(0, index); String value = token.substring(index + 1); DERObjectIdentifier oid = decodeOID(name, lookUp); if (value.indexOf('+') > 0) { X509NameTokenizer vTok = new X509NameTokenizer(value, '+'); this.ordering.addElement(oid); this.values.addElement(vTok.nextToken()); this.added.addElement(Boolean.FALSE); while (vTok.hasMoreTokens()) { String sv = vTok.nextToken(); int ndx = sv.indexOf('='); String nm = sv.substring(0, ndx); String vl = sv.substring(ndx + 1); this.ordering.addElement(decodeOID(nm, lookUp)); this.values.addElement(vl); this.added.addElement(Boolean.TRUE); } } else { this.ordering.addElement(oid); this.values.addElement(value); this.added.addElement(Boolean.FALSE); } } if (reverse) { Vector o = new Vector(); Vector v = new Vector(); Vector a = new Vector(); for (int i = this.ordering.size() - 1; i >= 0; i { o.addElement(this.ordering.elementAt(i)); v.addElement(this.values.elementAt(i)); a.addElement(this.added.elementAt(i)); } this.ordering = o; this.values = v; this.added = a; } } /** * return a vector of the oids in the name, in the order they were found. */ public Vector getOIDs() { Vector v = new Vector(); for (int i = 0; i != ordering.size(); i++) { v.addElement(ordering.elementAt(i)); } return v; } /** * return a vector of the values found in the name, in the order they * were found. */ public Vector getValues() { Vector v = new Vector(); for (int i = 0; i != values.size(); i++) { v.addElement(values.elementAt(i)); } return v; } public DERObject toASN1Object() { if (seq == null) { ASN1EncodableVector vec = new ASN1EncodableVector(); ASN1EncodableVector sVec = new ASN1EncodableVector(); DERObjectIdentifier lstOid = null; for (int i = 0; i != ordering.size(); i++) { ASN1EncodableVector v = new ASN1EncodableVector(); DERObjectIdentifier oid = (DERObjectIdentifier)ordering.elementAt(i); v.add(oid); String str = (String)values.elementAt(i); v.add(converter.getConvertedValue(oid, str)); if (lstOid == null || ((Boolean)this.added.elementAt(i)).booleanValue()) { sVec.add(new DERSequence(v)); } else { vec.add(new DERSet(sVec)); sVec = new ASN1EncodableVector(); sVec.add(new DERSequence(v)); } lstOid = oid; } vec.add(new DERSet(sVec)); seq = new DERSequence(vec); } return seq; } /** * @param inOrder if true the order of both X509 names must be the same, * as well as the values associated with each element. */ public boolean equals(Object _obj, boolean inOrder) { if (_obj == this) { return true; } if (!inOrder) { return this.equals(_obj); } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } for(int i = 0; i < _orderingSize; i++) { String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(i)).getId(); String _oVal = (String)_oxn.values.elementAt(i); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { continue; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (!v1.toString().equals(v2.toString())) { return false; } } } else { return false; } } return true; } /** * test for equality - note: case is ignored. */ public boolean equals(Object _obj) { if (_obj == this) { return true; } if (!(_obj instanceof X509Name || _obj instanceof ASN1Sequence)) { return false; } DERObject derO = ((DEREncodable)_obj).getDERObject(); if (this.getDERObject().equals(derO)) { return true; } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } boolean[] _indexes = new boolean[_orderingSize]; for(int i = 0; i < _orderingSize; i++) { boolean _found = false; String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); for(int j = 0; j < _orderingSize; j++) { if (_indexes[j]) { continue; } String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(j)).getId(); String _oVal = (String)_oxn.values.elementAt(j); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { _indexes[j] = true; _found = true; break; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (v1.toString().equals(v2.toString())) { _indexes[j] = true; _found = true; break; } } } } if(!_found) { return false; } } return true; } public int hashCode() { ASN1Sequence seq = (ASN1Sequence)this.getDERObject(); Enumeration e = seq.getObjects(); int hashCode = 0; while (e.hasMoreElements()) { hashCode ^= e.nextElement().hashCode(); } return hashCode; } private void appendValue( StringBuffer buf, Hashtable oidSymbols, DERObjectIdentifier oid, String value) { String sym = (String)oidSymbols.get(oid); if (sym != null) { buf.append(sym); } else { buf.append(oid.getId()); } buf.append('='); int index = buf.length(); buf.append(value); int end = buf.length(); while (index != end) { if ((buf.charAt(index) == ',') || (buf.charAt(index) == '"') || (buf.charAt(index) == '\\') || (buf.charAt(index) == '+') || (buf.charAt(index) == '<') || (buf.charAt(index) == '>') || (buf.charAt(index) == ';')) { buf.insert(index, "\\"); index++; end++; } index++; } } /** * convert the structure to a string - if reverse is true the * oids and values are listed out starting with the last element * in the sequence (ala RFC 2253), otherwise the string will begin * with the first element of the structure. If no string definition * for the oid is found in oidSymbols the string value of the oid is * added. Two standard symbol tables are provided DefaultSymbols, and * RFC2253Symbols as part of this class. * * @param reverse if true start at the end of the sequence and work back. * @param oidSymbols look up table strings for oids. */ public String toString( boolean reverse, Hashtable oidSymbols) { StringBuffer buf = new StringBuffer(); boolean first = true; if (reverse) { for (int i = ordering.size() - 1; i >= 0; i { if (first) { first = false; } else { if (((Boolean)added.elementAt(i + 1)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } else { for (int i = 0; i < ordering.size(); i++) { if (first) { first = false; } else { if (((Boolean)added.elementAt(i)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } return buf.toString(); } private String bytesToString( byte[] data) { char[] cs = new char[data.length]; for (int i = 0; i != cs.length; i++) { cs[i] = (char)(data[i] & 0xff); } return new String(cs); } public String toString() { return toString(DefaultReverse, DefaultSymbols); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.batch; import org.apache.log4j.Logger; import org.broad.igv.feature.Locus; import org.broad.igv.feature.RegionOfInterest; import org.broad.igv.sam.AlignmentTrack; import org.broad.igv.track.RegionScoreType; import org.broad.igv.track.TrackManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.WaitCursorManager; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.util.SnapshotUtilities; import org.broad.igv.util.*; import java.awt.image.renderable.RenderableImageOp; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.util.ArrayList; import java.util.List; public class CommandExecutor { private static Logger log = Logger.getLogger(CommandExecutor.class); private File snapshotDirectory; private List<String> getArgs(String[] tokens) { List<String> args = new ArrayList(tokens.length); for (String s : tokens) { if (s.trim().length() > 0) { args.add(s.trim()); } } return args; } public String execute(String command) { List<String> args = getArgs(StringUtils.breakQuotedString(command, ' ').toArray(new String[]{})); String result = "OK"; final IGV mainFrame = IGV.getFirstInstance(); System.out.println(); log.debug("Executing: " + command); try { if (args.size() > 0) { String cmd = args.get(0).toLowerCase(); String param1 = args.size() > 1 ? args.get(1) : null; String param2 = args.size() > 2 ? args.get(2) : null; String param3 = args.size() > 3 ? args.get(3) : null; if (cmd.equals("echo")) { result = cmd; } else if (cmd.equals("goto")) { result = goto1(args); } else if (cmd.equals("snapshotdirectory")) { result = setSnapshotDirectory(param1); } else if (cmd.equals("snapshot")) { String filename = param1; createSnapshot(filename); } else if ((cmd.equals("loadfile") || cmd.equals("load")) && param1 != null) { result = load(param1); } else if (cmd.equals("hget") && args.size() > 3) { result = hget(param1, param2, param3); } else if (cmd.equals("genome") && args.size() > 1) { result = genome(param1); } else if (cmd.equals("new") || cmd.equals("reset") || cmd.equals("clear")) { mainFrame.createNewSession(null); } else if (cmd.equals("region")) { defineRegion(param1, param2, param3); } else if (cmd.equals("sort")) { sort(param1, param2, param3); } else if (cmd.equals("collapse")) { String trackName = param1 == null ? null : param1.replace("\"", "").replace("'", ""); collapse(trackName); } else if (cmd.equals("expand")) { String trackName = param1 == null ? null : param1.replace("\"", "").replace("'", ""); expand(trackName); } else if (cmd.equals("tweakdivider")) { IGV.getFirstInstance().tweakPanelDivider(); } else if (cmd.equals("maxpanelheight") && param1 != null) { return setMaxPanelHeight(param1); } else if (cmd.equals("exit")) { System.exit(0); } else { log.error("UNKOWN COMMAND: " + command); return "UNKOWN COMMAND: " + command; } } else { return "Empty command string"; } IGV.getFirstInstance().doRefresh(); if (RuntimeUtils.getAvailableMemoryFraction() < 0.5) { log.debug("Clearing caches"); LRUCache.clearCaches(); } log.debug("Finished execution: " + command + " sleeping ...."); Thread.sleep(2000); log.debug("Finished sleeping"); } catch (Exception e) { log.error("Could not Parse Command", e); return "ERROR Could not Parse Command: " + e.toString(); } log.info(result); return result; } private String setMaxPanelHeight(String param1) { try { Integer h = Integer.parseInt(param1.trim()); SnapshotUtilities.MAX_PANEL_HEIGHT = h; return "OK"; } catch (NumberFormatException e) { return "ERROR - max panel height value ('" + param1 + ".) must be a number"; } } private String genome(String param1) { if (param1 == null) { return "ERROR missing genome parameter"; } String result; String genomeID = param1; IGV.getFirstInstance().selectGenomeFromList(genomeID); result = "OK"; return result; } private String hget(String param1, String param2, String param3) throws IOException { String result; String fileString = param1; String locusString = URLDecoder.decode(param2); String mergeValue = param3; boolean merge = mergeValue != null && mergeValue.equalsIgnoreCase("true"); result = loadFiles(fileString, locusString, merge); return result; } private String load(String param1) throws IOException { if (param1 == null) { return "ERROR: missing path parameter"; } String fileString = param1.replace("\"", "").replace("'", ""); return loadFiles(fileString, null, true); } private String setSnapshotDirectory(String param1) { if (param1 == null) { return "ERROR: missing directory parameter"; } String result; File parentDir = new File(param1); if (parentDir.exists()) { snapshotDirectory = parentDir; result = "OK"; } else { parentDir.mkdir(); if (parentDir.exists()) { snapshotDirectory = parentDir; result = "OK"; } else { result = "ERROR: directory: " + param1 + " does not exist"; } } return result; } private String goto1(List<String> args) { if (args == null || args.size() < 2) { return "ERROR: missing locus parameter"; } String locus = args.get(1); for (int i = 2; i < args.size(); i++) { locus += (" " + args.get(i)); } IGV.getFirstInstance().goToLocus(locus); return "OK"; } private void collapse(String trackName) { if (trackName == null) { IGV.getFirstInstance().getTrackManager().collapseTracks(); } else { IGV.getFirstInstance().getTrackManager().collapseTrack(trackName); } IGV.getFirstInstance().repaintDataPanels(); } private void expand(String trackName) { if (trackName == null) { IGV.getFirstInstance().getTrackManager().expandTracks(); } else { IGV.getFirstInstance().getTrackManager().expandTrack(trackName); } IGV.getFirstInstance().repaintDataPanels(); } private void defineRegion(String param1, String param2, String param3) { RegionOfInterest roi = null; if (param1 != null && param2 != null && param3 != null) { int start = Math.max(0, Integer.parseInt(param2) - 1); int end = Integer.parseInt(param3); roi = new RegionOfInterest(param1, start, end, ""); } if (param1 != null) { Locus locus = new Locus(param1); if (locus.isValid()) { int start = Math.max(0, locus.getStart() - 1); roi = new RegionOfInterest(locus.getChr(), start, locus.getEnd(), ""); } } if (roi != null) { IGV.getFirstInstance().addRegionOfInterest(roi); } } private void sort(String sortArg, String locusString, String param3) { TrackManager tm = IGV.getFirstInstance().getTrackManager(); RegionScoreType regionSortOption = getRegionSortOption(sortArg); if (regionSortOption != null) { RegionOfInterest roi = null; if (locusString != null) { Locus locus = new Locus(locusString); if (locus.isValid()) { int start = Math.max(0, locus.getStart() - 1); roi = new RegionOfInterest(locus.getChr(), start, locus.getEnd(), ""); } } tm.sortByRegionScore(roi, regionSortOption, FrameManager.getDefaultFrame()); } else { Double location = null; if (param3 != null && param3.trim().length() > 0) { try { location = new Double(param3.replace(",", "")); } catch (NumberFormatException e) { log.info("Unexpected sort location argument (expected number): " + param3); } } else if (locusString != null && locusString.trim().length() > 0) { try { location = new Double(locusString.replace(",", "")); } catch (NumberFormatException e) { log.info("Unexpected sort location argument (expected number): " + param3); } } if (location == null) { tm.sortAlignmentTracks(getAlignmentSortOption(sortArg)); } else { tm.sortAlignmentTracks(getAlignmentSortOption(sortArg), location); } } IGV.getFirstInstance().repaintDataPanels(); } private String loadFiles(final String fileString, final String locus, final boolean merge) throws IOException { log.debug("Run load files"); String[] files = fileString.split(","); List<ResourceLocator> fileLocators = new ArrayList<ResourceLocator>(); List<String> sessionPaths = new ArrayList<String>(); if (!merge) { IGV.getFirstInstance().createNewSession(null); } for (String f : files) { if (f.endsWith(".xml")) { sessionPaths.add(f); } else { ResourceLocator rl = new ResourceLocator(f); fileLocators.add(rl); } } for (String sessionPath : sessionPaths) { IGV.getFirstInstance().doRestoreSession(sessionPath, locus, merge); } IGV.getFirstInstance().loadTracks(fileLocators); if (locus != null && !locus.equals("null")) { IGV.getFirstInstance().goToLocus(locus); } return "OK"; } private void createSnapshot(String filename) { IGV mainFrame = IGV.getFirstInstance(); if (filename == null) { String locus = FrameManager.getDefaultFrame().getFormattedLocusString(); filename = locus.replaceAll(":", "_").replace("-", "_") + ".png"; } File file = snapshotDirectory == null ? new File(filename) : new File(snapshotDirectory, filename); System.out.println("Snapshot: " + file.getAbsolutePath()); SnapshotUtilities.doSnapshotOffscreen(mainFrame.getMainPanel(), file); } private static RegionScoreType getRegionSortOption(String str) { if (str == null) return null; String option = str.toUpperCase(); try { return RegionScoreType.valueOf(option); } catch (Exception e) { return null; } } //START, STRAND, NUCLEOTIDE, QUALITY, SAMPLE, READ_GROUP private static AlignmentTrack.SortOption getAlignmentSortOption(String str) { String option = str.toLowerCase(); if (str == null || option.equals("base")) { return AlignmentTrack.SortOption.NUCELOTIDE; } else if (option.equals("strand")) { return AlignmentTrack.SortOption.STRAND; } else if (option.equals("start") || option.equals("position")) { return AlignmentTrack.SortOption.START; } else if (option.equals("quality")) { return AlignmentTrack.SortOption.QUALITY; } else if (option.equals("sample")) { return AlignmentTrack.SortOption.SAMPLE; } else if (option.equals("readGroup") || option.equals("read_group")) { return AlignmentTrack.SortOption.READ_GROUP; } else if (option.equals("insertSize") || option.equals("insert_size")) { return AlignmentTrack.SortOption.INSERT_SIZE; } return AlignmentTrack.SortOption.NUCELOTIDE; } }
package org.dita.dost.reader; import java.io.File; import org.dita.dost.exception.DITAOTXMLErrorHandler; import org.dita.dost.log.DITAOTJavaLogger; import org.dita.dost.module.Content; import org.dita.dost.module.ContentImpl; import org.dita.dost.util.Constants; import org.dita.dost.util.MergeUtils; import org.dita.dost.util.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * MergeMapParser reads the ditamap file after preprocessing and merges * different files into one intermediate result. It calls MergeTopicParser * to process the topic file. * * @author Zhang, Yuan Peng */ public class MergeMapParser extends AbstractXMLReader { private XMLReader reader = null; private StringBuffer mapInfo = null; private MergeTopicParser topicParser = null; private DITAOTJavaLogger logger = null; private MergeUtils util; private ContentImpl content; private String dirPath = null; /** * Default Constructor */ public MergeMapParser() { logger = new DITAOTJavaLogger(); try{ if (System.getProperty(Constants.SAX_DRIVER_PROPERTY) == null){ //The default sax driver is set to xerces's sax driver StringUtils.initSaxDriver(); } if(reader == null){ reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(this); // reader.setProperty(Constants.LEXICAL_HANDLER_PROPERTY,this); reader.setFeature(Constants.FEATURE_NAMESPACE_PREFIX, true); // reader.setFeature(Constants.FEATURE_VALIDATION, true); // reader.setFeature(Constants.FEATURE_VALIDATION_SCHEMA, true); } if(mapInfo == null){ mapInfo = new StringBuffer(Constants.INT_1024); } topicParser = new MergeTopicParser(); content = new ContentImpl(); util = MergeUtils.getInstance(); }catch (Exception e){ logger.logException(e); } } /** * @see org.dita.dost.reader.AbstractReader#getContent() */ public Content getContent() { content.setValue(mapInfo.append((StringBuffer)topicParser.getContent().getValue())); return content; } /** * @see org.dita.dost.reader.AbstractReader#read(java.lang.String) */ public void read(String filename) { try{ File input = new File(filename); dirPath = input.getParent(); reader.setErrorHandler(new DITAOTXMLErrorHandler(filename)); reader.parse(filename); }catch(Exception e){ logger.logException(e); } } /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ public void endElement(String uri, String localName, String qName) throws SAXException { mapInfo.append(Constants.LESS_THAN) .append(Constants.SLASH) .append(qName) .append(Constants.GREATER_THAN); } /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ public void characters(char[] ch, int start, int length) throws SAXException { mapInfo.append(StringUtils.escapeXML(ch, start, length)); } /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { String scopeValue = null; String formatValue = null; String classValue = null; String fileId = null; int attsLen = atts.getLength(); mapInfo.append(Constants.LESS_THAN).append(qName); for (int i = 0; i < attsLen; i++) { String attQName = atts.getQName(i); String attValue = atts.getValue(i); if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName) && !StringUtils.isEmptyString(attValue) && classValue != null && classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){ scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE); formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT); // if (attValue.indexOf(Constants.SHARP) != -1){ // attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP)); if((scopeValue == null || Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue)) && (formatValue == null || Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){ if (util.isVisited(attValue)){ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); // random = RandomUtils.getRandomNum(); // filename = attValue + "(" + Long.toString(random) + ")"; attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString(); //parse the file but give it another file name // topicParser.read(filename); }else{ mapInfo.append(Constants.STRING_BLANK) .append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); //parse the topic fileId = topicParser.parse(attValue,dirPath); util.visit(attValue); attValue = new StringBuffer(Constants.SHARP).append(fileId).toString(); } } } //output all attributes mapInfo.append(Constants.STRING_BLANK) .append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION) .append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION); } mapInfo.append(Constants.GREATER_THAN); } }
// Administrator of the National Aeronautics and Space Administration // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file NOSA-1.3-JPF at the top of the distribution // directory tree for the complete NOSA document. // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. package gov.nasa.jpf.jvm; import java.io.PrintWriter; import gov.nasa.jpf.Config; import gov.nasa.jpf.JPFException; import gov.nasa.jpf.util.HashData; import gov.nasa.jpf.jvm.bytecode.Instruction; import java.lang.reflect.Array; /** * the class that encapsulates not only the current execution state of the VM * (the KernelState), but also the part of it's history that is required * by JVM to backtrack, plus some potential annotations that can be used to * control the search (i.e. forward/backtrack calls) */ public class SystemState { /** * instances of this class are used to store the SystemState parts which are * subject to backtracking/state resetting. At some point, we might have * stripped SystemState down enough to just store the SystemState itself * (so far, we don't change it's identity, there is only one) * the KernelState is still stored separately (which seems to be another * anachronism) * * NOTE: this gets stored at the end of a transition, i.e. if we need a value * to be restored to it's transition entry state (like atomicLevel), we have * to do that explicitly. Alternatively we could create the Memento before * we start to execute the step, but then we have to update the nextCg in the * snapshot, since it's only set at the transition end (required for * restore(), i.e. HeuristicSearches) */ static class Memento { ChoiceGenerator<?> curCg; // the ChoiceGenerator for the current transition ChoiceGenerator<?> nextCg; int atomicLevel; ChoicePoint trace; ThreadInfo execThread; int id; // the state id Memento (SystemState ss) { nextCg = ss.nextCg; curCg = ss.curCg; atomicLevel = ss.entryAtomicLevel; // store the value we had when we started the transition id = ss.id; execThread = ss.execThread; } /** * this one is used to restore to a state which will re-execute with the next choice * of the same CG, i.e. nextCG is reset */ void backtrack (SystemState ss) { ss.nextCg = null; // this is important - the nextCG will be set by the next Transition ss.curCg = curCg; ss.atomicLevel = atomicLevel; ss.id = id; ss.execThread = execThread; } /** * this one is used if we restore and then advance, i.e. it might change the CG on * the next advance (if nextCg was set) */ void restore (SystemState ss) { ss.nextCg = nextCg; ss.curCg = curCg; ss.atomicLevel = atomicLevel; ss.id = id; ss.execThread = execThread; } } int id; /** the state id */ ChoiceGenerator<?> nextCg; // the ChoiceGenerator for the next transition ChoiceGenerator<?> curCg; // the ChoiceGenerator used in the current transition ThreadInfo execThread; // currently executing thread, reset by ThreadChoiceGenerators static enum RANDOMIZATION {random, path, def}; /** current execution state of the VM (stored separately by VM) */ public KernelState ks; public Transition trail; /** trace information */ boolean retainAttributes; // as long as this is set, we don't reset attributes boolean isIgnored; // treat this as a matched state, i.e. backtrack boolean isForced; // treat this as a new state boolean isInteresting; boolean isBoring; boolean isBlockedInAtomicSection; /** uncaught exception in current transition */ public UncaughtException uncaughtException; /** set to true if garbage collection is necessary */ boolean GCNeeded = false; // this is an optimization - long transitions can cause a lot of short-living // garbage, which in turn can slow down the system considerably (heap size) // by setting 'nAllocGCThreshold', we can do sync. on-the-fly gc when the // number of new allocs within a single transition exceeds this value int maxAllocPerGC; int nAlloc; RANDOMIZATION randomization = RANDOMIZATION.def; /** NOTE: this has changed its meaning again. Now it once more is an * optimization that can be used by applications calling Verify.begin/endAtomic(), * but be aware of that it now reports a deadlock property violation in * case of a blocking op inside an atomic section * Data CGs however are now allowed to be inside atomic sections */ int atomicLevel; int entryAtomicLevel; /** the policy object used to create scheduling related ChoiceGenerators */ SchedulerFactory schedulerFactory; /** do we want CGs to randomize the order in which they return choices? */ boolean randomizeChoices = false; /** do we want executed insns to be recorded */ boolean recordSteps; /** * Creates a new system state. */ public SystemState (Config config, JVM vm) { ks = new KernelState(config); id = StateSet.UNKNOWN_ID; Class<?>[] argTypes = { Config.class, JVM.class, SystemState.class }; Object[] args = { config, vm, this }; schedulerFactory = config.getEssentialInstance("vm.scheduler_factory.class", SchedulerFactory.class, argTypes, args); // we can't yet initialize the trail until we have the start thread randomization = config.getEnum("cg.randomize_choices", RANDOMIZATION.values(), RANDOMIZATION.def); if(randomization != RANDOMIZATION.def) { randomizeChoices = true; } maxAllocPerGC = config.getInt("vm.max_alloc_gc", Integer.MAX_VALUE); // recordSteps is set later by VM, first we need a reporter (which requires the VM) } protected SystemState() { // just for unit test mockups } public void setStartThread (ThreadInfo ti) { execThread = ti; trail = new Transition(nextCg, execThread); } public int getId () { return id; } public void setId (int newId) { id = newId; trail.setStateId(newId); } public void recordSteps (boolean cond) { recordSteps = cond; } /** * use those with extreme care, it overrides scheduling choices */ public void incAtomic () { atomicLevel++; } public void decAtomic () { if (atomicLevel > 0) { atomicLevel } } public void clearAtomic() { atomicLevel = 0; } public boolean isAtomic () { return (atomicLevel > 0); } public void setBlockedInAtomicSection() { isBlockedInAtomicSection = true; } public Transition getTrail() { return trail; } public SchedulerFactory getSchedulerFactory () { return schedulerFactory; } /** * answer the ChoiceGenerator that is used in the current transition */ public ChoiceGenerator<?> getChoiceGenerator () { return curCg; } public ChoiceGenerator<?> getChoiceGenerator (String id) { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getPreviousChoiceGenerator()){ if (id.equals(cg.getId())){ return cg; } } return null; } /** * return the whole stack of CGs of the current path */ public ChoiceGenerator<?>[] getChoiceGenerators () { return curCg.getAll(); } public <T extends ChoiceGenerator<?>> T[] getChoiceGeneratorsOfType (Class<T> cgType) { return curCg.getAllOfType(cgType); } public <T extends ChoiceGenerator<?>> T getLastChoiceGeneratorOfType (Class<T> cgType) { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getPreviousChoiceGenerator()){ if (cgType.isAssignableFrom(cg.getClass())) { return (T)cg; } } return null; } public <T extends ChoiceGenerator<?>> T getCurrentChoiceGeneratorOfType (Class<T> cgType) { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getCascadedParent()){ if (cgType.isAssignableFrom(cg.getClass())){ return (T)cg; } } return null; } public <T extends ChoiceGenerator<?>> T getCurrentChoiceGenerator (String id, Class<T> cgType) { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getCascadedParent()){ if (id.equals(cg.getId()) && cgType.isAssignableFrom(cg.getClass())){ return (T)cg; } } return null; } public ChoiceGenerator<?> getCurrentChoiceGenerator (String id) { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getCascadedParent()){ if (id.equals(cg.getId())){ return cg; } } return null; } public ChoiceGenerator<?> getCurrentChoiceGenerator (ChoiceGenerator<?> cgPrev) { if (cgPrev == null){ return curCg; } else { return cgPrev.getCascadedParent(); } } /** * this returns the most recently registered ThreadChoiceGenerator that is * also a scheduling point, or 'null' if there is none in the list of current CGs */ public ThreadChoiceGenerator getCurrentSchedulingPoint () { for (ChoiceGenerator<?> cg = curCg; cg != null; cg = cg.getCascadedParent()){ if (cg instanceof ThreadChoiceGenerator){ ThreadChoiceGenerator tcg = (ThreadChoiceGenerator)cg; if (tcg.isSchedulingPoint()){ return tcg; } } } return null; } public ChoiceGenerator<?>[] getCurrentChoiceGenerators () { return curCg.getCascade(); } public <T extends ChoiceGenerator<?>> T getInsnChoiceGeneratorOfType (Class<T> cgType, Instruction insn, ChoiceGenerator<?> cgPrev){ ChoiceGenerator<?> cg = cgPrev != null ? cgPrev.getPreviousChoiceGenerator() : curCg; if (cg != null && cg.getInsn() == insn && cgType.isAssignableFrom(cg.getClass())){ return (T)cg; } return null; } public ChoiceGenerator<?> getNextChoiceGenerator () { return nextCg; } /** * set the ChoiceGenerator to be used in the next transition */ public void setNextChoiceGenerator (ChoiceGenerator<?> cg) { if (isIgnored){ // if this transition is already marked as ignored, we are not allowed // to set nextCg because 'isIgnored' results in a shortcut backtrack that // is not handed back to the Search (its solely in JVM forward) return; } // first, check if we have to randomize it (might create a new one) if (randomizeChoices){ cg = cg.randomize(); } // set its context (thread and insn) cg.setContext(execThread); // do we already have a nextCG, which means this one is a cascadet CG if (nextCg != null){ cg.setPreviousChoiceGenerator( nextCg); nextCg.setCascaded(); // note the last registered CG is NOT set cascaded } else { cg.setPreviousChoiceGenerator(curCg); } nextCg = cg; } public Object getBacktrackData () { return new Memento(this); } public void backtrackTo (Object backtrackData) { ((Memento) backtrackData).backtrack( this); } public void restoreTo (Object backtrackData) { ((Memento) backtrackData).restore( this); } public void retainAttributes (boolean b){ retainAttributes = b; } public boolean getRetainAttributes() { return retainAttributes; } /** * this can be called anywhere from within a transition, to revert it and * go on with the next choice. This is mostly used explicitly in the app * via Verify.ignoreIf(..) * * calling setIgnored() also breaks the current transition, i.e. no further * instructions are executed within this step * * NOTE: this reverts any previous or future setNextChoiceGenerator() call * during this transition */ public void setIgnored (boolean b) { if (nextCg != null) { // Umm, that's kinky - can only happen if somebody first explicitly sets // a CG from a listener, only to decide afterwards to dump this whole // transition alltogether. Gives us problems because ignored transitions // are not handed back to the search, i.e. are not normally backtracked // causes a ClassCastException in nextSuccessor (D&C's bug) nextCg = null; } isIgnored = b; if (b){ isForced = false; // mutually exclusive } } public boolean isIgnored () { return isIgnored; } public void setForced (boolean b){ isForced = b; if (b){ isIgnored = false; // mutually exclusive } } public boolean isForced () { return isForced; } public void setInteresting (boolean b) { isInteresting = b; if (b){ isBoring = false; } } public boolean isInteresting () { return isInteresting; } public void setBoring (boolean b) { isBoring = b; if (b){ isInteresting = false; } } public boolean isBoring () { return isBoring; } public boolean isInitState () { return (id == StateSet.UNKNOWN_ID); } public int getNonDaemonThreadCount () { return ks.tl.getNonDaemonThreadCount(); } public ElementInfo getObject (int reference) { return ks.da.get(reference); } @Deprecated public ThreadInfo getThread (int index) { return ks.tl.get(index); } @Deprecated public ThreadInfo getThread (ElementInfo reference) { return getThread(reference.getIndex()); } public int getThreadCount () { return ks.tl.length(); } public int getRunnableThreadCount () { return ks.tl.getRunnableThreadCount(); } public int getLiveThreadCount () { return ks.tl.getLiveThreadCount(); } public ThreadInfo getThreadInfo (int idx) { return ks.tl.get(idx); } public boolean isDeadlocked () { if (isBlockedInAtomicSection) { return true; // blocked in atomic section } return ks.isDeadlocked(); } public UncaughtException getUncaughtException () { return uncaughtException; } public void activateGC () { GCNeeded = true; } public void gcIfNeeded () { if (GCNeeded) { ks.gc(); GCNeeded = false; } nAlloc = 0; } /** * check if number of allocations since last GC exceed the maxAllocPerGC * threshold, perform on-the-fly GC if yes. This is aimed at avoiding a lot * of short-living garbage in long transitions, which slows down the heap * exponentially */ public void checkGC () { if (nAlloc++ > maxAllocPerGC){ gcIfNeeded(); } } public void hash (HashData hd) { ks.hash(hd); } void dumpThreadCG (ThreadChoiceGenerator cg) { PrintWriter pw = new PrintWriter(System.out, true); cg.printOn(pw); pw.flush(); } /** * Compute next program state * * return 'true' if we actually executed instructions, 'false' if this * state was already completely processed * * This is one of the key methods of the JPF execution * engine (together with VM.forward() and ThreadInfo.executeStep(),executeInstruction() * */ public boolean nextSuccessor (JVM vm) throws JPFException { if (!retainAttributes){ isIgnored = false; isForced = false; isInteresting = false; isBoring = false; } // 'nextCg' got set at the end of the previous transition (or a preceding // choiceGeneratorSet() notification). // Be aware of that 'nextCg' is only the *last* CG that was registered, i.e. // there can be any number of CGs between the previous 'curCg' and 'nextCg' // that were registered for the same insn. while (nextCg != null) { curCg = nextCg; nextCg = null; // Hmm, that's a bit late (could be in setNextCG), but we keep it here // for the sake of locality, and it's more consistent if it just refers // to curCg, i.e. the CG that is actually going to be used notifyChoiceGeneratorSet(vm, curCg); } assert (curCg != null) : "transition without choice generator"; if (!advanceCurCg( vm)){ return false; } // do we have a thread context switch setExecThread( vm); assert execThread.isRunnable() : "current thread not runnable: " + execThread.getStateDescription(); trail = new Transition(curCg, execThread); entryAtomicLevel = atomicLevel; // store before we start to execute execThread.executeStep(this); return true; } // the number of advanced choice generators in this step protected int nAdvancedCGs; protected void advance( JVM vm, ChoiceGenerator<?> cg){ while (true) { if (cg.hasMoreChoices()){ cg.advance(); isIgnored = false; vm.notifyChoiceGeneratorAdvanced(cg); if (!isIgnored){ nAdvancedCGs++; break; } } else { vm.notifyChoiceGeneratorProcessed(cg); break; } } } protected void advanceAllCascadedParents( JVM vm, ChoiceGenerator<?> cg){ ChoiceGenerator<?> parent = cg.getCascadedParent(); if (parent != null){ advanceAllCascadedParents(vm, parent); } advance(vm, cg); } protected boolean advanceCascadedParent (JVM vm, ChoiceGenerator<?> cg){ if (cg.hasMoreChoices()){ advance(vm,cg); return true; } else { ChoiceGenerator<?> parent = cg.getCascadedParent(); if (parent != null){ if (advanceCascadedParent(vm,parent)){ cg.reset(); advance(vm,cg); return true; } } return false; } } protected boolean advanceCurCg (JVM vm){ nAdvancedCGs = 0; ChoiceGenerator<?> cg = curCg; ChoiceGenerator<?> parent = cg.getCascadedParent(); if (cg.hasMoreChoices()){ // check if this is the first time, when we also have to advance our parents if (parent != null && parent.getProcessedNumberOfChoices() == 0){ advanceAllCascadedParents(vm,parent); } advance(vm, cg); } else { // this one is done, but how about our parents vm.notifyChoiceGeneratorProcessed(cg); if (parent != null){ if (advanceCascadedParent(vm,parent)){ cg.reset(); advance(vm,cg); } } } return (nAdvancedCGs > 0); } protected void notifyChoiceGeneratorSet (JVM vm, ChoiceGenerator<?> cg){ ChoiceGenerator<?> parent = cg.getCascadedParent(); if (parent != null) { notifyChoiceGeneratorSet(vm, parent); } vm.notifyChoiceGeneratorSet(cg); // notify top down } protected void setExecThread( JVM vm){ ThreadChoiceGenerator tcg = getCurrentSchedulingPoint(); if (tcg != null){ ThreadInfo tiNext = tcg.getNextChoice(); if (tiNext != execThread) { vm.notifyThreadScheduled(tiNext); execThread = tiNext; } } } // this is called on every executeInstruction from the running thread public boolean breakTransition () { return ((nextCg != null) || isIgnored); } void recordExecutionStep (Instruction pc) { // this can require a lot of memory, so we should only store // executed insns if we have to if (recordSteps) { Step step = new Step(pc); trail.addStep( step); } else { trail.incStepCount(); } } public boolean isEndState () { return ks.isTerminated(); } // the three primitive ops used from within JVM.forward() }
package org.exist.plugin; import java.io.*; import java.lang.invoke.LambdaMetafactory; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.net.URL; import java.util.*; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Database; import org.exist.EXistException; import org.exist.LifeCycle; import org.exist.backup.BackupHandler; import org.exist.backup.RestoreHandler; import org.exist.collections.Collection; import org.exist.config.*; import org.exist.config.Configuration; import org.exist.config.annotation.*; import org.exist.security.Permission; import org.exist.storage.BrokerPool; import org.exist.storage.BrokerPoolService; import org.exist.storage.BrokerPoolServiceException; import org.exist.storage.DBBroker; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.serializer.SAXSerializer; import org.exist.xmldb.XmldbURI; import org.w3c.dom.Document; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import static java.lang.invoke.MethodType.methodType; /** * Plugins manager. * It control search procedure, activation and de-actication (including runtime). * * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> */ @ConfigurationClass("plugin-manager") public class PluginsManagerImpl implements Configurable, BrokerPoolService, PluginsManager, LifeCycle { private static final Logger LOG = LogManager.getLogger(PluginsManagerImpl.class); private static final XmldbURI COLLETION_URI = XmldbURI.SYSTEM.append("plugins"); private static final XmldbURI CONFIG_FILE_URI = XmldbURI.create("config.xml"); @ConfigurationFieldAsAttribute("version") private String version = "1.0"; @ConfigurationFieldAsElement("plugin") private List<String> runPlugins = new ArrayList<>(); private Map<String, Plug> jacks = new HashMap<>(); private Configuration configuration = null; private Collection collection; private Database db; @Override public void prepare(final BrokerPool brokerPool) { this.db = brokerPool; //Temporary for testing addPlugin("org.exist.scheduler.SchedulerManager"); addPlugin("org.exist.storage.md.MDStorageManager"); addPlugin("org.exist.monitoring.MonitoringManager"); } @Override public void startSystem(final DBBroker systemBroker) throws BrokerPoolServiceException { try { start(systemBroker); } catch(final EXistException e) { throw new BrokerPoolServiceException(e); } } @Override public void start(DBBroker broker) throws EXistException { final TransactionManager transaction = broker.getBrokerPool().getTransactionManager(); boolean interrupted = false; try { try (final Txn txn = transaction.beginTransaction()) { collection = broker.getCollection(COLLETION_URI); if (collection == null) { collection = broker.getOrCreateCollection(txn, COLLETION_URI); if (collection == null) { return; } //if db corrupted it can lead to unrunnable issue //throw new ConfigurationException("Collection '/db/system/plugins' can't be created."); collection.setPermissions(Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM); broker.saveCollection(txn, collection); } transaction.commit(txn); } catch (final Exception e) { LOG.warn("Loading PluginsManager configuration failed: " + e.getMessage()); } final Configuration _config_ = Configurator.parse(this, broker, collection, CONFIG_FILE_URI); configuration = Configurator.configure(this, _config_); //load plugins by META-INF/services/ try { final MethodHandles.Lookup lookup = MethodHandles.lookup(); for (final Class<? extends Plug> pluginClazz : listServices(Plug.class)) { try { final MethodHandle methodHandle = lookup.findConstructor(pluginClazz, methodType(void.class, PluginsManager.class)); final Function<PluginsManager, Plug> ctor = (Function<PluginsManager, Plug>) LambdaMetafactory.metafactory( lookup, "apply", methodType(Function.class), methodHandle.type().erase(), methodHandle, methodHandle.type()).getTarget().invokeExact(); final Plug plgn = ctor.apply(this); jacks.put(pluginClazz.getName(), plgn); } catch (final Throwable e) { if (e instanceof InterruptedException) { // NOTE: must set interrupted flag interrupted = true; } LOG.error(e); } } } catch (final Throwable e) { LOG.error(e); } //UNDERSTAND: call save? // try { // configuration.save(broker); // //LOG? for (final Plug jack : jacks.values()) { jack.start(broker); } } finally { if (interrupted) { // NOTE: must set interrupted flag Thread.currentThread().interrupt(); } } } @Override public void sync(final DBBroker broker) { for (final Plug plugin : jacks.values()) { try { plugin.sync(broker); } catch (final Throwable e) { LOG.error(e); } } } @Override public void stop(final DBBroker broker) { for (final Plug plugin : jacks.values()) { try { plugin.stop(broker); } catch (final Throwable e) { LOG.error(e); } } } public String version() { return version; } @Override public Database getDatabase() { return db; //TODO(AR) get rid of this, maybe expand the BrokerPoolService arch to replace PluginsManagerImpl etc } @SuppressWarnings("unchecked") @Override public void addPlugin(final String className) { //check if already run if (jacks.containsKey(className)) {return;} try { final Class<? extends Plug> pluginClazz = (Class<? extends Plug>) Class.forName(className); final MethodHandles.Lookup lookup = MethodHandles.lookup(); final MethodHandle methodHandle = lookup.findConstructor(pluginClazz, methodType(void.class, PluginsManager.class)); final Function<PluginsManager, Plug> ctor = (Function<PluginsManager, Plug>) LambdaMetafactory.metafactory( lookup, "apply", methodType(Function.class), methodHandle.type().erase(), methodHandle, methodHandle.type()).getTarget().invokeExact(); final Plug plgn = ctor.apply(this); jacks.put(pluginClazz.getName(), plgn); runPlugins.add(className); //TODO: if (jack instanceof Startable) { ((Startable) jack).startUp(broker); } } catch (final Throwable e) { if (e instanceof InterruptedException) { // NOTE: must set interrupted flag Thread.currentThread().interrupt(); } LOG.error(e); } } /* * Generate list of service implementations */ private <S> Iterable<Class<? extends S>> listServices(final Class<S> ifc) throws Exception { final ClassLoader ldr = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> e = ldr.getResources("META-INF/services/" + ifc.getName()); final Set<Class<? extends S>> services = new HashSet<>(); while (e.hasMoreElements()) { final URL url = e.nextElement(); try (final InputStream is = url.openStream(); final BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { String line; while ((line = r.readLine()) != null) { final int comment = line.indexOf(' if (comment >= 0) { line = line.substring(0, comment); } final String name = line.trim(); if (name.length() == 0) { continue; } final Class<?> clz = Class.forName(name, true, ldr); final Class<? extends S> impl = clz.asSubclass(ifc); services.add(impl); } } } return services; } @Override public boolean isConfigured() { return configuration != null; } @Override public Configuration getConfiguration() { return configuration; } @Override public BackupHandler getBackupHandler(final Logger logger) { return new BH(logger); } class BH implements BackupHandler { Logger LOG; BH(final Logger logger) { LOG = logger; } @Override public void backup(final Collection colection, final AttributesImpl attrs) { for (final Plug plugin : jacks.values()) { if (plugin instanceof BackupHandler) { try { ((BackupHandler) plugin).backup(colection, attrs); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } } } @Override public void backup(final Collection colection, final SAXSerializer serializer) { for (final Plug plugin : jacks.values()) { if (plugin instanceof BackupHandler) { try { ((BackupHandler) plugin).backup(colection, serializer); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } } } @Override public void backup(final Document document, final AttributesImpl attrs) { for (final Plug plugin : jacks.values()) { if (plugin instanceof BackupHandler) { try { ((BackupHandler) plugin).backup(document, attrs); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } } } @Override public void backup(final Document document, final SAXSerializer serializer) { for (final Plug plugin : jacks.values()) { if (plugin instanceof BackupHandler) { try { ((BackupHandler) plugin).backup(document, serializer); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } } } } private RestoreHandler rh = new RH(); @Override public RestoreHandler getRestoreHandler() { return rh; } class RH implements RestoreHandler { @Override public void setDocumentLocator(final Locator locator) { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).setDocumentLocator(locator); } } } @Override public void startDocument() throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).startDocument(); } } } @Override public void endDocument() throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).endDocument(); } } } @Override public void startPrefixMapping(final String prefix, final String uri) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).startPrefixMapping(prefix, uri); } } } @Override public void endPrefixMapping(final String prefix) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).endPrefixMapping(prefix); } } } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).startElement(uri, localName, qName, atts); } } } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).endElement(uri, localName, qName); } } } @Override public void characters(final char[] ch, final int start, final int length) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).characters(ch, start, length); } } } @Override public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).ignorableWhitespace(ch, start, length); } } } @Override public void processingInstruction(final String target, final String data) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).processingInstruction(target, data); } } } @Override public void skippedEntity(final String name) throws SAXException { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).skippedEntity(name); } } } @Override public void startCollectionRestore(final Collection colection, final Attributes atts) { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).startCollectionRestore(colection, atts); } } } @Override public void endCollectionRestore(final Collection colection) { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).endCollectionRestore(colection); } } } @Override public void startDocumentRestore(final Document document, final Attributes atts) { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).startDocumentRestore(document, atts); } } } @Override public void endDocumentRestore(final Document document) { for (final Plug plugin : jacks.values()) { if (plugin instanceof RestoreHandler) { ((RestoreHandler) plugin).endDocumentRestore(document); } } } } }
package org.exist.storage; import java.util.ArrayList; import java.util.Map; import org.apache.log4j.Logger; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Contains information about which parts of a document should be * fulltext-indexed for a specified doctype. It basically keeps a list of paths * to include and exclude from indexing. Paths are specified using * simple XPath syntax, e.g. //SPEECH will select any SPEECH elements, * //title/@id will select all id attributes being children of title elements. * * @author Wolfgang Meier */ public class FulltextIndexSpec { private static final String PATH_ATTRIB = "path"; private static final String CONTENT_ATTRIB = "content"; private static final String CONTENT_MIXED = "mixed"; private static final String PRESERVE_CONTENT_ELEMENT = "preserveContent"; private static final String EXCLUDE_INTERFACE = "exclude"; private static final String INCLUDE_ELEMENT = "include"; private static final String ALPHANUM_ATTRIB = "alphanum"; private static final String ATTRIBUTES_ATTRIB = "attributes"; private static final String DEFAULT_ATTRIB = "default"; private static final NodePath[] ARRAY_TYPE = new NodePath[0]; private final static Logger LOG = Logger.getLogger(FulltextIndexSpec.class); protected NodePath[] includePath; protected NodePath[] excludePath; protected NodePath[] mixedPath; protected NodePath[] preserveContent; protected boolean includeByDefault = true; protected boolean includeAttributes = true; protected boolean includeAlphaNum = true; /** * Constructor for the IndexPaths object * * param def if set to true, include everything by default. In this case * use exclude elements to specify the excluded parts. */ public FulltextIndexSpec(Map namespaces, Element node) { includeByDefault = true; ArrayList includeList = new ArrayList(); ArrayList excludeList = new ArrayList(); ArrayList preserveList = new ArrayList(); ArrayList mixedList = new ArrayList(); // check default settings String def = node.getAttribute(DEFAULT_ATTRIB); if(def != null && def.length() > 0) { includeByDefault = def.equals("all"); } String indexAttributes = node.getAttribute(ATTRIBUTES_ATTRIB); if (indexAttributes != null && indexAttributes.length() > 0) { includeAttributes = indexAttributes.equals("true") || indexAttributes.equals("yes"); } String indexAlphaNum = node.getAttribute(ALPHANUM_ATTRIB); if (indexAlphaNum != null && indexAlphaNum.length() > 0) setIncludeAlphaNum(indexAlphaNum.equals("true") || indexAlphaNum.equals("yes")); // check paths to include/exclude NodeList children = node.getChildNodes(); String ps, content; Node next; Element elem; for(int j = 0; j < children.getLength(); j++) { next = children.item(j); if(INCLUDE_ELEMENT.equals(next.getLocalName())) { elem = (Element) next; content = elem.getAttribute(CONTENT_ATTRIB); ps = elem.getAttribute(PATH_ATTRIB); if (content != null && content.length() != 0 && CONTENT_MIXED.equals(content)) { mixedList.add(new NodePath(namespaces, ps, false)); } else { includeList.add( new NodePath(namespaces, ps) ); } } else if(EXCLUDE_INTERFACE.equals(next.getLocalName())) { ps = ((Element) next).getAttribute(PATH_ATTRIB); excludeList.add( new NodePath(namespaces, ps) ); } else if(PRESERVE_CONTENT_ELEMENT.equals(next.getLocalName())) { ps = ((Element) next).getAttribute(PATH_ATTRIB); preserveList.add( new NodePath(namespaces, ps) ); } } includePath = (NodePath[]) includeList.toArray(ARRAY_TYPE); excludePath = (NodePath[]) excludeList.toArray(ARRAY_TYPE); preserveContent = (NodePath[]) preserveList.toArray(ARRAY_TYPE); mixedPath = (NodePath[]) mixedList.toArray(ARRAY_TYPE); } /** * @return False if all elements are indexed, True if indexation is selective. */ public boolean isSelective() { if((includeByDefault && excludePath.length > 0) || ((!includeByDefault) && includePath.length > 0)) return true; return false; } /** * Include alpha-numeric data, i.e. numbers, serials, URLs and so on? * * @param index include alpha-numeric data */ private void setIncludeAlphaNum( boolean index ) { includeAlphaNum = index; } /** * Include alpha-numeric data? */ public boolean getIncludeAlphaNum( ) { return includeAlphaNum; } /** * Check if a given path should be indexed. * * @param path path to the node * * @return Description of the Return Value */ public boolean match( NodePath path ) { if ( includeByDefault ) { // check exclusions for (int i = 0; i < excludePath.length; i++) if( excludePath[i].match(path) ) return false; return true; } for (int i = 0; i < includePath.length; i++) { if( includePath[i].match(path) ) return true; } return false; } /** * Check if a given path should be indexed. * * @param path path to the node * * @return Description of the Return Value */ public boolean matchAttribute( NodePath path ) { if ( includeAttributes) { // check exclusions for (int i = 0; i < excludePath.length; i++) if( excludePath[i].match(path) ) return false; return true; } for (int i = 0; i < includePath.length; i++) { if( includePath[i].match(path) ) return true; } return false; } /** * Check if the element corresponding to the given path * should be indexed as an element with mixed content, * i.e. the string value of the element will be indexed * as a single text sequence. Descendant elements will be ignored and * will not break the text into chunks. * * Example: a mixed content index on the element * <![CDATA[<mixed><s>un</s>even</mixed>]]> * * @param path */ public boolean matchMixedElement(NodePath path) { for (int i = 0; i < mixedPath.length; i++) { if( mixedPath[i].match(path) ) return true; } return false; } /** * Check if a given path should be preserveContent. * * @param path path to the node * * @return Description of the Return Value */ public boolean preserveContent( NodePath path ) { for (int i = 0; i < preserveContent.length; i++) { if( preserveContent[i].match(path) ) return true; } return false; } public String toString() { StringBuffer result = new StringBuffer("Full-text index\n"); result.append("\tincludeByDefault : ").append(includeByDefault).append('\n'); result.append("\tincludeAttributes : ").append(includeAttributes).append('\n'); result.append("\tincludeAlphaNum : ").append(includeAlphaNum).append('\n'); if (includePath != null) { for (int i = 0 ; i < includePath.length; i++) { NodePath path = includePath[i]; if (path != null) result.append("\tinclude : ").append(path.toString()).append('\n'); } } if (excludePath != null) { for (int i = 0 ; i < excludePath.length; i++) { NodePath path = excludePath[i]; if (path != null) result.append("\texclude : ").append(path.toString()).append('\n'); } } if (preserveContent != null) { for (int i = 0 ; i < preserveContent.length; i++) { NodePath path = preserveContent[i]; if (path != null) result.append("\tpreserve content : ").append(path.toString()).append('\n'); } } return result.toString(); } }
package builders; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.tuple.Pair; import eAdapter.Document; import eAdapter.Representative; /** * * @author Jeff Gillispie * @version December 2016 * * Purpose: Builds a list of documents from a list of lines split on a comma * that represent either a single document or a group of documents. */ public class OpticonBuilder { private final int IMAGE_KEY_INDEX = 0; private final int VOLUME_NAME_INDEX = 1; private final int FULL_PATH_INDEX = 2; private final int DOC_BREAK_INDEX = 3; private final int BOX_BREAK_INDEX = 4; private final int FOLDER_BREAK_INDEX = 5; private final int PAGE_COUNT_INDEX = 6; private final String TRUE_VALUE = "Y"; private final String IMAGE_KEY_FIELD = "DocID"; private final String VOLUME_NAME_FIELD = "Volume Name"; private final String PAGE_COUNT_FIELD = "Page Count"; private final String BOX_BREAK_FIELD = "Box Break"; private final String FOLDER_BREAK_FIELD = "Folder Break"; private final String TEXT_EXT = ".txt"; private final String DEFAULT_IMAGE_REP_NAME = "default"; private final String DEFAULT_TEXT_REP_NAME = "default"; /** * Levels that a text representative can be. */ public enum TextLevel { /** * No text representative exists. */ None, /** * The text representative has a text file that corresponds to each page in the document * and it must be accompanied by a page level image. */ Page, /** * The text representative has a single text file that contains the text for all pages * of the document. The text file base name matches the image file base name of the * first page of the document. */ Doc } /** * Locations where a text representative can be. */ public enum TextLocation { /** * No text representative exists. */ None, /** * The text files reside in the same location as the image files. */ SameAsImages, /** * The text files reside in an alternate location. * A find/replace operation will transform the image path into the text path. */ AlternateLocation, } /** * Builds a list of documents from an opticon file with no text representatives and uses the default image representative name * @param lines the lines read from an opt file split on a comma * @return returns a list of documents */ public List<Document> buildDocuments(List<String[]> lines) { return buildDocuments(lines, DEFAULT_IMAGE_REP_NAME, DEFAULT_TEXT_REP_NAME, TextLevel.None, TextLocation.None, null); } /** * Builds a list of documents from an opticon file with no text representatives. * @param lines the lines read from an opt file split on a comma * @param imagesName the name of the image representative * @return returns a list of documents */ public List<Document> buildDocuments(List<String[]> lines, String imagesName) { return buildDocuments(lines, imagesName, DEFAULT_TEXT_REP_NAME, TextLevel.None, TextLocation.None, null); } /** * Builds a list of documents from an opticon file using the default image and text representative names * @param lines the lines read from an opt file split on a comma * @param textLevel the level of the text representative * @param textLocation the location of the text representative * @param textPathFindReplace a pair containing a pattern to find all image path specific * elements in the image path and the string to replace them with. The result of this * operation should be the transformation of the image path into the text path. * The file extension of the image file name will automatically be updated to '.txt'. * The base name of the image file and text file are expected to be identical. * @return returns a list of documents */ public List<Document> buildDocuments(List<String[]> lines, TextLevel textLevel, TextLocation textLocation, Pair<Pattern, String> textPathFindReplace) { return buildDocuments(lines, DEFAULT_IMAGE_REP_NAME, DEFAULT_TEXT_REP_NAME, textLevel, textLocation, textPathFindReplace); } /** * Builds a list of documents from an opticon file * @param lines the lines read from an opt file split on a comma * @param imagesName the name of images representative * @param textName the name of the text representative * @param textLevel the level of the text representative * @param textLocation the location of the text representative * @param textPathFindReplace a pair containing a pattern to find all image path specific * elements in the image path and the string to replace them with. The result of this * operation should be the transformation of the image path into the text path. * The file extension of the image file name will automatically be updated to '.txt'. * The base name of the image file and text file are expected to be identical. * @return returns a list of documents */ public List<Document> buildDocuments(List<String[]> lines, String imagesName, String textName, TextLevel textLevel, TextLocation textLocation, Pair<Pattern, String> textPathFindReplace) { // setup for building Map<String, Document> docs = new LinkedHashMap<>(); List<String[]> docPages = new ArrayList<>(); // build the documents for (String[] line : lines) { if (line[DOC_BREAK_INDEX].toUpperCase().equals(TRUE_VALUE)) { // send data to make a document if (docPages.size() > 0) { Document doc = buildDocument(docPages, imagesName, textName, textLevel, textLocation, textPathFindReplace); String key = doc.getMetadata().get(IMAGE_KEY_FIELD); docs.put(key, doc); } // clear docPages and add new first page docPages = new ArrayList<>(); docPages.add(line); } else { // add page to document pages docPages.add(line); } } // add last doc to the collection Document doc = buildDocument(docPages, imagesName, textName, textLevel, textLocation, textPathFindReplace); String key = doc.getMetadata().get(IMAGE_KEY_FIELD); docs.put(key, doc); return new ArrayList<>(docs.values()); } /** * Builds a single document using the default image representative name, which has no text representatie * @param docPages a list of opticon page records split on a comma * @return returns a single document */ public Document buildDocument(List<String[]> docPages) { return buildDocument(docPages, DEFAULT_IMAGE_REP_NAME, DEFAULT_TEXT_REP_NAME, TextLevel.None, TextLocation.None, null); } /** * Builds a single document, which has no text representative * @param docPages a list of opticon page records split on a comma * @param imagesName the name of the image representative * @return returns a single document */ public Document buildDocument(List<String[]> docPages, String imagesName) { return buildDocument(docPages, imagesName, DEFAULT_TEXT_REP_NAME, TextLevel.None, TextLocation.None, null); } /** * Builds a single document using the default image and text representative names * @param docPages a list of opticon page records split on a comma * @param textLevel the level of the text representative * @param textLocation the location of the text representative * @param textPathFileReplace a pair containing a pattern to find all image path specific * elements in the image path and the string to replace them with. The result of this * operation should be the transformation of the image path into the text path. * The file extension of the image file name will automatically be updated to '.txt'. * The base name of the image file and text file are expected to be identical. * @return returns a single document */ public Document buildDocument(List<String[]> docPages, TextLevel textLevel, TextLocation textLocation, Pair<Pattern, String> textPathFileReplace) { return buildDocument(docPages, DEFAULT_IMAGE_REP_NAME, DEFAULT_TEXT_REP_NAME, textLevel, textLocation, textPathFileReplace); } /** * Builds a single document * @param docPages a list of opticon page records split on a comma * @param imagesName the name of the images representative * @param textName the name of the text representative * @param textLevel the level of the text representative * @param textLocation the location of the text representative * @param textPathFindReplace a pair containing a pattern to find all image path specific * elements in the image path and the string to replace them with. The result of this * operation should be the transformation of the image path into the text path. * The file extension of the image file name will automatically be updated to '.txt'. * The base name of the image file and text file are expected to be identical. * @return returns a single document */ public Document buildDocument(List<String[]> docPages, String imagesName, String textName, TextLevel textLevel, TextLocation textLocation, Pair<Pattern, String> textPathFindReplace) { // setup for building Document doc = new Document(); // get document properties String[] pageOne = docPages.get(0); String key = pageOne[IMAGE_KEY_INDEX]; String vol = pageOne[VOLUME_NAME_INDEX]; String box = pageOne[BOX_BREAK_INDEX]; String dir = pageOne[FOLDER_BREAK_INDEX]; int pages = docPages.size(); // do we need to check the field value here? // set document properties doc.setKey(key); doc.addField(IMAGE_KEY_FIELD, key); doc.addField(VOLUME_NAME_FIELD, vol); doc.addField(PAGE_COUNT_FIELD, Integer.toString(pages)); doc.addField(BOX_BREAK_FIELD, box); doc.addField(FOLDER_BREAK_FIELD, dir); // get image representative Set<String> representativeFiles = new LinkedHashSet<>(); docPages.forEach(page -> representativeFiles.add(page[FULL_PATH_INDEX])); Representative imageRep = new Representative(); imageRep.setName(imagesName); imageRep.setType(Representative.Type.IMAGE); imageRep.setFiles(representativeFiles); // get text representative //List<String> textFiles = new ArrayList<>(); Set<String> textFiles = new LinkedHashSet<>(); // add textFiles switch (textLevel) { case None: // do nothing here break; case Page: docPages.forEach(page -> { String textFile = getTextFileFromPageInfo(page, textLocation, textPathFindReplace); textFiles.add(textFile); }); break; case Doc: String[] firstPageInfo = docPages.get(0); String textFile = getTextFileFromPageInfo(firstPageInfo, textLocation, textPathFindReplace); textFiles.add(textFile); break; default: // do nothing here break; } Representative textRep = new Representative(); textRep.setName(textName); textRep.setType(Representative.Type.TEXT); textRep.setFiles(textFiles); // set representatives Set<Representative> reps = new HashSet<>(); reps.add(imageRep); // if there are text files add the representative if (textFiles.size() > 0) { reps.add(textRep); } doc.setRepresentatives(reps); // return built doc return doc; } private String getTextFileFromPageInfo(String[] pageInfo, TextLocation textLocation, Pair<Pattern, String> textPathFindReplace) { String imagePath = pageInfo[FULL_PATH_INDEX]; String textFolder = FilenameUtils.getFullPath(imagePath); String textFile = FilenameUtils.getBaseName(imagePath) + TEXT_EXT; switch(textLocation) { case SameAsImages: // nothing to replace // do nothing here break; case AlternateLocation: Matcher m = textPathFindReplace.getLeft().matcher(textFolder); textFolder = m.replaceAll(textPathFindReplace.getRight()); break; default: // do nothing here break; } return Paths.get(textFolder, textFile).toString(); } }
package chaij; import java.util.*; /** * This utility class enables the usage of multiple exceptions in one unit test. */ public final class ExceptionReporter { private static final ThreadLocal<Boolean> USE_MULTIPLE = ThreadLocal.withInitial(() -> Boolean.FALSE); private static final ThreadLocal<List<UnmetExpectationException>> EXCEPTIONS = ThreadLocal.withInitial(LinkedList::new); /** * Man, you can't stop looking, can you? If you like it... */ private ExceptionReporter() {} /** * Enables the catching of multiple * {@link chaij.UnmetExpectationException UnmetExpectationExceptions}. * * <p> * If you call this method directly, it is <strong>vital</strong> * that you call {@link #resetAndVerify()} afterwards, or * this <strong>will be leaked into global state!</strong> */ public static void enableMultiple() { USE_MULTIPLE.set(Boolean.TRUE); } /** * Resets the multiplicity state and checks for any caught exceptions. * * <p> * If there was no exception, nothing will be thrown. * * <p> * If there was one {@link chaij.UnmetExpectationException}, this method rethrows it. * * <p> * If there were two or more exceptions, they will be wrapped * inside a {@link MultipleException} exception. */ public static void resetAndVerify() { USE_MULTIPLE.set(Boolean.FALSE); List<UnmetExpectationException> errors = new LinkedList<>(EXCEPTIONS.get()); EXCEPTIONS.remove(); if(!errors.isEmpty()) { if(errors.size() == 1) { throw errors.get(0); } else { throw new MultipleException(errors); } } } /** * Reports an unmet expectation, either caching or rethrowing the exception * based on the current multiplicity for the thread. * * @param e the unmet expectation exception */ public static void reportException(UnmetExpectationException e) { Objects.requireNonNull(e); if(USE_MULTIPLE.get()) { EXCEPTIONS.get().add(e); } else { throw e; } } /** * Collects multiple exceptions. */ public static final class MultipleException extends RuntimeException { private static final long serialVersionUID = -1212008157115633368L; private final Collection<? extends Throwable> errors; /** * Constructs a new exception. You probably shouldn't use this directly. * * @param errors the exceptions! */ public MultipleException(Collection<? extends Throwable> errors) { this.errors = new ArrayList<>(errors); } @Override public String getMessage() { StringBuilder sb = new StringBuilder(String.format("There were %d errors:", errors.size())); for(Throwable e : errors) { sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage())); } return sb.toString(); } } }
package edu.vu.isis.ammo.core; import java.util.HashMap; /** * Definitions for mime-type to mime-type-id mapping. * */ public class AmmoMimeTypes { public static final HashMap<Integer, String> mimeTypes; public static final HashMap<String, Integer> mimeIds; static { mimeTypes = new HashMap<Integer, String>(); mimeIds = new HashMap<String, Integer>(); mimeTypes.put( 1, "application/vnd.edu.vu.isis.ammo.sms.message" ); mimeIds.put( "application/vnd.edu.vu.isis.ammo.sms.message", 1 ); mimeTypes.put( 2, "application/vnd.com.aterrasys.nevada.locations" ); mimeIds.put( "application/vnd.com.aterrasys.nevada.locations", 2 ); } }
package com.qiniu.http; import com.qiniu.common.QiniuException; import com.qiniu.util.Json; import com.qiniu.util.StringMap; import com.qiniu.util.StringUtils; import okhttp3.MediaType; import java.io.IOException; import java.io.InputStream; import java.util.Locale; /** * HTTP */ public final class Response { public static final int InvalidArgument = -4; public static final int InvalidFile = -3; public static final int Cancelled = -2; public static final int NetworkError = -1; public final int statusCode; public final String reqId; public final String xlog; /** * cdn */ public final String xvia; public final String error; public final double duration; public final String address; private byte[] body; private okhttp3.Response response; private Response(okhttp3.Response response, int statusCode, String reqId, String xlog, String xvia, String address, double duration, String error, byte[] body) { this.response = response; this.statusCode = statusCode; this.reqId = reqId; this.xlog = xlog; this.xvia = xvia; this.duration = duration; this.error = error; this.address = address; this.body = body; } public static Response create(okhttp3.Response response, String address, double duration) { String error = null; int code = response.code(); String reqId = null; reqId = response.header("X-Reqid"); reqId = (reqId == null) ? null : reqId.trim(); byte[] body = null; if (ctype(response).equals(Client.JsonMime)) { try { body = response.body().bytes(); if (response.code() >= 400 && !StringUtils.isNullOrEmpty(reqId) && body != null) { ErrorBody errorBody = Json.decode(new String(body), ErrorBody.class); error = errorBody.error; } } catch (Exception e) { if (response.code() < 300) { error = e.getMessage(); } } } return new Response(response, code, reqId, response.header("X-Log"), via(response), address, duration, error, body); } public static Response createError(okhttp3.Response response, String address, double duration, String error) { if (response == null) { return new Response(null, -1, "", "", "", "", duration, error, null); } int code = response.code(); String reqId = null; reqId = response.header("X-Reqid"); reqId = (reqId == null) ? null : reqId.trim(); byte[] body = null; if (ctype(response).equals(Client.JsonMime)) { try { body = response.body().bytes(); if (response.code() >= 400 && !StringUtils.isNullOrEmpty(reqId) && body != null) { ErrorBody errorBody = Json.decode(new String(body), ErrorBody.class); error = errorBody.error; } } catch (Exception e) { if (response.code() < 300) { error = e.getMessage(); } } } return new Response(response, code, reqId, response.header("X-Log"), via(response), address, duration, error, body); } private static String via(okhttp3.Response response) { String via; if (!(via = response.header("X-Via", "")).equals("")) { return via; } if (!(via = response.header("X-Px", "")).equals("")) { return via; } if (!(via = response.header("Fw-Via", "")).equals("")) { return via; } return via; } private static String ctype(okhttp3.Response response) { MediaType mediaType = response.body().contentType(); if (mediaType == null) { return ""; } return mediaType.type() + "/" + mediaType.subtype(); } public boolean isOK() { return statusCode == 200 && error == null && reqId != null && reqId.length() > 0; } public boolean isNetworkBroken() { return statusCode == NetworkError; } public boolean isServerError() { return (statusCode >= 500 && statusCode < 600 && statusCode != 579) || statusCode == 996; } public boolean needSwitchServer() { return isNetworkBroken() || (statusCode >= 500 && statusCode < 600 && statusCode != 579); } public boolean needRetry() { return isNetworkBroken() || isServerError() || statusCode == 406 || (statusCode == 200 && error != null); } public String toString() { return String.format(Locale.ENGLISH, "{ResponseInfo:%s,status:%d, reqId:%s, xlog:%s, xvia:%s, adress:%s, duration:%f s, error:%s}", super.toString(), statusCode, reqId, xlog, xvia, address, duration, error); } public <T> T jsonToObject(Class<T> classOfT) throws QiniuException { if (!isJson()) { return null; } String b = bodyString(); return Json.decode(b, classOfT); } public StringMap jsonToMap() throws QiniuException { if (!isJson()) { return null; } String b = bodyString(); return Json.decode(b); } public synchronized byte[] body() throws QiniuException { if (body != null) { return body; } try { this.body = response.body().bytes(); } catch (IOException e) { throw new QiniuException(e); } return body; } public String bodyString() throws QiniuException { return StringUtils.utf8String(body()); } public synchronized InputStream bodyStream() throws QiniuException { if (this.response == null) { return null; } return this.response.body().byteStream(); } public String contentType() { return ctype(response); } public boolean isJson() { return contentType().equals(Client.JsonMime); } public String url() { return response.request().url().toString(); } public static class ErrorBody { public String error; } public String getInfo() { String[] msg = new String[3]; try { msg[0] = url(); } catch (Throwable t) { } try { msg[1] = toString(); } catch (Throwable t) { } try { msg[2] = bodyString(); } catch (Throwable t) { } return StringUtils.join(msg, " \n"); } }
package org.pentaho.di.core.gui; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.Rectangle; import org.pentaho.di.core.gui.ScrollBarInterface; import org.pentaho.di.core.gui.AreaOwner.AreaType; import org.pentaho.di.core.gui.GCInterface.EColor; import org.pentaho.di.core.gui.GCInterface.EImage; import org.pentaho.di.core.gui.GCInterface.ELineStyle; import org.pentaho.di.trans.step.errorhandling.StreamIcon; public class BasePainter { public final double theta = Math.toRadians(11); // arrowhead sharpness protected static final int MINI_ICON_SIZE = 16; protected static final int MINI_ICON_MARGIN = 5; protected static final int MINI_ICON_TRIANGLE_BASE = 10; protected static final int MINI_ICON_DISTANCE = 7; protected static final int MINI_ICON_SKEW = 0; protected Point area; protected ScrollBarInterface hori, vert; protected List<AreaOwner> areaOwners; protected Point offset; protected Point drop_candidate; protected int iconsize; protected int gridSize; protected Rectangle selrect; protected int linewidth; protected float magnification; protected float translationX; protected float translationY; protected boolean shadow; protected Object subject; protected GCInterface gc; protected int shadowSize; private String noteFontName; private int noteFontHeight; public BasePainter(GCInterface gc, Object subject, Point area, ScrollBarInterface hori, ScrollBarInterface vert, Point drop_candidate, Rectangle selrect, List<AreaOwner> areaOwners, int iconsize, int linewidth, int gridsize, int shadowSize, boolean antiAliasing, String noteFontName, int noteFontHeight ) { this.gc = gc; this.subject = subject; this.area = area; this.hori = hori; this.vert = vert; this.selrect = selrect; this.drop_candidate = drop_candidate; this.areaOwners = areaOwners; areaOwners.clear(); // clear it before we start filling it up again. // props = PropsUI.getInstance(); this.iconsize = iconsize; this.linewidth = linewidth; this.gridSize = gridsize; this.shadowSize = shadowSize; this.shadow = shadowSize>0; this.magnification = 1.0f; gc.setAntialias(antiAliasing); this.noteFontName = noteFontName; this.noteFontHeight = noteFontHeight; } public static EImage getStreamIconImage(StreamIcon streamIcon) { switch(streamIcon) { case TRUE : return EImage.TRUE; case FALSE : return EImage.FALSE; case ERROR : return EImage.ERROR; case INFO : return EImage.INFO; case TARGET : return EImage.TARGET; case INPUT : return EImage.INPUT; case OUTPUT : return EImage.OUTPUT; default: return EImage.ARROW; } } protected void drawNote(NotePadMeta notePadMeta) { if (notePadMeta.isSelected()) { gc.setLineWidth(2); } else { gc.setLineWidth(1); } Point ext; if (Const.isEmpty(notePadMeta.getNote())) { ext = new Point(10,10); // Empty note } else { gc.setFont(Const.NVL(notePadMeta.getFontName(),noteFontName), notePadMeta.getFontSize()==-1 ? noteFontHeight : notePadMeta.getFontSize(), notePadMeta.isFontBold(), notePadMeta.isFontItalic() ); ext = gc.textExtent(notePadMeta.getNote()); } Point p = new Point(ext.x, ext.y); Point loc = notePadMeta.getLocation(); Point note = real2screen(loc.x, loc.y); int margin = Const.NOTE_MARGIN; p.x += 2 * margin; p.y += 2 * margin; int width = notePadMeta.width; int height = notePadMeta.height; if (p.x > width) width = p.x; if (p.y > height) height = p.y; int noteshape[] = new int[] { note.x, note.y, // Top left note.x + width + 2 * margin, note.y, // Top right note.x + width + 2 * margin, note.y + height, // bottom right 1 note.x + width, note.y + height + 2 * margin, // bottom right 2 note.x + width, note.y + height, // bottom right 3 note.x + width + 2 * margin, note.y + height, // bottom right 1 note.x + width, note.y + height + 2 * margin, // bottom right 2 note.x, note.y + height + 2 * margin // bottom left }; // Draw shadow around note? if(notePadMeta.isDrawShadow()) { int s = shadowSize; int shadowa[] = new int[] { note.x+s, note.y+s, // Top left note.x + width + 2 * margin+s, note.y+s, // Top right note.x + width + 2 * margin+s, note.y + height+s, // bottom right 1 note.x + width+s, note.y + height + 2 * margin+s, // bottom right 2 note.x+s, note.y + height + 2 * margin+s // bottom left }; gc.setBackground(EColor.LIGHTGRAY); gc.fillPolygon(shadowa); } gc.setBackground(notePadMeta.getBackGroundColorRed(), notePadMeta.getBackGroundColorGreen(), notePadMeta.getBackGroundColorBlue()); gc.setForeground(notePadMeta.getBorderColorRed(), notePadMeta.getBorderColorGreen(), notePadMeta.getBorderColorBlue()); gc.fillPolygon(noteshape); gc.drawPolygon(noteshape); if (!Const.isEmpty(notePadMeta.getNote())) { gc.setForeground(notePadMeta.getFontColorRed(),notePadMeta.getFontColorGreen(),notePadMeta.getFontColorBlue()); gc.drawText(notePadMeta.getNote(), note.x + margin, note.y + margin, true); } notePadMeta.width = width; // Save for the "mouse" later on... notePadMeta.height = height; if (notePadMeta.isSelected()) gc.setLineWidth(1); else gc.setLineWidth(2); // Add to the list of areas... if (!shadow) { areaOwners.add(new AreaOwner(AreaType.NOTE, note.x, note.y, width, height, offset, subject, notePadMeta)); } } protected Point real2screen(int x, int y) { Point screen = new Point( x + offset.x, y + offset.y ); return screen; } protected Point getThumb(Point area, Point transMax) { Point resizedMax = magnifyPoint(transMax); Point thumb = new Point(0, 0); if (resizedMax.x <= area.x) thumb.x = 100; else thumb.x = (int) Math.floor( 100d * area.x / resizedMax.x ); if (resizedMax.y <= area.y) thumb.y = 100; else thumb.y = (int) Math.floor( 100d * area.y / resizedMax.y ); return thumb; } protected Point magnifyPoint(Point p) { return new Point(Math.round(p.x * magnification), Math.round(p.y*magnification)); } protected Point getOffset(Point thumb, Point area) { Point p = new Point(0, 0); if (hori==null || vert==null) return p; Point sel = new Point(hori.getSelection(), vert.getSelection()); if (thumb.x == 0 || thumb.y == 0) return p; p.x = Math.round(-sel.x * area.x / thumb.x / magnification); p.y = Math.round(-sel.y * area.y / thumb.y / magnification); return p; } protected void drawRect(Rectangle rect) { if (rect == null) return; gc.setLineStyle(ELineStyle.DASHDOT); gc.setLineWidth(linewidth); gc.setForeground(EColor.GRAY); // PDI-2619: SWT on Windows doesn't cater for negative rect.width/height so handle here. Point s = real2screen(rect.x, rect.y); if (rect.width < 0) { s.x = s.x + rect.width; } if (rect.height < 0) { s.y = s.y + rect.height; } gc.drawRectangle(s.x, s.y, Math.abs(rect.width), Math.abs(rect.height)); gc.setLineStyle(ELineStyle.SOLID); } protected void drawGrid() { Point bounds = gc.getDeviceBounds(); for (int x=0;x<bounds.x;x+=gridSize) { for (int y=0;y<bounds.y;y+=gridSize) { gc.drawPoint(x+(offset.x%gridSize),y+(offset.y%gridSize)); } } } protected int calcArrowLength() { return 19 + (linewidth - 1) * 5; // arrowhead length; } /** * @return the magnification */ public float getMagnification() { return magnification; } /** * @param magnification the magnification to set */ public void setMagnification(float magnification) { this.magnification = magnification; } }
package de.dwslab.risk.gui; import java.awt.Color; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.NumberFormat; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.collect.HashMultimap; import com.mxgraph.layout.hierarchical.mxHierarchicalLayout; import com.mxgraph.model.mxCell; import com.mxgraph.swing.util.mxSwingConstants; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxEvent; import com.mxgraph.util.mxResources; import com.mxgraph.view.mxGraph; import de.dwslab.ai.util.Utils; import de.dwslab.risk.gui.jgraphx.BasicGraphEditor; import de.dwslab.risk.gui.jgraphx.EditorMenuBar; import de.dwslab.risk.gui.jgraphx.EditorPalette; import de.dwslab.risk.gui.model.BackgroundKnowledge; import de.dwslab.risk.gui.model.Entity; import de.dwslab.risk.gui.model.Grounding; import de.dwslab.risk.gui.model.GuiBackgroundKnowledge; import de.dwslab.risk.gui.model.MlnBackgroundKnowledge; import de.dwslab.risk.gui.model.Predicate; import de.dwslab.risk.gui.model.Type; public class RoCA extends BasicGraphEditor { private static final long serialVersionUID = -4601740824088314699L; private static final Logger logger = LogManager.getLogger(); private BackgroundKnowledge knowledge; /** * Holds the shared number formatter. * * @see NumberFormat#getInstance() */ public static final NumberFormat numberFormat = NumberFormat.getInstance(); public RoCA() throws IOException { super("RoCA", new CustomGraphComponent(new CustomGraph())); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { JOptionPane.showMessageDialog(RoCA.this, e.getMessage()); logger.error("Unhandeled exception", e); }); Path dummy = Utils.createTempPath("dummy", ".db"); knowledge = new MlnBackgroundKnowledge(RoCA.class.getResource("/default.mln"), dummy); Files.delete(dummy); final mxGraph graph = graphComponent.getGraph(); graph.addListener( mxEvent.CELLS_ADDED, (sender, event) -> { Object[] cells = (Object[]) event.getProperties().get("cells"); for (Object obj : cells) { mxCell cell = (mxCell) obj; if (cell.isVertex()) { Entity entity = (Entity) cell.getValue(); cell.setValue(new Entity(entity.getName(), entity.getType())); } else { Entity source = (Entity) cell.getSource().getValue(); Entity target = (Entity) cell.getTarget().getValue(); String sourceName = source.getType().getName(); String targetName = target.getType().getName(); if (targetName.equals("risk") && sourceName.equals("infra")) { Grounding grounding = new Grounding(new Predicate("hasRiskDegree"), Arrays.asList(source.getName(), target.getName(), String.valueOf(0d))); cell.setValue(grounding); } else if (targetName.equals("infra") && sourceName.equals("infra")) { Grounding grounding = new Grounding(new Predicate("dependsOn"), Arrays.asList(source.getName(), target.getName())); cell.setValue(grounding); } else { event.consume(); graph.removeCells(new Object[] { cell }); JOptionPane.showMessageDialog( SwingUtilities.getWindowAncestor(graphComponent), "Relation wird nicht unterstützt: " + source + " + target); } } } }); // Creates the shapes palette EditorPalette shapesPalette = insertPalette(mxResources.get("shapes")); // Adds some template cells for dropping into the graph shapesPalette.addTemplate("Component", new ImageIcon(RoCA.class .getResource("/com/mxgraph/examples/swing/images/rectangle.png")), null, 160, 120, new Entity("New Component", new Type("infra"))); // shapesPalette.addTemplate("Service", // new ImageIcon(RoCA.class // .getResource("/com/mxgraph/examples/swing/images/rounded.png")), // "rounded=1", 160, 120, new Entity("", new Type("infra"))); shapesPalette.addTemplate("Risk", new ImageIcon(RoCA.class .getResource("/com/mxgraph/examples/swing/images/ellipse.png")), "ellipse", 160, 120, new Entity("New Risk", new Type("risk"))); } public BackgroundKnowledge getBackgroundKnowledge() { return new GuiBackgroundKnowledge(graphComponent.getGraph(), knowledge); } public void handleKnowledgeUpdate(BackgroundKnowledge knowledge) { logger.debug("Updating background knowledge"); this.knowledge = knowledge; mxGraph graph = graphComponent.getGraph(); try { graph.setEventsEnabled(false); graph.getModel().beginUpdate(); // clear the current graph graph.selectAll(); graph.removeCells(); // add the new entities Map<String, mxCell> cellMap = new HashMap<>(); Set<Entity> infras = knowledge.getEntities().get(new Type("infra")); for (Entity infra : infras) { mxCell cell = insertEntity(infra, graph); cellMap.put(infra.getName(), cell); } // add the risks Set<Entity> risks = knowledge.getEntities().get(new Type("risk")); for (Entity risk : risks) { mxCell cell = insertRisk(risk, graph); cellMap.put(risk.getName(), cell); } HashMultimap<Predicate, Grounding> groundings = knowledge.getGroundings(); // connect the entities with edges Set<Grounding> dependsOns = groundings.get(new Predicate("dependsOn")); for (Grounding literal : dependsOns) { String source = literal.getValues().get(0); String target = literal.getValues().get(1); insertDependsOn(literal, cellMap.get(source), cellMap.get(target), graph); } Set<Grounding> hasRisks = groundings.get(new Predicate("hasRiskDegree")); for (Grounding literal : hasRisks) { String source = literal.getValues().get(0); String target = literal.getValues().get(1); insertHasRisk(literal, cellMap.get(source), cellMap.get(target), graph); } Set<Grounding> offlines = groundings.get(new Predicate("offline")); for (Grounding literal : offlines) { String infra = literal.getValues().get(0); mxCell cell = cellMap.get(infra); Entity value = (Entity) cell.getValue(); knowledge.getEntities().remove(value.getType(), cell.getValue()); value.setOffline(Boolean.TRUE); knowledge.getEntities().put(value.getType(), ((Entity) cell.getValue())); graph.getModel().setStyle(cell, "fillColor=#FF2222"); } Set<Grounding> notOfflines = groundings.get(new Predicate(true, "offline")); for (Grounding literal : notOfflines) { String infra = literal.getValues().get(0); mxCell cell = cellMap.get(infra); Entity value = (Entity) cell.getValue(); knowledge.getEntities().remove(value.getType(), cell.getValue()); value.setOffline(Boolean.FALSE); knowledge.getEntities().put(value.getType(), ((Entity) cell.getValue())); graph.getModel().setStyle(cell, "fillColor=#22FF22"); } } finally { graph.setEventsEnabled(true); graph.getModel().endUpdate(); } logger.info("Executing layout"); mxHierarchicalLayout layout = new mxHierarchicalLayout(graph); try { graph.getModel().beginUpdate(); layout.execute(graph.getDefaultParent()); } finally { graph.getModel().endUpdate(); graph.repaint(); } } private mxCell insertEntity(Entity entity, mxGraph graph) { Object parent = graph.getDefaultParent(); int x = 100; int y = 100; int width = 160; int height = 120; return (mxCell) graph.insertVertex(parent, entity.getName(), entity, x, y, width, height); } private mxCell insertRisk(Entity risk, mxGraph graph) { Object parent = graph.getDefaultParent(); int x = 100; int y = 100; int width = 160; int height = 120; return (mxCell) graph.insertVertex(parent, risk.getName(), risk, x, y, width, height, "rounded=1"); } private mxCell insertDependsOn(Grounding grounding, mxCell source, mxCell target, mxGraph graph) { Object parent = graph.getDefaultParent(); String id = "dependsOn(" + source.getValue() + "," + target.getValue() + ")"; return (mxCell) graph.insertEdge(parent, id, grounding, source, target); } private mxCell insertHasRisk(Grounding grounding, mxCell source, mxCell target, mxGraph graph) { Object parent = graph.getDefaultParent(); String id = "hasRiskDegree(" + source.getValue() + "," + target.getValue() + ")"; return (mxCell) graph.insertEdge(parent, id, grounding, source, target); } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { e1.printStackTrace(); } mxSwingConstants.SHADOW_COLOR = Color.LIGHT_GRAY; mxConstants.W3C_SHADOWCOLOR = "#D3D3D3"; RoCA editor = new RoCA(); editor.createFrame(new EditorMenuBar(editor)).setVisible(true); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // FILE NAME: Kilroy.java (Team 339 - Kilroy) // ABSTRACT: // This file is where almost all code for Kilroy will be // written. All of these functions are functions that should // override methods in the base class (IterativeRobot). The // functions are as follows: // autonomousInit() - Initialization code for autonomous mode // should go here. Will be called each time the robot enters // autonomous mode. // disabledInit() - Initialization code for disabled mode should // go here. This function will be called one time when the // robot first enters disabled mode. // robotInit() - Robot-wide initialization code should go here. // It will be called exactly 1 time. // teleopInit() - Initialization code for teleop mode should go here. // Will be called each time the robot enters teleop mode. // autonomousPeriodic() - Periodic code for autonomous mode should // go here. Will be called periodically at a regular rate while // the robot is in autonomous mode. // disabledPeriodic() - Periodic code for disabled mode should go here. // Will be called periodically at a regular rate while the robot // is in disabled mode. // teleopPeriodic() - Periodic code for teleop mode should go here. // Will be called periodically at a regular rate while the robot // is in teleop mode. // autonomousContinuous() - Continuous code for autonomous mode should // go here. Will be called repeatedly as frequently as possible // while the robot is in autonomous mode. // disabledContinuous() - Continuous code for disabled mode should go // here. Will be called repeatedly as frequently as possible while // the robot is in disabled mode. // teleopContinuous() - Continuous code for teleop mode should go here. // Will be called repeatedly as frequently as possible while the // robot is in teleop mode. // Other functions not normally used // startCompetition() - This function is a replacement for the WPI // supplied 'main loop'. This should not normally be written or // used. // Team 339. package org.usfirst.frc.team339.robot; import org.usfirst.frc.team339.Hardware.Hardware; import org.usfirst.frc.team339.HardwareInterfaces.DoubleSolenoid; import org.usfirst.frc.team339.HardwareInterfaces.transmission.Transmission_old.debugStateValues; import org.usfirst.frc.team339.Utils.ImageProcessing.ObjectRemoval; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.Relay.Direction; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { // private data for the class @Override public void autonomousInit () { // start setup - tell the user we are beginning // setup System.out.println("Started AutonousInit()."); // Call the Autonomous class's Init function, // which contains the user code. Autonomous.init(); // done setup - tell the user we are complete // setup System.out.println("Completed AutonousInit()."); } // end autonomousInit @Override public void autonomousPeriodic () { // Call the Autonomous class's Periodic function, // which contains the user code. Autonomous.periodic(); // feed all motor safeties Hardware.leftRearMotorSafety.feed(); Hardware.rightRearMotorSafety.feed(); Hardware.leftFrontMotorSafety.feed(); Hardware.rightFrontMotorSafety.feed(); } // end autonomousPeriodic @Override public void disabledInit () { // start setup - tell the user we are beginning // setup System.out.println("Started DisabledInit()."); // User code goes below here try { //check the Autonomous ENABLED/DISABLED switch. Autonomous.autonomousEnabled = Hardware.autonomousEnabled.isOn(); // set the delay time based on potentiometer. Autonomous.delay = Autonomous.initDelayTime(); // get the lane based off of startingPositionPotentiometer Autonomous.lane = Autonomous.getLane(); Autonomous.debug = Autonomous.DEBUGGING_DEFAULT; Hardware.transmission .setDebugState(debugStateValues.DEBUG_NONE); Autonomous.initAutoState(); // Hardware.drive.setMaxSpeed(MAXIMUM_AUTONOMOUS_SPEED); // motor initialization Hardware.transmission.setFirstGearPercentage(1.0); Hardware.transmission.setGear(1); Hardware.transmission.setJoysticksAreReversed(true); Hardware.transmission.setJoystickDeadbandRange(0.0); // Encoder Initialization Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); // Sets Resolution of camera Hardware.ringLightRelay.set(Relay.Value.kOff); Hardware.axisCamera .writeBrightness( Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS); // turn the timer off and reset the counter // so that we can use it in autonomous Hardware.kilroyTimer.stop(); Hardware.kilroyTimer.reset(); Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); Hardware.leftFrontMotor.set(0.0); Hardware.leftRearMotor.set(0.0); Hardware.rightFrontMotor.set(0.0); Hardware.rightRearMotor.set(0.0); Hardware.armMotor.set(0.0); Hardware.armIntakeMotor.set(0.0); Hardware.catapultSolenoid0.set(false); Hardware.catapultSolenoid1.set(false); Hardware.catapultSolenoid2.set(false); } catch (Exception e) { System.out.println("Disabled init died"); } // User code goes above here // done setup - tell the user we are complete // setup System.out.println("Completed DisabledInit()."); } // end disabledInit @Override public void disabledPeriodic () { // Watch dog code used to go here. // User code goes below here // User code goes above here } // end disabledPeriodic @Override public void robotInit () { // Watch dog code used to go here. // User code goes below here // Encoder Initialization if (Hardware.runningInLab == true) { // for old Kilroy 16 // Hardware.leftRearEncoder.setDistancePerPulse(.0197); // Hardware.rightRearEncoder.setDistancePerPulse(.0197); Hardware.leftRearEncoder.setDistancePerPulse( this.distancePerTickForMotorEncoders); Hardware.rightRearEncoder.setDistancePerPulse( this.distancePerTickForMotorEncoders); Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); } else { // Kilroy 17 Hardware.leftRearEncoder.setDistancePerPulse( this.distancePerTickForMotorEncoders); Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.setDistancePerPulse( this.distancePerTickForMotorEncoders); Hardware.rightRearEncoder.reset(); Hardware.rightRearEncoder.setReverseDirection(true); } // initialize all things with the drive system Hardware.transmission.setMaxGear(2); Hardware.transmission.setJoystickDeadbandRange( JOYSTICK_DEADBAND_ZONE); Hardware.transmission .setFirstGearPercentage(FIRST_GEAR_PERCENTAGE); Hardware.transmission.setSecondGearPercentage( SECOND_GEAR_PERCENTAGE); // denote which motors are wired backwards // from what we want - setup based on whether // or not we are in the lab if (Hardware.runningInLab == true) { Hardware.rightFrontMotor.setInverted(true); Hardware.rightRearMotor.setInverted(false); Hardware.leftFrontMotor.setInverted(true); Hardware.leftRearMotor.setInverted(true); Hardware.axisCamera.setHaveCamera(false); } else { Hardware.rightFrontMotor.setInverted(true); Hardware.rightRearMotor.setInverted(false); Hardware.leftFrontMotor.setInverted(true); Hardware.leftRearMotor.setInverted(true); } Hardware.armMotor.setInverted(false); Hardware.armIntakeMotor.setInverted(false); // AXIS camera initialization // Set the axis camera brightness to dark // Hardware.axisCamera.writeBrightness( // Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS); Hardware.axisCamera.writeBrightness( Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS); // USB camera initialization // Settings for the USB Camera //TODO readd // Hardware.cam0.setBrightness(50); // Hardware.cam0.setExposureAuto(); // Hardware.cam0.setSize(160, 120); // Hardware.cam0.setFPS(20); // Hardware.cam0.setWhiteBalanceAuto(); // Hardware.cam0.setWhiteBalanceHoldCurrent(); // Hardware.cam0.updateSettings(); // Sets FPS and Resolution of camera Hardware.axisCamera.writeMaxFPS(Hardware.AXIS_FPS); Hardware.axisCamera.writeResolution(Hardware.AXIS_RESOLUTION); // Hardware.axisCamera // .writeWhiteBalance(AxisCamera.WhiteBalance.kHold); switch (Hardware.axisCamera.getResolution()) { case k640x480: Hardware.drive.setXResolution(640.0); Hardware.drive.setYResolution(480.0); break; case k480x360: Hardware.drive.setXResolution(480.0); Hardware.drive.setYResolution(360.0); break; case k320x240: Hardware.drive.setXResolution(320.0); Hardware.drive.setYResolution(240.0); break; case k240x180: Hardware.drive.setXResolution(240.0); Hardware.drive.setYResolution(180.0); break; case k176x144: Hardware.drive.setXResolution(176.0); Hardware.drive.setYResolution(144.0); break; default: case k160x120: Hardware.drive.setXResolution(160.0); Hardware.drive.setYResolution(120.0); break; } // Starts streaming video //TODO add back in //Hardware.cameraServer.startAutomaticCapture(Hardware.cam0);//AHK @cameratesting // Sets the hue, saturation, and luminance values for the vision // processing. //Hardware.imageProcessor.setHSLValues(0, 255, 0, 75, 5, 141); //Hardware.imageProcessor.setHSLValues(0, 115, 0, 69, 17, 44); Hardware.imageProcessor.setHSLValues(73, 132, 110, 255, 9, 47); // Has us remove small objects at the intensity of 5. May have to // change those values. // Hardware.imageProcessor.setObjectRemoval(ObjectRemoval.BORDER); Hardware.imageProcessor.setObjectRemoval(ObjectRemoval.SMALL, 3); // Has us convex hull our image so that the goal becomes a rectangle. Hardware.imageProcessor.setUseConvexHull(true); // we could also crop the image to only include blobs in our // good height range, which removes the possibility of // convex hull connecting the two totes when we carry more than one // info on cropping image here: // Removed criteria that drops blobs outside the center that was in // this general area, we need to keep them so we can tell where it is // on the screen if it isn't in the center // Tells the relay which way is on (kBackward is unable to be used) Hardware.ringLightRelay.setDirection(Direction.kForward); // motor initialization Hardware.leftRearMotorSafety.setSafetyEnabled(false); Hardware.rightRearMotorSafety.setSafetyEnabled(false); Hardware.leftFrontMotorSafety.setSafetyEnabled(false); Hardware.rightFrontMotorSafety.setSafetyEnabled(false); Hardware.leftRearMotorSafety.setExpiration(.25); Hardware.rightRearMotorSafety.setExpiration(.25); Hardware.leftFrontMotorSafety.setExpiration(.25); Hardware.rightFrontMotorSafety.setExpiration(.25); // Compressor Initialization Hardware.compressor.setClosedLoopControl(true); // Solenoid Initialization // initializes the solenoids...duh duh duh... Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward); Hardware.catapultSolenoid0.set(false); Hardware.catapultSolenoid1.set(false); Hardware.catapultSolenoid2.set(false); if (Hardware.runningInLab == true) { Autonomous.labScalingFactor = 0.25; } else { Autonomous.labScalingFactor = 1.0; } // User code goes above here // done setup - tell the user we are complete // setup System.out.println( "Kilroy XVII is started. All hardware items created."); System.out.println(); System.out.println(); } // end robotInit @Override public void teleopInit () { // start setup - tell the user we are beginning // setup System.out.println("Started teleopInit()."); // Call the Teleop class's Init function, // which contains the user code. Teleop.init(); // done setup - tell the user we are complete // setup System.out.println("Completed TeleopInit()."); } // end teleopInit @Override public void teleopPeriodic () { // Watch dog code used to go here. // Call the Teleop class's Periodic function, // which contains the user code. Teleop.periodic(); // feed all motor safeties Hardware.leftRearMotorSafety.feed(); Hardware.rightRearMotorSafety.feed(); Hardware.leftFrontMotorSafety.feed(); Hardware.rightFrontMotorSafety.feed(); } // end teleopPeriodic @Override public void testInit () { // User code goes below here // User code goes above here } // end testInit @Override public void testPeriodic () { // User code goes below here System.out .println(Hardware.ultrasonic.getRefinedDistanceValue()); // User code goes above here } // end testPeriodic // TUNEABLES //The inches/tics ratio private final double distancePerTickForMotorEncoders = 0.0745033113; // was 0.0745614 public static final double JOYSTICK_DEADBAND_ZONE = 0.20; public static final double FIRST_GEAR_PERCENTAGE = 0.5; public static final double SECOND_GEAR_PERCENTAGE = 1.0;//previously 0.7;//.85 } // end class
package estivate; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import estivate.annotations.Select; import estivate.core.ast.EstivateAST; import estivate.core.ast.parser.EstivateParser; import estivate.core.eval.EstivateEvaluator; import estivate.core.eval.EstivateEvaluator.EvalContext; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * <ul> * <li>parse members and call registered implementation</li> * <li>use dialect JSoup by default</li> * <li>get members ordered to evaluate</li> * <li>evaluate select elements</li> * <li>evaluate reduce value</li> * <li>converts value</li> * <li>sets value to target</li> * </ul> * * @author Benoit Theunissen * */ @Slf4j public class EstivateMapper { @Getter @Setter protected String encoding = "UTF-8"; @Getter @Setter protected String baseURI = "/"; protected static final String PACKAGE_NAME = Select.class.getPackage().getName(); protected static final List<Class<?>> STANDARD_TARGET_TYPES = new ArrayList<Class<?>>(); static { STANDARD_TARGET_TYPES.add(Document.class); STANDARD_TARGET_TYPES.add(Elements.class); STANDARD_TARGET_TYPES.add(Element.class); } public <T> T map(InputStream stream, Class<T> clazz) throws IOException { Document doc = parseStream(stream); log.debug("{}", doc.toString()); return this.map(doc, clazz); } public <T> List<T> mapToList(InputStream stream, Class<T> clazz) throws IOException { Document doc = parseStream(stream); log.debug("{}", doc.toString()); return this.mapToList(doc, clazz); } public Object map(InputStream stream, Type type) throws IOException { Document doc = parseStream(stream); log.debug("{}", doc.toString()); return map(doc, type); } private Document parseStream(InputStream stream) throws IOException { return Jsoup.parse(stream, this.encoding, this.baseURI); } @SuppressWarnings("unchecked") public <T> T map(Document document, Class<T> clazz) { EstivateAST ast = EstivateParser.parse(clazz); EvalContext context = EstivateEvaluator.buildEvalContext(document, new Elements(document), ast); return (T) EstivateEvaluator.eval(context, ast); } @SuppressWarnings("unchecked") public <T> List<T> mapToList(Document document, Class<T> clazz) { EstivateAST ast = EstivateParser.parse(clazz); EvalContext context = EstivateEvaluator.buildEvalContext(document, new Elements(document), ast); return (List<T>) EstivateEvaluator.evalToList(context, ast); } public Object map(Document document, Type type) throws IOException { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; // Handle type parameter class Class<?> classArgument = (Class<?>) parameterizedType.getActualTypeArguments()[0]; // Handle type class Class<?> rowClass = (Class<?>) parameterizedType.getRawType(); if (Collection.class.isAssignableFrom(rowClass)) { log.debug(rowClass.getCanonicalName() + " is a Collection type"); return this.mapToList(document, classArgument); } else { log.error(rowClass.getCanonicalName() + " is not a Collection type"); throw new IllegalArgumentException("Parameterized type not handled: " + rowClass.getCanonicalName()); } } else { return this.map(document, (Class<?>) type); } } }
package org.exist.dom; import org.exist.storage.ElementValue; import org.exist.util.XMLChar; import org.exist.xquery.Constants; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; /** * Represents a QName, consisting of a local name, a namespace URI and a prefix. * * @author Wolfgang <wolfgang@exist-db.org> */ public class QName implements Comparable { public final static QName DOCUMENT_QNAME = new QName("#document", "", null); public final static QName TEXT_QNAME = new QName("#text", "", null); public final static QName COMMENT_QNAME = new QName("#comment", "", null); public final static QName DOCTYPE_QNAME = new QName("#doctype", "", null); public final static QName EMPTY_QNAME = new QName("", "", null); private String localName_ = null; private String namespaceURI_ = null; private String prefix_ = null; private byte nameType_ = ElementValue.ELEMENT; /** * Construct a QName. The prefix might be null for the default namespace or if no prefix * has been defined for the QName. The namespace URI should be set to the empty * string, if no namespace URI is defined. * * @param localName * @param namespaceURI * @param prefix */ public QName(String localName, String namespaceURI, String prefix) { localName_ = localName; if(namespaceURI == null) namespaceURI_ = ""; else namespaceURI_ = namespaceURI; prefix_ = prefix; } public QName(String localName, String namespaceURI) { this(localName, namespaceURI, null); } public QName(QName other) { this(other.localName_, other.namespaceURI_, other.prefix_); nameType_ = other.nameType_; } public String getLocalName() { return localName_; } public void setLocalName(String name) { localName_ = name; } public String getNamespaceURI() { return namespaceURI_; } public void setNamespaceURI(String namespaceURI) { namespaceURI_ = namespaceURI; } /** * Returns true if the QName defines a namespace URI. * * @return */ public boolean needsNamespaceDecl() { return namespaceURI_ != null && namespaceURI_.length() > 0; } public String getPrefix() { return prefix_; } public void setPrefix(String prefix) { prefix_ = prefix; } public void setNameType(byte type) { nameType_ = type; } public byte getNameType() { return nameType_; } public String getStringValue() { if (prefix_ != null && prefix_.length() > 0) return prefix_ + ':' + localName_; else return localName_; } /** * @deprecated : use for debugging purpose only, * use getStringValue() for production */ public String toString() { //TODO : remove this copy of getStringValue() if (prefix_ != null && prefix_.length() > 0) return prefix_ + ':' + localName_; else return localName_; //TODO : replace by something like this /* if (prefix_ != null && prefix_.length() > 0) return prefix_ + ':' + localName_; if (needsNamespaceDecl()) { if (prefix_ != null && prefix_.length() > 0) return "{" + namespaceURI_ + "}" + prefix_ + ':' + localName_; return "{" + namespaceURI_ + "}" + localName_; } else return localName_; */ } /** * Compares two QNames by comparing namespace URI * and local names. The prefixes are not relevant. * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Object o) { QName other = (QName) o; if(nameType_ != other.nameType_) { return nameType_ < other.nameType_ ? Constants.INFERIOR : Constants.SUPERIOR; } int c; if (namespaceURI_ == null) c = other.namespaceURI_ == null ? Constants.EQUAL : Constants.INFERIOR; else if (other.namespaceURI_ == null) c = Constants.SUPERIOR; else c = namespaceURI_.compareTo(other.namespaceURI_); return c == Constants.EQUAL ? localName_.compareTo(other.localName_) : c; } /** * Checks two QNames for equality. Two QNames are equal * if their namespace URIs, local names and prefixes are equal. * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { int cmp = compareTo(obj); if(cmp != 0) return false; QName other = (QName) obj; if(prefix_ == null) return other.prefix_ == null ? true : false; else if(other.prefix_ == null) return false; else return prefix_.equals(other.prefix_); } public boolean equalsSimple(QName other) { int c; if (namespaceURI_ == null) c = other.namespaceURI_ == null ? Constants.EQUAL : Constants.INFERIOR; else if (other.namespaceURI_ == null) c = Constants.SUPERIOR; else c = namespaceURI_.compareTo(other.namespaceURI_); if (c == Constants.EQUAL) return localName_.equals(other.localName_); return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { int h = nameType_ + 31 + localName_.hashCode(); h += 31*h + (namespaceURI_ == null ? 1 : namespaceURI_.hashCode()); h += 31*h + (prefix_ == null ? 1 : prefix_.hashCode()); return h; } public static String extractPrefix(String qname) { int p = qname.indexOf(':'); if (p == Constants.STRING_NOT_FOUND) return null; if (p == 0) throw new IllegalArgumentException("Illegal QName: starts with a :"); return qname.substring(0, p); } public static String extractLocalName(String qname) { int p = qname.indexOf(':'); if (p == Constants.STRING_NOT_FOUND) return qname; if (p == 0) throw new IllegalArgumentException("Illegal QName: starts with a :"); if (p == qname.length()) throw new IllegalArgumentException("Illegal QName: ends with a :"); return qname.substring(p + 1); } public static QName parse(XQueryContext context, String qname, String defaultNS) throws XPathException { String prefix = extractPrefix(qname); String namespaceURI; if (prefix != null) { namespaceURI = context.getURIForPrefix(prefix); if (namespaceURI == null) throw new XPathException("No namespace defined for prefix " + prefix); } else namespaceURI = defaultNS; if (namespaceURI == null) namespaceURI = ""; return new QName(extractLocalName(qname), namespaceURI, prefix); } public static QName parse(XQueryContext context, String qname) throws XPathException { return parse(context, qname, context.getURIForPrefix("")); } public final static boolean isQName(String name) { int colon = name.indexOf(':'); if (colon == Constants.STRING_NOT_FOUND) return XMLChar.isValidNCName(name); if (colon == 0 || colon == name.length() - 1) return false; if (!XMLChar.isValidNCName(name.substring(0, colon))) return false; if (!XMLChar.isValidNCName(name.substring(colon + 1))) return false; return true; } }
package org.jgroups; import org.jgroups.conf.ClassConfigurator; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.util.Buffer; import org.jgroups.util.Headers; import org.jgroups.util.Streamable; import org.jgroups.util.Util; import java.io.*; import java.util.Map; /** * A Message encapsulates data sent to members of a group. It contains among other things the * address of the sender, the destination address, a payload (byte buffer) and a list of headers. * Headers are added by protocols on the sender side and removed by protocols on the receiver's * side. * <p> * The byte buffer can point to a reference, and we can subset it using index and length. However, * when the message is serialized, we only write the bytes between index and length. * * @since 2.0 * @author Bela Ban */ public class Message implements Streamable { protected Address dest_addr; protected Address src_addr; /** The payload */ private byte[] buf; /** The index into the payload (usually 0) */ protected int offset; /** The number of bytes in the buffer (usually buf.length is buf not equal to null). */ protected int length; /** All headers are placed here */ protected Headers headers; private volatile short flags; private volatile byte transient_flags; // transient_flags is neither marshalled nor copied protected static final Log log=LogFactory.getLog(Message.class); static final byte DEST_SET = 1; static final byte SRC_SET = 1 << 1; static final byte BUF_SET = 1 << 2; public static enum Flag { OOB((short) 1), // message is out-of-band DONT_BUNDLE( (short)(1 << 1)), // don't bundle message at the transport NO_FC( (short)(1 << 2)), // bypass flow control SCOPED( (short)(1 << 3)), // when a message has a scope NO_RELIABILITY((short)(1 << 4)), // bypass UNICAST(2) and NAKACK NO_TOTAL_ORDER((short)(1 << 5)), // bypass total order (e.g. SEQUENCER) NO_RELAY((short) (1 << 6)), // bypass relaying (RELAY) RSVP((short) (1 << 7)); final short value; Flag(short value) {this.value=value;} public short value() {return value;} } public static final Flag OOB=Flag.OOB; public static final Flag DONT_BUNDLE=Flag.DONT_BUNDLE; public static final Flag NO_FC=Flag.NO_FC; public static final Flag SCOPED=Flag.SCOPED; public static final Flag NO_RELIABILITY=Flag.NO_RELIABILITY; public static final Flag NO_TOTAL_ORDER=Flag.NO_TOTAL_ORDER; public static final Flag NO_RELAY=Flag.NO_RELAY; public static final Flag RSVP=Flag.RSVP; public static enum TransientFlag { OOB_DELIVERED((short)1); final short value; TransientFlag(short flag) {value=flag;} public short value() {return value;} } public static final TransientFlag OOB_DELIVERED=TransientFlag.OOB_DELIVERED; // OOB which has already been delivered up the stack /** * Constructs a Message given a destination Address * * @param dest * Address of receiver. If it is <em>null</em> then the message sent to the group. * Otherwise, it contains a single destination and is sent to that member. * <p> */ public Message(Address dest) { setDest(dest); headers=createHeaders(3); } /** * Constructs a Message given a destination Address, a source Address and the payload byte buffer * * @param dest * Address of receiver. If it is <em>null</em> then the message sent to the group. * Otherwise, it contains a single destination and is sent to that member. * <p> * @param src * Address of sender * @param buf * Message to be sent. Note that this buffer must not be modified (e.g. buf[0]=0 is not * allowed), since we don't copy the contents on clopy() or clone(). */ public Message(Address dest, Address src, byte[] buf) { this(dest); setSrc(src); setBuffer(buf); } public Message(Address dest, byte[] buf) { this(dest, null, buf); } /** * Constructs a message. The index and length parameters allow to provide a <em>reference</em> to * a byte buffer, rather than a copy, and refer to a subset of the buffer. This is important when * we want to avoid copying. When the message is serialized, only the subset is serialized.<br/> * <em> * Note that the byte[] buffer passed as argument must not be modified. Reason: if we retransmit the * message, it would still have a ref to the original byte[] buffer passed in as argument, and so we would * retransmit a changed byte[] buffer ! * </em> * * @param dest * Address of receiver. If it is <em>null</em> then the message sent to the group. * Otherwise, it contains a single destination and is sent to that member. * <p> * @param src * Address of sender * @param buf * A reference to a byte buffer * @param offset * The index into the byte buffer * @param length * The number of bytes to be used from <tt>buf</tt>. Both index and length are checked * for array index violations and an ArrayIndexOutOfBoundsException will be thrown if * invalid */ public Message(Address dest, Address src, byte[] buf, int offset, int length) { this(dest); setSrc(src); setBuffer(buf, offset, length); } public Message(Address dest, byte[] buf, int offset, int length) { this(dest, null, buf, offset, length); } /** * Constructs a Message given a destination Address, a source Address and the payload Object * * @param dest * Address of receiver. If it is <em>null</em> then the message sent to the group. * Otherwise, it contains a single destination and is sent to that member. * <p> * @param src * Address of sender * @param obj * The object will be marshalled into the byte buffer. * <em>Obj has to be serializable (e.g. implementing * Serializable, Externalizable or Streamable, or be a basic type (e.g. Integer, Short etc)).</em> * ! The resulting buffer must not be modified (e.g. buf[0]=0 is not allowed), since we * don't copy the contents on clopy() or clone(). * <p/> */ public Message(Address dest, Address src, Object obj) { this(dest); setSrc(src); setObject(obj); } public Message(Address dest, Object obj) { this(dest, null, obj); } public Message() { headers=createHeaders(3); } public Message(boolean create_headers) { if(create_headers) headers=createHeaders(3); } public Address getDest() { return dest_addr; } public void setDest(Address new_dest) { dest_addr=new_dest; } public Address getSrc() { return src_addr; } public void setSrc(Address new_src) { src_addr=new_src; } /** * Returns a <em>reference</em> to the payload (byte buffer). Note that this buffer should not be * modified as we do not copy the buffer on copy() or clone(): the buffer of the copied message * is simply a reference to the old buffer.<br/> * Even if offset and length are used: we return the <em>entire</em> buffer, not a subset. */ public byte[] getRawBuffer() { return buf; } /** * Returns a copy of the buffer if offset and length are used, otherwise a reference. * * @return byte array with a copy of the buffer. */ final public byte[] getBuffer() { if(buf == null) return null; if(offset == 0 && length == buf.length) return buf; else { byte[] retval=new byte[length]; System.arraycopy(buf, offset, retval, 0, length); return retval; } } final public void setBuffer(byte[] b) { buf=b; if(buf != null) { offset=0; length=buf.length; } else { offset=length=0; } } /** * Set the internal buffer to point to a subset of a given buffer * * @param b * The reference to a given buffer. If null, we'll reset the buffer to null * @param offset * The initial position * @param length * The number of bytes */ final public void setBuffer(byte[] b, int offset, int length) { buf=b; if(buf != null) { if(offset < 0 || offset > buf.length) throw new ArrayIndexOutOfBoundsException(offset); if((offset + length) > buf.length) throw new ArrayIndexOutOfBoundsException((offset+length)); this.offset=offset; this.length=length; } else { this.offset=this.length=0; } } /** * <em> * Note that the byte[] buffer passed as argument must not be modified. Reason: if we retransmit the * message, it would still have a ref to the original byte[] buffer passed in as argument, and so we would * retransmit a changed byte[] buffer ! * </em> */ public final void setBuffer(Buffer buf) { if(buf != null) { this.buf=buf.getBuf(); this.offset=buf.getOffset(); this.length=buf.getLength(); } } /** * * Returns the offset into the buffer at which the data starts * */ public int getOffset() { return offset; } /** * * Returns the number of bytes in the buffer * */ public int getLength() { return length; } /** * Returns a reference to the headers hashmap, which is <em>immutable</em>. Any attempt to modify * the returned map will cause a runtime exception */ public Map<Short,Header> getHeaders() { return headers.getHeaders(); } public String printHeaders() { return headers.printHeaders(); } public int getNumHeaders() { return headers != null? headers.size() : 0; } /** * Takes an object and uses Java serialization to generate the byte[] buffer which is set in the * message. Parameter 'obj' has to be serializable (e.g. implementing Serializable, * Externalizable or Streamable, or be a basic type (e.g. Integer, Short etc)). */ final public void setObject(Object obj) { if(obj == null) return; if(obj instanceof byte[]) { setBuffer((byte[])obj); return; } if(obj instanceof Buffer) { setBuffer((Buffer)obj); return; } try { byte[] tmp=Util.objectToByteBuffer(obj); setBuffer(tmp); } catch(Exception ex) { throw new IllegalArgumentException(ex); } } /** * Uses custom serialization to create an object from the buffer of the message. Note that this * is dangerous when using your own classloader, e.g. inside of an application server ! Most * likely, JGroups will use the system classloader to deserialize the buffer into an object, * whereas (for example) a web application will want to use the webapp's classloader, resulting * in a ClassCastException. The recommended way is for the application to use their own * serialization and only pass byte[] buffer to JGroups. * * @return */ final public Object getObject() { try { return Util.objectFromByteBuffer(buf, offset, length); } catch(Exception ex) { throw new IllegalArgumentException(ex); } } /** * Sets a number of flags in a message * @param flags The flag or flags * @return A reference to the message */ public Message setFlag(Flag ... flags) { if(flags != null) for(Flag flag: flags) if(flag != null) this.flags |= flag.value(); return this; } /** * Sets the flags from a short. <em>Not recommended</em> (use {@link #setFlag(org.jgroups.Message.Flag...)} instead), * as the internal representation of flags might change anytime. * @param flag * @return */ public Message setFlag(short flag) { flags |= flag; return this; } /** * Returns the internal representation of flags. Don't use this, as the internal format might change at any time ! * This is only used by unit test code * @return */ public short getFlags() {return flags;} /** * Clears a number of flags in a message * @param flags The flags * @return A reference to the message */ public Message clearFlag(Flag ... flags) { if(flags != null) for(Flag flag: flags) if(flag != null) this.flags &= ~flag.value(); return this; } public static boolean isFlagSet(short flags, Flag flag) { return flag != null && ((flags & flag.value()) == flag.value()); } /** * Checks if a given flag is set * @param flag The flag * @return Whether of not the flag is curently set */ public boolean isFlagSet(Flag flag) { return isFlagSet(flags, flag); } /** * Same as {@link #setFlag(Flag...)} except that transient flags are not marshalled * @param flag The flag */ public Message setTransientFlag(TransientFlag ... flags) { if(flags != null) for(TransientFlag flag: flags) if(flag != null) transient_flags |= flag.value(); return this; } /** * Atomically checks if a given flag is set and - if not - sets it. When multiple threads * concurrently call this method with the same flag, only one of them will be able to set the * flag * * @param flag * @return True if the flag could be set, false if not (was already set) */ public synchronized boolean setTransientFlagIfAbsent(TransientFlag flag) { if(isTransientFlagSet(flag)) return false; setTransientFlag(flag); return true; } public Message clearTransientFlag(TransientFlag ... flags) { if(flags != null) for(TransientFlag flag: flags) if(flag != null) transient_flags &= ~flag.value(); return this; } public boolean isTransientFlagSet(TransientFlag flag) { return flag != null && (transient_flags & flag.value()) == flag.value(); } public short getTransientFlags() { return transient_flags; } public void setScope(short scope) { Util.setScope(this, scope); } public short getScope() { return Util.getScope(this); } /** Puts a header given an ID into the hashmap. Overwrites potential existing entry. */ public void putHeader(short id, Header hdr) { if(id < 0) throw new IllegalArgumentException("An ID of " + id + " is invalid"); headers.putHeader(id, hdr); } /** * Puts a header given a key into the map, only if the key doesn't exist yet * * @param id * @param hdr * @return the previous value associated with the specified key, or <tt>null</tt> if there was no * mapping for the key. (A <tt>null</tt> return can also indicate that the map previously * associated <tt>null</tt> with the key, if the implementation supports null values.) */ public Header putHeaderIfAbsent(short id, Header hdr) { if(id <= 0) throw new IllegalArgumentException("An ID of " + id + " is invalid"); return headers.putHeaderIfAbsent(id, hdr); } public Header getHeader(short id) { if(id <= 0) throw new IllegalArgumentException("An ID of " + id + " is invalid. Add the protocol which calls " + "getHeader() to jg-protocol-ids.xml"); return headers.getHeader(id); } public Message copy() { return copy(true); } /** * Create a copy of the message. If offset and length are used (to refer to another buffer), the * copy will contain only the subset offset and length point to, copying the subset into the new * copy. * * @param copy_buffer * @return Message with specified data */ public Message copy(boolean copy_buffer) { return copy(copy_buffer, true); } /** * Create a copy of the message. If offset and length are used (to refer to another buffer), the * copy will contain only the subset offset and length point to, copying the subset into the new * copy. * * @param copy_buffer * @param copy_headers * Copy the headers * @return Message with specified data */ public Message copy(boolean copy_buffer, boolean copy_headers) { Message retval=new Message(false); retval.dest_addr=dest_addr; retval.src_addr=src_addr; retval.flags=flags; retval.transient_flags=transient_flags; if(copy_buffer && buf != null) { // change bela Feb 26 2004: we don't resolve the reference retval.setBuffer(buf, offset, length); } retval.headers=copy_headers? createHeaders(headers) : createHeaders(3); return retval; } /** * Doesn't copy any headers except for those with ID >= copy_headers_above * * @param copy_buffer * @param starting_id * @return A message with headers whose ID are >= starting_id */ public Message copy(boolean copy_buffer, short starting_id) { Message retval=copy(copy_buffer, false); if(starting_id > 0) { for(Map.Entry<Short,Header> entry: getHeaders().entrySet()) { short id=entry.getKey(); if(id >= starting_id) retval.putHeader(id, entry.getValue()); } } return retval; } public Message makeReply() { return new Message(src_addr); } public String toString() { StringBuilder ret=new StringBuilder(64); ret.append("[dst: "); if(dest_addr == null) ret.append("<null>"); else ret.append(dest_addr); ret.append(", src: "); if(src_addr == null) ret.append("<null>"); else ret.append(src_addr); int size; if((size=getNumHeaders()) > 0) ret.append(" (").append(size).append(" headers)"); ret.append(", size="); if(buf != null && length > 0) ret.append(length); else ret.append('0'); ret.append(" bytes"); if(flags > 0) ret.append(", flags=").append(flagsToString(flags)); if(transient_flags > 0) ret.append(", transient_flags=" + transientFlagsToString()); ret.append(']'); return ret.toString(); } /** Tries to read an object from the message's buffer and prints it */ public String toStringAsObject() { if(buf == null) return null; try { Object obj=getObject(); return obj != null ? obj.toString() : ""; } catch(Exception e) { // it is not an object return ""; } } public String printObjectHeaders() { return headers.printObjectHeaders(); } /** * Streams all members (dest and src addresses, buffer and headers) to the output stream. * * * @param out * @throws Exception */ public void writeTo(DataOutput out) throws Exception { byte leading=0; if(dest_addr != null) leading=Util.setFlag(leading, DEST_SET); if(src_addr != null) leading=Util.setFlag(leading, SRC_SET); if(buf != null) leading=Util.setFlag(leading, BUF_SET); // 1. write the leading byte first out.write(leading); // 2. the flags (e.g. OOB, LOW_PRIO) out.writeShort(flags); // 3. dest_addr if(dest_addr != null) Util.writeAddress(dest_addr, out); // 4. src_addr if(src_addr != null) Util.writeAddress(src_addr, out); // 5. buf if(buf != null) { out.writeInt(length); out.write(buf, offset, length); } // 6. headers int size=headers.size(); out.writeShort(size); final short[] ids=headers.getRawIDs(); final Header[] hdrs=headers.getRawHeaders(); for(int i=0; i < ids.length; i++) { if(ids[i] > 0) { out.writeShort(ids[i]); writeHeader(hdrs[i], out); } } } /** * Writes the message to the output stream, but excludes the dest and src addresses unless the * src address given as argument is different from the message's src address * * @param src * @param out * @throws Exception */ public void writeToNoAddrs(Address src, DataOutputStream out) throws Exception { byte leading=0; boolean write_src_addr=src == null || src_addr != null && !src_addr.equals(src); if(write_src_addr) leading=Util.setFlag(leading, SRC_SET); if(buf != null) leading=Util.setFlag(leading, BUF_SET); // 1. write the leading byte first out.write(leading); // 2. the flags (e.g. OOB, LOW_PRIO) out.writeShort(flags); // 4. src_addr if(write_src_addr) Util.writeAddress(src_addr, out); // 5. buf if(buf != null) { out.writeInt(length); out.write(buf, offset, length); } // 6. headers int size=headers.size(); out.writeShort(size); final short[] ids=headers.getRawIDs(); final Header[] hdrs=headers.getRawHeaders(); for(int i=0; i < ids.length; i++) { if(ids[i] > 0) { out.writeShort(ids[i]); writeHeader(hdrs[i], out); } } } public void readFrom(DataInput in) throws Exception { // 1. read the leading byte first byte leading=in.readByte(); // 2. the flags flags=in.readShort(); // 3. dest_addr if(Util.isFlagSet(leading, DEST_SET)) dest_addr=Util.readAddress(in); // 4. src_addr if(Util.isFlagSet(leading, SRC_SET)) src_addr=Util.readAddress(in); // 5. buf if(Util.isFlagSet(leading, BUF_SET)) { int len=in.readInt(); buf=new byte[len]; in.readFully(buf, 0, len); length=len; } // 6. headers int len=in.readShort(); headers=createHeaders(len); short[] ids=headers.getRawIDs(); Header[] hdrs=headers.getRawHeaders(); for(int i=0; i < len; i++) { short id=in.readShort(); Header hdr=readHeader(in); ids[i]=id; hdrs[i]=hdr; } } /** * Returns the exact size of the marshalled message. Uses method size() of each header to compute * the size, so if a Header subclass doesn't implement size() we will use an approximation. * However, most relevant header subclasses have size() implemented correctly. (See * org.jgroups.tests.SizeTest). * * @return The number of bytes for the marshalled message */ public long size() { long retval=Global.BYTE_SIZE // leading byte + Global.SHORT_SIZE; // flags if(dest_addr != null) retval+=Util.size(dest_addr); if(src_addr != null) retval+=Util.size(src_addr); if(buf != null) retval+=Global.INT_SIZE // length (integer) + length; // number of bytes in the buffer retval+=Global.SHORT_SIZE; // number of headers retval+=headers.marshalledSize(); return retval; } public static String flagsToString(short flags) { StringBuilder sb=new StringBuilder(); boolean first=true; if(isFlagSet(flags, Flag.OOB)) { first=false; sb.append("OOB"); } if(isFlagSet(flags, Flag.DONT_BUNDLE)) { if(!first) sb.append("|"); else first=false; sb.append("DONT_BUNDLE"); } if(isFlagSet(flags, Flag.NO_FC)) { if(!first) sb.append("|"); else first=false; sb.append("NO_FC"); } if(isFlagSet(flags, Flag.SCOPED)) { if(!first) sb.append("|"); else first=false; sb.append("SCOPED"); } if(isFlagSet(flags, Flag.NO_RELIABILITY)) { if(!first) sb.append("|"); else first=false; sb.append("NO_RELIABILITY"); } if(isFlagSet(flags, Flag.NO_TOTAL_ORDER)) { if(!first) sb.append("|"); else first=false; sb.append("NO_TOTAL_ORDER"); } if(isFlagSet(flags, Flag.NO_RELAY)) { if(!first) sb.append("|"); else first=false; sb.append("NO_RELAY"); } if(isFlagSet(flags, Flag.RSVP)) { if(!first) sb.append("|"); else first=false; sb.append("RSVP"); } return sb.toString(); } public String transientFlagsToString() { StringBuilder sb=new StringBuilder(); if(isTransientFlagSet(TransientFlag.OOB_DELIVERED)) sb.append("OOB_DELIVERED"); return sb.toString(); } private static void writeHeader(Header hdr, DataOutput out) throws Exception { short magic_number=ClassConfigurator.getMagicNumber(hdr.getClass()); out.writeShort(magic_number); hdr.writeTo(out); } private static Header readHeader(DataInput in) throws Exception { short magic_number=in.readShort(); Class clazz=ClassConfigurator.get(magic_number); if(clazz == null) throw new IllegalArgumentException("magic number " + magic_number + " is not available in magic map"); Header hdr=(Header)clazz.newInstance(); hdr.readFrom(in); return hdr; } private static Headers createHeaders(int size) { return size > 0? new Headers(size) : new Headers(3); } private static Headers createHeaders(Headers m) { return new Headers(m); } }
package au.id.chenery.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; import java.util.HashSet; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import au.id.chenery.mapyrus.dataset.GeographicDataset; /** * Maintains state information during interpretation inside a single procedure block. * Holds the graphics attributes (color, line styles, transformations, etc.), the * variables set by the user and connections to external data sources. */ public class Context { /* * Units of world coordinate system. */ public static final int WORLD_UNITS_METRES = 1; public static final int WORLD_UNITS_FEET = 2; public static final int WORLD_UNITS_DEGREES = 3; /* * Bit flags of graphical attributes. OR-ed together * to control which attributes have been set, or not set. */ private static final int ATTRIBUTE_FONT = 1; private static final int ATTRIBUTE_JUSTIFY = 2; private static final int ATTRIBUTE_COLOR = 4; private static final int ATTRIBUTE_LINESTYLE = 8; private static final int ATTRIBUTE_CLIP = 16; /* * Projection transformation may results in some strange warping. * To get a better estimate of extents when projecting to world coordinate * system we project many points in a grid to find minimum and maximum values. */ private static final int PROJECTED_GRID_STEPS = 5; /* * Page resolution to use when no output page defined. */ private static final int DEFAULT_RESOLUTION = 96; /* * Fixed miter limit for line joins. */ private static final float MITER_LIMIT = 10.0f; /* * Graphical attributes */ private Color mColor; private BasicStroke mLinestyle; private int mJustify; private String mFontName; private int mFontStyle; private double mFontSize; private double mFontRotation; /* * Bit flags of graphical attributes that have been changed by caller * but not set yet. */ private int mAttributesPending; /* * Bit flags of graphical attributes that have been changed in this context. */ private int mAttributesChanged; /* * Transformation matrix and cumulative scaling factors and rotation. */ private AffineTransform mCtm; private double mScaling; private double mRotation; /* * Projection transformation from one world coordinate system to another. */ private WorldCoordinateTransform mProjectionTransform; /* * Transformation matrix from world coordinates to page coordinates * and the units of world coordinates. */ private AffineTransform mWorldCtm; private Rectangle2D.Double mWorldExtents; private int mWorldUnits; /* * Coordinates making up path. */ private GeometricPath mPath; /* * Path in context from which this context was created. * Used when path is not modified in this context to avoid * needlessly copying paths from one context to another. */ private GeometricPath mExistingPath; /* * List of clip polygons making up the complete clipping path. * We need a list of clip polygons instead of a single clip * polygon to preserve the inside/outside of each individual * clip polygon. */ private ArrayList mClippingPaths; /* * Currently defined variables and variables that are local * to this context. */ private HashMap mVars; private HashSet mLocalVars; /* * Output device we are drawing to. */ private OutputFormat mOutputFormat; /* * Flag true if output defined in this context. In this case * we must close the output file when this context is finished. */ private boolean mOutputDefined; /* * Dataset currently being read from, the next row to provide to caller * and the number of rows already fetched from it. */ private Dataset mDataset; /** * Create a new context with reasonable default values. */ public Context() { mColor = Color.BLACK; mLinestyle = new BasicStroke(0.1f); mJustify = OutputFormat.JUSTIFY_LEFT | OutputFormat.JUSTIFY_BOTTOM; mFontName = "SansSerif"; mFontStyle = Font.PLAIN; mFontSize = 5; mFontRotation = 0; mCtm = new AffineTransform(); mProjectionTransform = null; mWorldCtm = null; mScaling = 1.0; mRotation = 0.0; mVars = null; mLocalVars = null; mPath = null; mClippingPaths = null; mOutputFormat = null; mOutputDefined = false; mAttributesPending = mAttributesChanged = 0; mDataset = null; } /** * Create a new context, making a copy from an existing context. * @param existing is context to copy from. */ public Context(Context existing) { mColor = existing.mColor; mLinestyle = existing.mLinestyle; mJustify = existing.mJustify; mFontName = existing.mFontName; mFontStyle = existing.mFontStyle; mFontSize = existing.mFontSize; mFontRotation = existing.mFontRotation; mCtm = new AffineTransform(existing.mCtm); mProjectionTransform = null; mWorldCtm = null; mScaling = existing.mScaling; mRotation = existing.mRotation; mDataset = existing.mDataset; /* * Only create variable lookup tables when some values are * defined locally. */ mVars = null; mLocalVars = null; /* * Don't copy path -- it can be large. * Just keep reference to existing path. * * Create path locally when needed. If path is referenced without * being created then we can reuse path from existing context instead. * * This saves unnecessary copying of paths when contexts are created. */ mPath = null; if (existing.mPath != null) mExistingPath = existing.mPath; else mExistingPath = existing.mExistingPath; /* * Copy list of paths we must clip against. */ if (existing.mClippingPaths != null) mClippingPaths = (ArrayList)(existing.mClippingPaths.clone()); else mClippingPaths = null; mOutputFormat = existing.mOutputFormat; mOutputDefined = false; /* * Save state in parent context so it won't be disturbed by anything * that gets changed in this new context. */ if (mOutputFormat != null) { mOutputFormat.saveState(); } mAttributesPending = existing.mAttributesPending; mAttributesChanged = 0; } private GeometricPath getDefinedPath() { GeometricPath retval; /* * Return path defined in this context, or one defined * in previous context if nothing set here. */ if (mPath != null) retval = mPath; else retval = mExistingPath; return(retval); } /** * Return page width for output we are currently writing. * @return width in millimetres. */ public double getPageWidth() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageWidth(); return(retval); } /** * Return page height for output we are currently writing. * @return height in millimetres. */ public double getPageHeight() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageHeight(); return(retval); } /** * Return file format for output we are currently writing. * @return file format. */ public String getPageFormat() { String retval; if (mOutputFormat == null) retval = ""; else retval = mOutputFormat.getPageFormat(); return(retval); } /** * Return resolution of page we are writing to as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() throws MapyrusException { double retval; if (mOutputFormat == null) retval = Constants.MM_PER_INCH / DEFAULT_RESOLUTION; else retval = mOutputFormat.getResolution(); return(retval); } /** * Set graphics attributes (color, line width, etc.) if they * have changed since the last time we drew something. * @param attributeMask bit mask of attributes to set: ATTRIBUTE_*. */ private void setGraphicsAttributes(int attributeMask) { int maskComplement = (~attributeMask); if ((mAttributesPending & ATTRIBUTE_FONT & attributeMask) != 0) mOutputFormat.setFontAttribute(mFontName, mFontStyle, mFontSize, mFontRotation); if ((mAttributesPending & ATTRIBUTE_JUSTIFY & attributeMask) != 0) mOutputFormat.setJustifyAttribute(mJustify); if ((mAttributesPending & ATTRIBUTE_COLOR & attributeMask) != 0) mOutputFormat.setColorAttribute(mColor); if ((mAttributesPending & ATTRIBUTE_LINESTYLE & attributeMask) != 0) mOutputFormat.setLinestyleAttribute(mLinestyle); if ((mAttributesPending & ATTRIBUTE_CLIP & attributeMask) != 0) mOutputFormat.setClipAttribute(mClippingPaths); /* * Clear attributes we've just set -- they are no longer pending. */ mAttributesPending = (mAttributesPending & maskComplement); } /** * Flag that graphics attributes have been changed by a call to a procedure. * @param attributes bit flags of attributes that are changed. */ public void setAttributesChanged(int attributes) { mAttributesPending |= attributes; mAttributesChanged |= attributes; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to. * @param format is image format for saving output. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param resolution is resolution for output in dots per inch (DPI) * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, int width, int height, int resolution, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { if (mOutputDefined && mOutputFormat != null) { /* * Finish any previous page before beginning a new one. */ mOutputFormat.closeOutputFormat(); /* * Clear world extents, projection and clip path from previous page. * Other page settings are independent of a particular page so leave * them alone. */ mWorldExtents = null; mWorldCtm = null; mProjectionTransform = null; mClippingPaths = null; } mOutputFormat = new OutputFormat(filename, format, width, height, resolution, extras, stdoutStream); mAttributesPending = ATTRIBUTE_FONT|ATTRIBUTE_JUSTIFY|ATTRIBUTE_COLOR| ATTRIBUTE_LINESTYLE|ATTRIBUTE_CLIP; mOutputDefined = true; } /** * Closes a context. Any output started in this context is completed, * memory used for context is released. * A context cannot be used again after this call. * @return bit flag of graphical attributes that were changed in this context * and cannot be restored. */ public int closeContext() throws IOException, MapyrusException { boolean restoredState; if (mOutputFormat != null && !mOutputDefined) { /* * If state could be restored then no need for caller to set * graphical attributes back to their old values again. */ restoredState = mOutputFormat.restoreState(); if (restoredState) mAttributesChanged = 0; } if (mOutputDefined) { mOutputFormat.closeOutputFormat(); mOutputFormat = null; mOutputDefined = false; } mPath = mExistingPath = null; mClippingPaths = null; mVars = null; mLocalVars = null; mDataset = null; return(mAttributesChanged); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { /* * Adjust width and dashes by current scaling factor. */ if (dashes == null) { mLinestyle = new BasicStroke((float)(width * mScaling), cap, join, MITER_LIMIT); } else { for (int i = 0; i < dashes.length; i++) dashes[i] *= mScaling; mLinestyle = new BasicStroke((float)(width * mScaling), cap, join, MITER_LIMIT, dashes, (float)phase); } mAttributesPending |= ATTRIBUTE_LINESTYLE; mAttributesChanged |= ATTRIBUTE_LINESTYLE; } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color color) { mColor = color; mAttributesPending |= ATTRIBUTE_COLOR; mAttributesChanged |= ATTRIBUTE_COLOR; } /** * Sets font for labelling with. * @param fontName is name of font as defined in java.awt.Font class. * @param fontStyle is a style as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. */ public void setFont(String fontName, int fontStyle, double fontSize) { mFontName = fontName; mFontStyle = fontStyle; mFontSize = fontSize * mScaling; mFontRotation = mRotation; mAttributesChanged |= ATTRIBUTE_FONT; mAttributesPending |= ATTRIBUTE_FONT; } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of JUSTIFY_* constant values for justification. */ public void setJustify(int code) { mJustify = code; mAttributesChanged |= ATTRIBUTE_JUSTIFY; mAttributesPending |= ATTRIBUTE_JUSTIFY; } /** * Sets scaling for subsequent coordinates. * @param factor is new scaling in X and Y axes. */ public void setScaling(double factor) { mCtm.scale(factor, factor); mScaling *= factor; } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { mCtm.translate(x, y); } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, measured counter-clockwise. */ public void setRotation(double angle) { mCtm.rotate(angle); mRotation += angle; mRotation = Math.IEEEremainder(mRotation, Math.PI * 2); } /** * Sets transformation from real world coordinates to page coordinates. * @param x1 minimum X world coordinate. * @param y1 minimum Y world coordinate. * @param x2 maximum X world coordinate. * @param y2 maximum Y world coordinate. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) */ public void setWorlds(double x1, double y1, double x2, double y2, int units) throws MapyrusException { double xDiff = x2 - x1; double yDiff = y2 - y1; double xMid, yMid; double worldAspectRatio = yDiff / xDiff; double pageAspectRatio; if (mOutputFormat == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_OUTPUT)); pageAspectRatio = mOutputFormat.getPageHeight() / mOutputFormat.getPageWidth(); /* * Expand world coordinate range in either X or Y axis so * it has same aspect ratio as page. */ if (worldAspectRatio > pageAspectRatio) { xMid = (x1 + x2) / 2.0; x1 = xMid - (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); x2 = xMid + (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); } else if (worldAspectRatio < pageAspectRatio) { /* * World coordinate range is wider than page coordinate system. * Expand Y axis range. */ yMid = (y1 + y2) / 2.0; y1 = yMid - (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); y2 = yMid + (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); } /* * Setup CTM from world coordinates to page coordinates. */ mWorldCtm = new AffineTransform(); mWorldCtm.scale(mOutputFormat.getPageWidth() / (x2 - x1), mOutputFormat.getPageHeight() / (y2 - y1)); mWorldCtm.translate(-x1, -y1); mWorldExtents = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); mWorldUnits = units; } /** * Sets reprojection between two world coordinate systems. * @param sourceSystem description of coordinate system coordinates transformed form. * @param destinationSystem description of coordinate system coordinates * are transformed to. */ public void setReprojection(String sourceSystem, String destinationSystem) throws MapyrusException { mProjectionTransform = new WorldCoordinateTransform(sourceSystem, destinationSystem); } /** * Set current dataset that can be queried and fetched from. * @param dataset opened dataset for subsequent queries. */ public void setDataset(GeographicDataset dataset) throws MapyrusException { // TODO close any previous dataset first. mDataset = new Dataset(dataset); } /** * Returns scaling factor in current transformation. * @return scale value. */ public double getScaling() { return(mScaling); } /** * Returns rotation angle in current transformation. * @return rotation in radians. */ public double getRotation() { return(mRotation); } /** * Returns world coordinate extents being shown on page. * @return rectangular area covered by extents. */ public Rectangle2D.Double getWorldExtents() throws MapyrusException { Rectangle2D.Double retval; if (mWorldExtents != null) { retval = mWorldExtents; } else if (mOutputFormat != null) { retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(); } return(retval); } /** * Return scale of world coordinates. The world coordinate range divided * by the page size. * @return scale, (1:2000) is returned as value 2000. */ public double getWorldScale() { double scale; double worldWidthInMM; if (mOutputFormat != null && mWorldCtm != null) { worldWidthInMM = mWorldExtents.width; if (mWorldUnits == WORLD_UNITS_METRES) worldWidthInMM *= 1000.0; else if (mWorldUnits == WORLD_UNITS_FEET) worldWidthInMM *= (1000.0 / 0.3048); else worldWidthInMM *= (110000 * 1000.0); scale = worldWidthInMM / mOutputFormat.getPageWidth(); } else { scale = 1.0; } return(scale); } /** * Returns bounding that when transformed through projection results * in same bounding box as current world coordinate system. * @return bounding box. */ public Rectangle2D.Double getUnprojectedExtents() throws MapyrusException { Rectangle2D.Double retval; double xMin, yMin, xMax, yMax; int i, j; double coords[] = new double[2]; xMin = yMin = Float.MAX_VALUE; xMax = yMax = Float.MIN_VALUE; if (mWorldExtents != null) { if (mProjectionTransform != null) { /* * Transform points around boundary of world coordinate extents * backwards through projection transformation. * Find minimum and maximum values. */ for (i = 0; i <= PROJECTED_GRID_STEPS; i++) { for (j = 0; j <= PROJECTED_GRID_STEPS; j++) { /* * Only transform points around boundary. */ if ((i == 0 || i == PROJECTED_GRID_STEPS) && (j == 0 || j == PROJECTED_GRID_STEPS)) { coords[0] = mWorldExtents.x + ((double)i / PROJECTED_GRID_STEPS) * mWorldExtents.width; coords[1] = mWorldExtents.y + ((double)j / PROJECTED_GRID_STEPS) * mWorldExtents.height; mProjectionTransform.backwardTransform(coords); if (coords[0] < xMin) xMin = coords[0]; if (coords[1] < yMin) yMin = coords[1]; if (coords[0] > xMax) xMax = coords[0]; if (coords[1] > yMax) yMax = coords[1]; } } } retval = new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin); } else { /* * No projection transformation set so just return plain world * coordinate extents. */ retval = mWorldExtents; } } else if (mOutputFormat != null) { /* * No world coordinate system set, just return page coordinate. */ retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(0, 0, 1, 1); } return(retval); } /** * Get dataset currently being queried. * @return dataset being queried, or null if not dataset is being queried. */ public Dataset getDataset() { return(mDataset); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); /* * Set no rotation for point. */ mPath.moveTo(dstPts[0], dstPts[1], 0.0f); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Make sure that a start point for path was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_MOVETO)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); mPath.lineTo(dstPts[0], dstPts[1]); } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { double centrePts[] = new double[2]; double endPts[] = new double[2]; float dstPts[] = new float[4]; centrePts[0] = xCentre; centrePts[1] = yCentre; endPts[0] = xEnd; endPts[1] = yEnd; /* * Make sure that a start point for arc was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_ARC_START)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(centrePts); mProjectionTransform.forwardTransform(endPts); } /* * Transform points from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) { mWorldCtm.transform(centrePts, 0, centrePts, 0, 1); mWorldCtm.transform(endPts, 0, endPts, 0, 1); } mCtm.transform(centrePts, 0, dstPts, 0, 1); mCtm.transform(endPts, 0, dstPts, 2, 1); mPath.arcTo(direction, dstPts[0], dstPts[1], dstPts[2], dstPts[3]); } /** * Clears currently defined path. */ public void clearPath() { /* * If a path was defined then clear it. * If no path then clear any path we are using from another * context too. */ if (mPath != null) mPath.reset(); else mExistingPath = null; } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path != null) { mPath = path.samplePath(spacing * mScaling, offset * mScaling, resolution); } } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { GeometricPath path = getDefinedPath(); if (path != null) mPath = path.stripePath(spacing * mScaling, angle); } /** * Draw currently defined path. */ public void stroke() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_LINESTYLE|ATTRIBUTE_CLIP); mOutputFormat.stroke(path.getShape()); } } /** * Fill currently defined path. */ public void fill() { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_CLIP); mOutputFormat.fill(path.getShape()); } } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void protect() throws MapyrusException { GeometricPath path = getDefinedPath(); GeometricPath protectedPath; if (path != null && mOutputFormat != null) { /* * Add a rectangle around the edge of the page as the new polygon * perimeter. The path becomes an island in the polygon (with * opposite direction so winding rule works) and only * the area outside the path is then visible. */ float width = (float)(mOutputFormat.getPageWidth()); float height = (float)(mOutputFormat.getPageHeight()); protectedPath = new GeometricPath(); protectedPath.moveTo(0.0f, 0.0f, 0.0); if (path.isClockwise(getResolution())) { /* * Outer rectange should be anti-clockwise. */ protectedPath.lineTo(width, 0.0f); protectedPath.lineTo(width, height); protectedPath.lineTo(0.0f, height); } else { /* * Outer rectangle should be clockwise. */ protectedPath.lineTo(0.0f, height); protectedPath.lineTo(width, height); protectedPath.lineTo(width, 0.0f); } protectedPath.closePath(); protectedPath.append(path, false); mAttributesPending |= ATTRIBUTE_CLIP; mAttributesChanged |= ATTRIBUTE_CLIP; mOutputFormat.clip(protectedPath.getShape()); /* * Add this polygon to list of paths we are clipping against. */ if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(protectedPath); } } /** * Clip to show only inside of currently defined path. */ public void clip() { GeometricPath path = getDefinedPath(); GeometricPath clipPath; if (path != null && mOutputFormat != null) { clipPath = new GeometricPath(path); if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(clipPath); mAttributesPending |= ATTRIBUTE_CLIP; mAttributesChanged |= ATTRIBUTE_CLIP; if (mOutputFormat != null) { mOutputFormat.clip(clipPath.getShape()); } } } /** * Draw label positioned at (or along) currently defined path. * @param label is string to draw on page. */ public void label(String label) { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_FONT|ATTRIBUTE_JUSTIFY|ATTRIBUTE_CLIP); mOutputFormat.label(path.getMoveTos(), label); } } /** * Returns the number of moveTo's in path defined in this context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in this context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getLineToCount(); return(retval); } /** * Returns geometric length of current path. * @return length of current path. */ public double getPathLength() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getLength(resolution); return(retval); } /** * Returns geometric area of current path. * @return area of current path. */ public double getPathArea() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getArea(resolution); return(retval); } /** * Returns geometric centroid of current path. * @return centroid of current path. */ public Point2D.Double getPathCentroid() throws MapyrusException { Point2D.Double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = new Point2D.Double(); else retval = path.getCentroid(resolution); return(retval); } /** * Returns rotation angle for each each moveTo point in current path * @return array of rotation angles relative to rotation in current * transformation matrix. */ public ArrayList getMoveToRotations() { ArrayList retval; GeometricPath path = getDefinedPath(); if (path == null) retval = null; else retval = path.getMoveToRotations(); return(retval); } /** * Returns coordinate for each each moveTo point in current path. * @return array of Point2D.Float objects relative to current transformation matrix. */ public ArrayList getMoveTos() throws MapyrusException { ArrayList retval = null; GeometricPath path = getDefinedPath(); AffineTransform inverse; ArrayList moveTos; try { if (path != null) { /* * If there is no transformation matrix then we can return original * coordinates, otherwise we must convert all coordinates to be relative * to the current transformation matrix and build a new list. */ if (mCtm.isIdentity()) { retval = path.getMoveTos(); } else { inverse = mCtm.createInverse(); moveTos = path.getMoveTos(); retval = new ArrayList(moveTos.size()); for (int i = 0; i < moveTos.size(); i++) { Point2D.Float pt = (Point2D.Float)(moveTos.get(i)); retval.add(inverse.transform(pt, null)); } } } } catch (NoninvertibleTransformException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Returns bounding box of this geometry. * @return bounding box, or null if no path is defined. */ public Rectangle2D getBounds2D() { Rectangle2D bounds; GeometricPath path = getDefinedPath(); if (path == null) bounds = null; else bounds = path.getBounds2D(); return(bounds); } /** * Returns value of a variable. * @param variable name to lookup. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName) { Argument retval; /* * Variable is not set if no lookup table is defined. */ if (mVars == null) retval = null; else retval = (Argument)mVars.get(varName); return(retval); } /** * Indicates that a variable is to be stored locally in this context * and not be made available to other contexts. * @param varName name of variable to be treated as local. */ public void setLocalScope(String varName) { /* * Record that variable is local. */ if (mLocalVars == null) mLocalVars = new HashSet(); mLocalVars.add(varName); } /** * Returns true if variable has been defined local in this context * with @see setLocalScope(). * @param varName is name of variable to check. * @return true if variable defined local. */ public boolean hasLocalScope(String varName) { return(mLocalVars != null && mLocalVars.contains(varName)); } /** * Define variable in current context, replacing any existing * variable with the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { /* * Create new variable. */ if (mVars == null) mVars = new HashMap(); mVars.put(varName, value); } }
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; import com.ecyrd.jspwiki.providers.*; import com.ecyrd.jspwiki.attachment.*; public class WikiEngineTest extends TestCase { public static final String NAME1 = "Test1"; Properties props = new Properties(); TestEngine m_engine; public WikiEngineTest( String s ) { super( s ); } public static Test suite() { return new TestSuite( WikiEngineTest.class ); } public static void main(String[] args) { junit.textui.TestRunner.main(new String[] { WikiEngineTest.class.getName() } ); } public void setUp() throws Exception { props.load( TestEngine.findTestProperties() ); m_engine = new TestEngine(props); } public void tearDown() { String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); File f = new File( files, NAME1+FileSystemProvider.FILE_EXT ); f.delete(); } public void testNonExistantDirectory() throws Exception { String tmpdir = System.getProperties().getProperty("java.tmpdir"); String dirname = "non-existant-directory"; String newdir = tmpdir + File.separator + dirname; props.setProperty( FileSystemProvider.PROP_PAGEDIR, newdir ); try { WikiEngine test = new TestEngine( props ); fail( "Wiki did not warn about wrong property." ); } catch( WikiException e ) { // This is okay. } } public void testNonExistantDirProperty() throws Exception { props.remove( FileSystemProvider.PROP_PAGEDIR ); try { WikiEngine test = new TestEngine( props ); fail( "Wiki did not warn about missing property." ); } catch( WikiException e ) { // This is okay. } } /** * Check that calling pageExists( String ) works. */ public void testNonExistantPage() throws Exception { String pagename = "Test1"; assertEquals( "Page already exists", false, m_engine.pageExists( pagename ) ); } /** * Check that calling pageExists( WikiPage ) works. */ public void testNonExistantPage2() throws Exception { WikiPage page = new WikiPage("Test1"); assertEquals( "Page already exists", false, m_engine.pageExists( page ) ); } public void testPutPage() { String text = "Foobar.\r\n"; String name = NAME1; m_engine.saveText( name, text ); assertEquals( "page does not exist", true, m_engine.pageExists( name ) ); assertEquals( "wrong content", text, m_engine.getText( name ) ); } public void testPutPageEntities() { String text = "Foobar. &quot;\r\n"; String name = NAME1; m_engine.saveText( name, text ); assertEquals( "page does not exist", true, m_engine.pageExists( name ) ); assertEquals( "wrong content", "Foobar. &amp;quot;\r\n", m_engine.getText( name ) ); } /** * Cgeck that basic " is changed. */ public void testPutPageEntities2() { String text = "Foobar. \"\r\n"; String name = NAME1; m_engine.saveText( name, text ); assertEquals( "page does not exist", true, m_engine.pageExists( name ) ); assertEquals( "wrong content", "Foobar. &quot;\r\n", m_engine.getText( name ) ); } public void testGetHTML() { String text = "''Foobar.''"; String name = NAME1; m_engine.saveText( name, text ); String data = m_engine.getHTML( name ); assertEquals( "<I>Foobar.</I>\n", data ); } public void testEncodeNameLatin1() { String name = "abc"; assertEquals( "abc%E5%E4%F6", m_engine.encodeName(name) ); } public void testEncodeNameUTF8() throws Exception { String name = "\u0041\u2262\u0391\u002E"; props.setProperty( WikiEngine.PROP_ENCODING, "UTF-8" ); WikiEngine engine = new TestEngine( props ); assertEquals( "A%E2%89%A2%CE%91.", engine.encodeName(name) ); } public void testReadLinks() throws Exception { String src="Foobar. [Foobar]. Frobozz. [This is a link]."; Object[] result = m_engine.scanWikiLinks( src ).toArray(); assertEquals( "item 0", result[0], "Foobar" ); assertEquals( "item 1", result[1], "ThisIsALink" ); } public void testBeautifyTitle() { String src = "WikiNameThingy"; assertEquals("Wiki Name Thingy", m_engine.beautifyTitle( src ) ); } /** * Acronyms should be treated wisely. */ public void testBeautifyTitleAcronym() { String src = "JSPWikiPage"; assertEquals("JSP Wiki Page", m_engine.beautifyTitle( src ) ); } /** * Acronyms should be treated wisely. */ public void testBeautifyTitleAcronym2() { String src = "DELETEME"; assertEquals("DELETEME", m_engine.beautifyTitle( src ) ); } public void testBeautifyTitleAcronym3() { String src = "JSPWikiFAQ"; assertEquals("JSP Wiki FAQ", m_engine.beautifyTitle( src ) ); } public void testBeautifyTitleNumbers() { String src = "TestPage12"; assertEquals("Test Page 12", m_engine.beautifyTitle( src ) ); } /** * English articles too. */ public void testBeautifyTitleArticle() { String src = "ThisIsAPage"; assertEquals("This Is A Page", m_engine.beautifyTitle( src ) ); } /** * English articles too, pathological case... */ /* public void testBeautifyTitleArticle2() { String src = "ThisIsAJSPWikiPage"; assertEquals("This Is A JSP Wiki Page", m_engine.beautifyTitle( src ) ); } */ /** * Tries to find an existing class. */ public void testFindClass() throws Exception { Class foo = WikiEngine.findWikiClass( "WikiPage", "com.ecyrd.jspwiki" ); assertEquals( foo.getName(), "com.ecyrd.jspwiki.WikiPage" ); } /** * Non-existant classes should throw ClassNotFoundEx. */ public void testFindClassNoClass() throws Exception { try { Class foo = WikiEngine.findWikiClass( "MubbleBubble", "com.ecyrd.jspwiki" ); fail("Found class"); } catch( ClassNotFoundException e ) { // Expected } } public void testLatestGet() throws Exception { props.setProperty( "jspwiki.pageProvider", "com.ecyrd.jspwiki.providers.VerySimpleProvider" ); WikiEngine engine = new TestEngine( props ); WikiPage p = engine.getPage( "test", -1 ); VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider(); assertEquals( "wrong page", "test", vsp.m_latestReq ); assertEquals( "wrong version", -1, vsp.m_latestVers ); } public void testLatestGet2() throws Exception { props.setProperty( "jspwiki.pageProvider", "com.ecyrd.jspwiki.providers.VerySimpleProvider" ); WikiEngine engine = new TestEngine( props ); String p = engine.getText( "test", -1 ); VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider(); assertEquals( "wrong page", "test", vsp.m_latestReq ); assertEquals( "wrong version", -1, vsp.m_latestVers ); } public void testLatestGet3() throws Exception { props.setProperty( "jspwiki.pageProvider", "com.ecyrd.jspwiki.providers.VerySimpleProvider" ); WikiEngine engine = new TestEngine( props ); String p = engine.getHTML( "test", -1 ); VerySimpleProvider vsp = (VerySimpleProvider) engine.getPageManager().getProvider(); assertEquals( "wrong page", "test", vsp.m_latestReq ); assertEquals( "wrong version", -1, vsp.m_latestVers ); } public void testLatestGet4() throws Exception { props.setProperty( "jspwiki.pageProvider", "com.ecyrd.jspwiki.providers.VerySimpleProvider" ); props.setProperty( "jspwiki.usePageCache", "true" ); WikiEngine engine = new TestEngine( props ); String p = engine.getHTML( "test", -1 ); CachingProvider cp = (CachingProvider)engine.getPageManager().getProvider(); VerySimpleProvider vsp = (VerySimpleProvider) cp.getRealProvider(); assertEquals( "wrong page", "test", vsp.m_latestReq ); assertEquals( "wrong version", -1, vsp.m_latestVers ); } /** * Checks, if ReferenceManager is informed of new attachments. */ public void testAttachmentRefs() throws Exception { ReferenceManager refMgr = m_engine.getReferenceManager(); AttachmentManager attMgr = m_engine.getAttachmentManager(); m_engine.saveText( NAME1, "fooBar"); Attachment att = new Attachment( NAME1, "TestAtt.txt" ); att.setAuthor( "FirstPost" ); attMgr.storeAttachment( att, m_engine.makeAttachmentFile() ); try { // and check post-conditions Collection c = refMgr.findUncreated(); assertTrue("attachment exists: "+c, c==null || c.size()==0 ); c = refMgr.findUnreferenced(); assertEquals( "unreferenced count", 2, c.size() ); Iterator i = c.iterator(); String first = (String) i.next(); String second = (String) i.next(); assertTrue( "unreferenced", (first.equals( NAME1 ) && second.equals( NAME1+"/TestAtt.txt")) || (first.equals( NAME1+"/TestAtt.txt" ) && second.equals( NAME1 )) ); } finally { // do cleanup String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); m_engine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) ); } } /** * Is ReferenceManager updated properly if a page references * its own attachments? */ /* FIXME: This is a deep problem. The real problem is that the reference manager cannot know when it encounters a link like "testatt.txt" that it is really a link to an attachment IF the link is created before the attachment. This means that when the attachment is created, the link will stay in the "uncreated" list. There are two issues here: first of all, TranslatorReader should able to return the proper attachment references (which I think it does), and second, the ReferenceManager should be able to remove any links that are not referred to, nor they are created. However, doing this in a relatively sane timeframe can be a problem. */ public void testAttachmentRefs2() throws Exception { ReferenceManager refMgr = m_engine.getReferenceManager(); AttachmentManager attMgr = m_engine.getAttachmentManager(); m_engine.saveText( NAME1, "[TestAtt.txt]"); // check a few pre-conditions Collection c = refMgr.findReferrers( "TestAtt.txt" ); assertTrue( "normal, unexisting page", c!=null && ((String)c.iterator().next()).equals( NAME1 ) ); c = refMgr.findReferrers( NAME1+"/TestAtt.txt" ); assertTrue( "no attachment", c==null || c.size()==0 ); c = refMgr.findUncreated(); assertTrue( "unknown attachment", c!=null && c.size()==1 && ((String)c.iterator().next()).equals( "TestAtt.txt" ) ); // now we create the attachment Attachment att = new Attachment( NAME1, "TestAtt.txt" ); att.setAuthor( "FirstPost" ); attMgr.storeAttachment( att, m_engine.makeAttachmentFile() ); try { // and check post-conditions c = refMgr.findUncreated(); assertTrue( "attachment exists: ", c==null || c.size()==0 ); c = refMgr.findReferrers( "TestAtt.txt" ); assertTrue( "no normal page", c==null || c.size()==0 ); c = refMgr.findReferrers( NAME1+"/TestAtt.txt" ); assertTrue( "attachment exists now", c!=null && ((String)c.iterator().next()).equals( NAME1 ) ); c = refMgr.findUnreferenced(); assertTrue( "unreferenced", c.size()==1 && ((String)c.iterator().next()).equals( NAME1 )); } finally { // do cleanup String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); m_engine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) ); } } /** * Checks, if ReferenceManager is informed if a link to an attachment is added. */ public void testAttachmentRefs3() throws Exception { ReferenceManager refMgr = m_engine.getReferenceManager(); AttachmentManager attMgr = m_engine.getAttachmentManager(); m_engine.saveText( NAME1, "fooBar"); Attachment att = new Attachment( NAME1, "TestAtt.txt" ); att.setAuthor( "FirstPost" ); attMgr.storeAttachment( att, m_engine.makeAttachmentFile() ); m_engine.saveText( NAME1, " ["+NAME1+"/TestAtt.txt] "); try { // and check post-conditions Collection c = refMgr.findUncreated(); assertTrue( "attachment exists", c==null || c.size()==0 ); c = refMgr.findUnreferenced(); assertEquals( "unreferenced count", c.size(), 1 ); assertTrue( "unreferenced", ((String)c.iterator().next()).equals( NAME1 ) ); } finally { // do cleanup String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); m_engine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) ); } } /** * Checks, if ReferenceManager is informed if a third page references an attachment. */ public void testAttachmentRefs4() throws Exception { ReferenceManager refMgr = m_engine.getReferenceManager(); AttachmentManager attMgr = m_engine.getAttachmentManager(); m_engine.saveText( NAME1, "[TestPage2]"); Attachment att = new Attachment( NAME1, "TestAtt.txt" ); att.setAuthor( "FirstPost" ); attMgr.storeAttachment( att, m_engine.makeAttachmentFile() ); m_engine.saveText( "TestPage2", "["+NAME1+"/TestAtt.txt]"); try { // and check post-conditions Collection c = refMgr.findUncreated(); assertTrue( "attachment exists", c==null || c.size()==0 ); c = refMgr.findUnreferenced(); assertEquals( "unreferenced count", c.size(), 1 ); assertTrue( "unreferenced", ((String)c.iterator().next()).equals( NAME1 ) ); } finally { // do cleanup String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); m_engine.deleteAll( new File( files, NAME1+BasicAttachmentProvider.DIR_EXTENSION ) ); new File( files, "TestPage2"+FileSystemProvider.FILE_EXT ).delete(); } } }
package org.mapyrus; import java.awt.BasicStroke; import java.awt.Color; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.HashSet; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import javax.swing.ImageIcon; import org.mapyrus.dataset.GeographicDataset; import org.mapyrus.font.StringDimension; import org.mapyrus.geom.Sinkhole; import org.mapyrus.geom.SutherlandHodgman; /** * Maintains state information during interpretation inside a single procedure block. * Holds the graphics attributes (color, line styles, transformations, etc.), the * variables set by the user and connections to external data sources. */ public class Context { /* * Units of world coordinate system. */ public static final int WORLD_UNITS_METRES = 1; public static final int WORLD_UNITS_FEET = 2; public static final int WORLD_UNITS_DEGREES = 3; /* * Bit flags of graphical attributes. OR-ed together * to control which attributes have been set, or not set. */ private static final int ATTRIBUTE_FONT = 1; private static final int ATTRIBUTE_JUSTIFY = 2; private static final int ATTRIBUTE_COLOR = 4; private static final int ATTRIBUTE_LINESTYLE = 8; private static final int ATTRIBUTE_CLIP = 16; /* * Projection transformation may results in some strange warping. * To get a better estimate of extents when projecting to world coordinate * system we project many points in a grid to find minimum and maximum values. */ private static final int PROJECTED_GRID_STEPS = 5; /* * Page resolution to use when no output page defined. */ private static final int DEFAULT_RESOLUTION = 96; /* * Fixed miter limit for line joins. */ private static final float MITER_LIMIT = 10.0f; /* * Graphical attributes */ private Color mColor; private BasicStroke mLinestyle; private int mJustify; private String mFontName; private double mFontSize; private double mFontRotation; /* * Bit flags of graphical attributes that have been changed by caller * but not set yet. */ private int mAttributesPending; /* * Bit flags of graphical attributes that have been changed in this context. */ private int mAttributesChanged; /* * Transformation matrix and cumulative scaling factors and rotation. */ private AffineTransform mCtm; private double mScaling; private double mRotation; /* * Projection transformation from one world coordinate system to another. */ private WorldCoordinateTransform mProjectionTransform; /* * Transformation matrix from world coordinates to page coordinates * and the units of world coordinates. */ private AffineTransform mWorldCtm; private Rectangle2D.Double mWorldExtents; private int mWorldUnits; /* * Coordinates making up path. */ private GeometricPath mPath; /* * Path in context from which this context was created. * Used when path is not modified in this context to avoid * needlessly copying paths from one context to another. */ private GeometricPath mExistingPath; /* * List of clip polygons making up the complete clipping path. * We need a list of clip polygons instead of a single clip * polygon to preserve the inside/outside of each individual * clip polygon. */ private ArrayList mClippingPaths; /* * Currently defined variables and variables that are local * to this context. */ private HashMap mVars; private HashSet mLocalVars; /* * Output device we are drawing to. */ private OutputFormat mOutputFormat; /* * Flag true if output and dataset defined in this context. In this case * we must close the output file and dataset when this context is finished. */ private boolean mOutputDefined; private boolean mDatasetDefined; /* * Dataset currently being read from, the next row to provide to caller * and the number of rows already fetched from it. */ private Dataset mDataset; /* * Name of procedure block that this context is executing in. */ private String mBlockName; /** * Clear graphics context to empty state. * @param c context to clear. */ private void initialiseContext(Context c) { mColor = Color.BLACK; mLinestyle = new BasicStroke(0.1f); mJustify = OutputFormat.JUSTIFY_LEFT | OutputFormat.JUSTIFY_BOTTOM; mFontName = "SansSerif"; mFontSize = 5; mFontRotation = 0; mPath = mExistingPath = null; mClippingPaths = null; mCtm = new AffineTransform(); mScaling = 1.0; mRotation = 0.0; mAttributesPending = (ATTRIBUTE_CLIP | ATTRIBUTE_COLOR | ATTRIBUTE_FONT | ATTRIBUTE_JUSTIFY | ATTRIBUTE_LINESTYLE); mAttributesChanged = 0; mProjectionTransform = null; mWorldCtm = null; } /** * Create a new context with reasonable default values. */ public Context() { mVars = null; mLocalVars = null; mOutputFormat = null; mOutputDefined = false; mDatasetDefined = false; mDataset = null; /* * First context is outside of any procedure block. */ mBlockName = null; initialiseContext(this); } /** * Create a new context, making a copy from an existing context. * @param existing is context to copy from. * @param blockName is name of procedure block which context will execute. */ public Context(Context existing, String blockName) { mColor = existing.mColor; mLinestyle = existing.mLinestyle; mJustify = existing.mJustify; mFontName = existing.mFontName; mFontSize = existing.mFontSize; mFontRotation = existing.mFontRotation; mCtm = new AffineTransform(existing.mCtm); mProjectionTransform = null; mWorldCtm = null; mScaling = existing.mScaling; mRotation = existing.mRotation; mDataset = existing.mDataset; /* * Only create variable lookup tables when some values are * defined locally. */ mVars = null; mLocalVars = null; /* * Don't copy path -- it can be large. * Just keep reference to existing path. * * Create path locally when needed. If path is referenced without * being created then we can reuse path from existing context instead. * * This saves unnecessary copying of paths when contexts are created. */ mPath = null; if (existing.mPath != null) mExistingPath = existing.mPath; else mExistingPath = existing.mExistingPath; /* * Copy list of paths we must clip against. */ if (existing.mClippingPaths != null) mClippingPaths = (ArrayList)(existing.mClippingPaths.clone()); else mClippingPaths = null; mOutputFormat = existing.mOutputFormat; mOutputDefined = false; /* * Save state in parent context so it won't be disturbed by anything * that gets changed in this new context. */ if (mOutputFormat != null) { mOutputFormat.saveState(); } mDatasetDefined = false; mAttributesPending = existing.mAttributesPending; mAttributesChanged = 0; mBlockName = blockName; } private GeometricPath getDefinedPath() { GeometricPath retval; /* * Return path defined in this context, or one defined * in previous context if nothing set here. */ if (mPath != null) retval = mPath; else retval = mExistingPath; return(retval); } /** * Return page width for output we are currently writing. * @return width in millimetres. */ public double getPageWidth() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageWidth(); return(retval); } /** * Return page height for output we are currently writing. * @return height in millimetres. */ public double getPageHeight() { double retval; if (mOutputFormat == null) retval = 0.0; else retval = mOutputFormat.getPageHeight(); return(retval); } /** * Return file format for output we are currently writing. * @return file format. */ public String getPageFormat() { String retval; if (mOutputFormat == null) retval = ""; else retval = mOutputFormat.getPageFormat(); return(retval); } /** * Return resolution of page we are writing to as a distance measurement. * @return distance in millimetres between centres of adjacent pixels. */ public double getResolution() throws MapyrusException { double retval; if (mOutputFormat == null) retval = Constants.MM_PER_INCH / DEFAULT_RESOLUTION; else retval = mOutputFormat.getResolution(); return(retval); } /** * Set graphics attributes (color, line width, etc.) if they * have changed since the last time we drew something. * @param attributeMask bit mask of attributes to set: ATTRIBUTE_*. */ private void setGraphicsAttributes(int attributeMask) throws IOException, MapyrusException { int maskComplement = (~attributeMask); if ((mAttributesPending & ATTRIBUTE_FONT & attributeMask) != 0) mOutputFormat.setFontAttribute(mFontName, mFontSize, mFontRotation); if ((mAttributesPending & ATTRIBUTE_JUSTIFY & attributeMask) != 0) mOutputFormat.setJustifyAttribute(mJustify); if ((mAttributesPending & ATTRIBUTE_COLOR & attributeMask) != 0) mOutputFormat.setColorAttribute(mColor); if ((mAttributesPending & ATTRIBUTE_LINESTYLE & attributeMask) != 0) mOutputFormat.setLinestyleAttribute(mLinestyle); if ((mAttributesPending & ATTRIBUTE_CLIP & attributeMask) != 0) mOutputFormat.setClipAttribute(mClippingPaths); /* * Clear attributes we've just set -- they are no longer pending. */ mAttributesPending = (mAttributesPending & maskComplement); } /** * Flag that graphics attributes have been changed by a call to a procedure. * @param attributes bit flags of attributes that are changed. */ public void setAttributesChanged(int attributes) { mAttributesPending |= attributes; mAttributesChanged |= attributes; } /** * Sets output file for drawing to. * @param filename name of image file output will be saved to. * @param format is image format for saving output. * @param width is the page width (in mm). * @param height is the page height (in mm). * @param extras contains extra settings for this output. * @param stdoutStream standard output stream for program. */ public void setOutputFormat(String format, String filename, double width, double height, String extras, PrintStream stdoutStream) throws IOException, MapyrusException { if (mOutputDefined && mOutputFormat != null) { /* * Finish any previous page before beginning a new one. */ mOutputFormat.closeOutputFormat(); } /* * Clear graphics context before beginning new page. */ initialiseContext(this); mOutputFormat = new OutputFormat(filename, format, width, height, extras, stdoutStream); mOutputDefined = true; } /** * Sets image for drawing to. * @param image is buffered image to draw into. * @param extras contains extra settings for this output. */ public void setOutputFormat(BufferedImage image, String extras) throws IOException, MapyrusException { if (mOutputDefined && mOutputFormat != null) { /* * Finish any previous page before beginning a new one. */ mOutputFormat.closeOutputFormat(); } /* * Clear graphics context before beginning new page. */ initialiseContext(this); mOutputFormat = new OutputFormat(image, extras); mOutputDefined = true; } /** * Closes a context. Any output started in this context is completed, * memory used for context is released. * A context cannot be used again after this call. * @return bit flag of graphical attributes that were changed in this context * and cannot be restored. */ public int closeContext() throws IOException, MapyrusException { boolean restoredState; if (mOutputFormat != null && !mOutputDefined) { /* * If state could be restored then no need for caller to set * graphical attributes back to their old values again. */ restoredState = mOutputFormat.restoreState(); if (restoredState) mAttributesChanged = 0; } if (mOutputDefined) { mOutputFormat.closeOutputFormat(); mOutputFormat = null; mOutputDefined = false; } /* * Close any dataset we opened in this context. */ if (mDatasetDefined) { mDataset.close(); } mDataset = null; mPath = mExistingPath = null; mClippingPaths = null; mVars = null; mLocalVars = null; return(mAttributesChanged); } /** * Sets linestyle. * @param width is width for lines in millimetres. * @param cap is a BasicStroke end cap value. * @param join is a BasicStroke line join value. * @param phase is offset at which pattern is started. * @param dashes list of dash pattern lengths. */ public void setLinestyle(double width, int cap, int join, double phase, float []dashes) { /* * Adjust width and dashes by current scaling factor. */ if (dashes == null) { mLinestyle = new BasicStroke((float)(width * mScaling), cap, join, MITER_LIMIT); } else { for (int i = 0; i < dashes.length; i++) dashes[i] *= mScaling; mLinestyle = new BasicStroke((float)(width * mScaling), cap, join, MITER_LIMIT, dashes, (float)phase); } mAttributesPending |= ATTRIBUTE_LINESTYLE; mAttributesChanged |= ATTRIBUTE_LINESTYLE; } /** * Gets current color. * @return current color. */ public Color getColor() { return(mColor); } /** * Sets color. * @param c is new color for drawing. */ public void setColor(Color color) { mColor = color; mAttributesPending |= ATTRIBUTE_COLOR; mAttributesChanged |= ATTRIBUTE_COLOR; } /** * Sets font for labelling with. * @param fontName is name of font as defined in java.awt.Font class. * @param fontSize is size for labelling in millimetres. */ public void setFont(String fontName, double fontSize) { mFontName = fontName; mFontSize = fontSize * mScaling; mFontRotation = mRotation; mAttributesChanged |= ATTRIBUTE_FONT; mAttributesPending |= ATTRIBUTE_FONT; } /** * Sets horizontal and vertical justification for labelling. * @param code is bit flags of JUSTIFY_* constant values for justification. */ public void setJustify(int code) { mJustify = code; mAttributesChanged |= ATTRIBUTE_JUSTIFY; mAttributesPending |= ATTRIBUTE_JUSTIFY; } /** * Sets scaling for subsequent coordinates. * @param factor is new scaling in X and Y axes. */ public void setScaling(double factor) { mCtm.scale(factor, factor); mScaling *= factor; } /** * Sets translation for subsequent coordinates. * @param x is new point for origin on X axis. * @param y is new point for origin on Y axis. */ public void setTranslation(double x, double y) { mCtm.translate(x, y); } /** * Sets rotation for subsequent coordinates. * @param angle is rotation angle in radians, measured counter-clockwise. */ public void setRotation(double angle) { mCtm.rotate(angle); mRotation += angle; mRotation = Math.IEEEremainder(mRotation, Math.PI * 2); } /** * Sets transformation from real world coordinates to page coordinates. * @param x1 minimum X world coordinate. * @param y1 minimum Y world coordinate. * @param x2 maximum X world coordinate. * @param y2 maximum Y world coordinate. * @param units units of world coordinates (WORLD_UNITS_METRES,WORLD_UNITS_FEET, etc.) */ public void setWorlds(double x1, double y1, double x2, double y2, int units) throws MapyrusException { double xDiff = x2 - x1; double yDiff = y2 - y1; double xMid, yMid; double worldAspectRatio = yDiff / xDiff; double pageAspectRatio; if (mOutputFormat == null) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_OUTPUT)); pageAspectRatio = mOutputFormat.getPageHeight() / mOutputFormat.getPageWidth(); /* * Expand world coordinate range in either X or Y axis so * it has same aspect ratio as page. */ if (worldAspectRatio > pageAspectRatio) { xMid = (x1 + x2) / 2.0; x1 = xMid - (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); x2 = xMid + (xDiff / 2.0) * (worldAspectRatio / pageAspectRatio); } else if (worldAspectRatio < pageAspectRatio) { /* * World coordinate range is wider than page coordinate system. * Expand Y axis range. */ yMid = (y1 + y2) / 2.0; y1 = yMid - (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); y2 = yMid + (yDiff / 2.0) * (pageAspectRatio / worldAspectRatio); } /* * Setup CTM from world coordinates to page coordinates. */ mWorldCtm = new AffineTransform(); mWorldCtm.scale(mOutputFormat.getPageWidth() / (x2 - x1), mOutputFormat.getPageHeight() / (y2 - y1)); mWorldCtm.translate(-x1, -y1); mWorldExtents = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); mWorldUnits = units; } /** * Sets reprojection between two world coordinate systems. * @param sourceSystem description of coordinate system coordinates transformed form. * @param destinationSystem description of coordinate system coordinates * are transformed to. */ public void setReprojection(String sourceSystem, String destinationSystem) throws MapyrusException { mProjectionTransform = new WorldCoordinateTransform(sourceSystem, destinationSystem); } /** * Set current dataset that can be queried and fetched from. * @param dataset opened dataset for subsequent queries. */ public void setDataset(GeographicDataset dataset) throws MapyrusException { /* * Clear any previous dataset defined in this context. */ if (mDataset != null && mDatasetDefined) mDataset.close(); mDataset = new Dataset(dataset); mDatasetDefined = true; } /** * Returns scaling factor in current transformation. * @return scale value. */ public double getScaling() { return(mScaling); } /** * Returns rotation angle in current transformation. * @return rotation in radians. */ public double getRotation() { return(mRotation); } /** * Returns world coordinate extents being shown on page. * @return rectangular area covered by extents. */ public Rectangle2D.Double getWorldExtents() throws MapyrusException { Rectangle2D.Double retval; if (mWorldExtents != null) { retval = mWorldExtents; } else if (mOutputFormat != null) { retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(); } return(retval); } /** * Return scale of world coordinates. The world coordinate range divided * by the page size. * @return scale, (1:2000) is returned as value 2000. */ public double getWorldScale() { double scale; double worldWidthInMM; if (mOutputFormat != null && mWorldCtm != null) { worldWidthInMM = mWorldExtents.width; if (mWorldUnits == WORLD_UNITS_METRES) worldWidthInMM *= 1000.0; else if (mWorldUnits == WORLD_UNITS_FEET) worldWidthInMM *= (1000.0 / 0.3048); else worldWidthInMM *= (110000 * 1000.0); scale = worldWidthInMM / mOutputFormat.getPageWidth(); } else { scale = 1.0; } return(scale); } /** * Returns bounding that when transformed through projection results * in same bounding box as current world coordinate system. * @return bounding box. */ public Rectangle2D.Double getUnprojectedExtents() throws MapyrusException { Rectangle2D.Double retval; double xMin, yMin, xMax, yMax; int i, j; double coords[] = new double[2]; xMin = yMin = Float.MAX_VALUE; xMax = yMax = Float.MIN_VALUE; if (mWorldExtents != null) { if (mProjectionTransform != null) { /* * Transform points around boundary of world coordinate extents * backwards through projection transformation. * Find minimum and maximum values. */ for (i = 0; i <= PROJECTED_GRID_STEPS; i++) { for (j = 0; j <= PROJECTED_GRID_STEPS; j++) { /* * Only transform points around boundary. */ if ((i == 0 || i == PROJECTED_GRID_STEPS) && (j == 0 || j == PROJECTED_GRID_STEPS)) { coords[0] = mWorldExtents.x + ((double)i / PROJECTED_GRID_STEPS) * mWorldExtents.width; coords[1] = mWorldExtents.y + ((double)j / PROJECTED_GRID_STEPS) * mWorldExtents.height; mProjectionTransform.backwardTransform(coords); if (coords[0] < xMin) xMin = coords[0]; if (coords[1] < yMin) yMin = coords[1]; if (coords[0] > xMax) xMax = coords[0]; if (coords[1] > yMax) yMax = coords[1]; } } } retval = new Rectangle2D.Double(xMin, yMin, xMax - xMin, yMax - yMin); } else { /* * No projection transformation set so just return plain world * coordinate extents. */ retval = mWorldExtents; } } else if (mOutputFormat != null) { /* * No world coordinate system set, just return page coordinate. */ retval = new Rectangle2D.Double(0, 0, mOutputFormat.getPageWidth(), mOutputFormat.getPageHeight()); } else { retval = new Rectangle2D.Double(0, 0, 1, 1); } return(retval); } /** * Get dataset currently being queried. * @return dataset being queried, or null if not dataset is being queried. */ public Dataset getDataset() { return(mDataset); } /** * Get name of procedure block containing statements currently being executed. * @return procedure block name, or null if outside of any procedure block. */ public String getBlockName() { return(mBlockName); } /** * Add point to path. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void moveTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); /* * Set no rotation for point. */ mPath.moveTo(dstPts[0], dstPts[1], 0.0f); } /** * Add point to path with straight line segment from last point. * @param x X coordinate to add to path. * @param y Y coordinate to add to path. */ public void lineTo(double x, double y) throws MapyrusException { double srcPts[] = new double[2]; float dstPts[] = new float[2]; srcPts[0] = x; srcPts[1] = y; /* * Make sure that a start point for path was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_MOVETO)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform point from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 1); mCtm.transform(srcPts, 0, dstPts, 0, 1); if (mPath == null) mPath = new GeometricPath(); mPath.lineTo(dstPts[0], dstPts[1]); } /** * Add point to path with straight line segment relative to last point. * @param x X coordinate distance to move, relative to last point. * @param y Y coordinate distance to move, relative to last point. */ public void rlineTo(double x, double y) throws MapyrusException { /* * Make sure that a previous point in path is defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_MOVETO)); try { /* * Calculate position of last point in path in current * coordinate system. */ Point2D currentPoint = mPath.getShape().getCurrentPoint(); /* * Transform back to current world coordinate system. */ // TODO should transform through mProjection too if it is not null. if (mWorldCtm != null) mWorldCtm.inverseTransform(currentPoint, currentPoint); mCtm.inverseTransform(currentPoint, currentPoint); /* * Work out absolute position, based on last point. Then draw * a line segment to that point. */ x += currentPoint.getX(); y += currentPoint.getY(); lineTo(x, y); } catch (NoninvertibleTransformException e) { /* * The matrix should always be invertible because we prevent * scaling by 0 -- the only way an AffineTransform can become singular. */ throw new MapyrusException(e.getMessage()); } } /** * Add circular arc to path from last point to a new point, given centre and direction. * @param direction positive for clockwise, negative for anti-clockwise. * @param xCentre X coordinate of centre point of arc. * @param yCentre Y coordinate of centre point of arc. * @param xEnd X coordinate of end point of arc. * @param yEnd Y coordinate of end point of arc. */ public void arcTo(int direction, double xCentre, double yCentre, double xEnd, double yEnd) throws MapyrusException { double centrePts[] = new double[2]; double endPts[] = new double[2]; float dstPts[] = new float[4]; centrePts[0] = xCentre; centrePts[1] = yCentre; endPts[0] = xEnd; endPts[1] = yEnd; /* * Make sure that a start point for arc was defined. */ if (mPath == null || mPath.getMoveToCount() == 0) throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NO_ARC_START)); /* * Transform to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(centrePts); mProjectionTransform.forwardTransform(endPts); } /* * Transform points from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) { mWorldCtm.transform(centrePts, 0, centrePts, 0, 1); mWorldCtm.transform(endPts, 0, endPts, 0, 1); } mCtm.transform(centrePts, 0, dstPts, 0, 1); mCtm.transform(endPts, 0, dstPts, 2, 1); mPath.arcTo(direction, dstPts[0], dstPts[1], dstPts[2], dstPts[3]); } /** * Clears currently defined path. */ public void clearPath() { /* * If a path was defined then clear it. * If no path then clear any path we are using from another * context too. */ if (mPath != null) mPath.reset(); else mExistingPath = null; } /** * Closes path back to last moveTo point. */ public void closePath() { if (mPath != null) { mPath.closePath(); } else if (mExistingPath != null) { mPath = new GeometricPath(mExistingPath); mPath.closePath(); } } /** * Replace path with regularly spaced points along it. * @param spacing is distance between points. * @param offset is starting offset of first point. */ public void samplePath(double spacing, double offset) throws MapyrusException { GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path != null) { mPath = path.samplePath(spacing * mScaling, offset * mScaling, resolution); } } /** * Replace path defining polygon with parallel stripe * lines covering the polygon. * @param spacing is distance between stripes. * @param angle is angle of stripes, in radians, with zero horizontal. */ public void stripePath(double spacing, double angle) { GeometricPath path = getDefinedPath(); if (path != null) mPath = path.stripePath(spacing * mScaling, angle); } /** * Replace path defining polygon with a sinkhole point. */ public void createSinkhole() { GeometricPath path = getDefinedPath(); if (path != null) { Point2D pt = Sinkhole.calculate(path.getShape()); mPath = new GeometricPath(); mPath.moveTo((float)pt.getX(), (float)pt.getY(), 0); } } /** * Replace path defining polygon with a sinkhole point. */ public void guillotine(double x1, double y1, double x2, double y2) throws MapyrusException { GeometricPath path = getDefinedPath(); if (path != null) { double srcPts[] = new double[4]; float dstPts[] = new float[6]; srcPts[0] = x1; srcPts[1] = y1; srcPts[2] = x2; srcPts[3] = y2; /* * Transform rectangle to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform rectangle from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 2); mCtm.transform(srcPts, 0, dstPts, 0, 2); double resolution = getResolution(); x1 = Math.min(dstPts[0], dstPts[2]); y1 = Math.min(dstPts[1], dstPts[3]); x2 = Math.max(dstPts[0], dstPts[2]); y2 = Math.max(dstPts[1], dstPts[3]); Rectangle2D.Double rect = new Rectangle2D.Double(x1, y1, x2 - x1, y2 - y1); /* * If path is made up of only move points then keep those * that fall inside rectangle. */ if (path.getLineToCount() == 0 && path.getMoveToCount() > 0) { ArrayList moveTos = path.getMoveTos(); ArrayList moveToRotations = path.getMoveToRotations(); mPath = new GeometricPath(); for (int i = 0; i < moveTos.size(); i++) { Point2D.Float pt = (Point2D.Float)(moveTos.get(i)); if (rect.outcode(pt) == 0) { Double rotation = (Double)(moveToRotations.get(i)); mPath.moveTo(pt.x, pt.y, rotation.doubleValue()); } } return; } /* * Return immediately if shape is completely inside or outside * clip rectangle. */ GeneralPath s = path.getShape(); Rectangle2D bounds = s.getBounds2D(); if (rect.contains(bounds)) return; if (!rect.intersects(bounds)) { mPath = new GeometricPath(); return; } GeneralPath p = SutherlandHodgman.clip(s, rect, resolution); /* * Copy clipped path back to current path. */ if (mPath == path) mPath.reset(); else mPath = new GeometricPath(); float []coords = dstPts; PathIterator pi = p.getPathIterator(Constants.IDENTITY_MATRIX); while (!pi.isDone()) { int segmentType = pi.currentSegment(coords); if (segmentType == PathIterator.SEG_MOVETO) mPath.moveTo(coords[0], coords[1], 0); else if (segmentType == PathIterator.SEG_LINETO) mPath.lineTo(coords[0], coords[1]); else if (segmentType == PathIterator.SEG_CLOSE) mPath.closePath(); pi.next(); } } } /** * Set rectangular area in page mask toa value. * @param x1 lower-left corner of rectangle. * @param y1 lower-left corner of rectangle. * @param x2 upper-right corner of rectangle. * @param y2 upper-right corner of rectangle. * @param maskValue value to set in mask for rectangular area. */ public void setPageMask(double x1, double y1, double x2, double y2, int maskValue) throws MapyrusException { double srcPts[] = new double[4]; float dstPts[] = new float[6]; srcPts[0] = x1; srcPts[1] = y1; srcPts[2] = x2; srcPts[3] = y2; /* * Transform rectangle to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform rectangle from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 2); mCtm.transform(srcPts, 0, dstPts, 0, 2); if (mOutputFormat != null) { /* * Get mask for this page and mark area as protected/unprotected. */ PageMask pageMask = mOutputFormat.getPageMask(); pageMask.setValue(Math.round(dstPts[0]), Math.round(dstPts[1]), Math.round(dstPts[2]), Math.round(dstPts[3]), maskValue); } } public boolean isPageMaskAllZero(double x1, double y1, double x2, double y2) throws MapyrusException { boolean retval = true; if (mOutputFormat != null) { double srcPts[] = new double[4]; float dstPts[] = new float[4]; srcPts[0] = x1; srcPts[1] = y1; srcPts[2] = x2; srcPts[3] = y2; /* * Transform rectangle to correct world coordinate system. */ if (mProjectionTransform != null) { mProjectionTransform.forwardTransform(srcPts); } /* * Transform rectangle from world coordinates * to millimetre position on page. */ if (mWorldCtm != null) mWorldCtm.transform(srcPts, 0, srcPts, 0, 2); mCtm.transform(srcPts, 0, dstPts, 0, 2); /* * Get mask for this page and check whether area is protected. */ PageMask pageMask = mOutputFormat.getPageMask(); retval = pageMask.isAllZero(Math.round(dstPts[0]), Math.round(dstPts[1]), Math.round(dstPts[2]), Math.round(dstPts[3])); } return(retval); } /** * Shift all coordinates in path shifted by a fixed amount. * @param xShift distance in millimetres to shift X coordinate values. * @param yShift distance in millimetres to shift Y coordinate values. */ public void translatePath(double xShift, double yShift) { GeometricPath path = getDefinedPath(); double coords[] = new double[2]; coords[0] = xShift; coords[1] = yShift; /* * Scale and rotate shift to current transformation matrix. */ if (!mCtm.isIdentity()) { AffineTransform at = AffineTransform.getRotateInstance(mRotation); at.scale(mScaling, mScaling); at.transform(coords, 0, coords, 0, 1); } if (path != null) mPath = path.translatePath(coords[0], coords[1]); } /** * Draw image icon at current point on path. * @param icon icon to draw. * @param size size for icon in millimetres. */ public void drawIcon(ImageIcon icon, double size) throws IOException, MapyrusException { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_CLIP); mOutputFormat.drawIcon(path.getMoveTos(), icon, size, mRotation, mScaling); } } /** * Draw currently defined path. */ public void stroke() throws IOException, MapyrusException { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_LINESTYLE|ATTRIBUTE_CLIP); mOutputFormat.stroke(path.getShape()); } } /** * Fill currently defined path. */ public void fill() throws IOException, MapyrusException { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_CLIP); mOutputFormat.fill(path.getShape()); } } /** * Clip to show only area outside currently defined path, * protecting what is inside path. */ public void clipOutside() throws MapyrusException { GeometricPath path = getDefinedPath(); GeometricPath protectedPath; if (path != null && mOutputFormat != null) { /* * Add a rectangle around the edge of the page as the new polygon * perimeter. The path becomes an island in the polygon (with * opposite direction so winding rule works) and only * the area outside the path is then visible. */ float width = (float)(mOutputFormat.getPageWidth()); float height = (float)(mOutputFormat.getPageHeight()); protectedPath = new GeometricPath(); protectedPath.moveTo(0.0f, 0.0f, 0.0); if (path.isClockwise(getResolution())) { /* * Outer rectange should be anti-clockwise. */ protectedPath.lineTo(width, 0.0f); protectedPath.lineTo(width, height); protectedPath.lineTo(0.0f, height); } else { /* * Outer rectangle should be clockwise. */ protectedPath.lineTo(0.0f, height); protectedPath.lineTo(width, height); protectedPath.lineTo(width, 0.0f); } protectedPath.closePath(); protectedPath.append(path, false); mAttributesPending |= ATTRIBUTE_CLIP; mAttributesChanged |= ATTRIBUTE_CLIP; mOutputFormat.clip(protectedPath.getShape()); /* * Add this polygon to list of paths we are clipping against. */ if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(protectedPath); } } /** * Clip to show only inside of currently defined path. */ public void clipInside() { GeometricPath path = getDefinedPath(); GeometricPath clipPath; if (path != null && mOutputFormat != null) { clipPath = new GeometricPath(path); if (mClippingPaths == null) mClippingPaths = new ArrayList(); mClippingPaths.add(clipPath); mAttributesPending |= ATTRIBUTE_CLIP; mAttributesChanged |= ATTRIBUTE_CLIP; if (mOutputFormat != null) { mOutputFormat.clip(clipPath.getShape()); } } } /** * Draw label positioned at (or along) currently defined path. * @param label is string to draw on page. */ public void label(String label) throws IOException, MapyrusException { GeometricPath path = getDefinedPath(); if (path != null && mOutputFormat != null) { setGraphicsAttributes(ATTRIBUTE_COLOR|ATTRIBUTE_FONT|ATTRIBUTE_JUSTIFY|ATTRIBUTE_CLIP); mOutputFormat.label(path.getMoveTos(), label); } } /** * Returns the number of moveTo's in path defined in this context. * @return count of moveTo calls made. */ public int getMoveToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getMoveToCount(); return(retval); } /** * Returns the number of lineTo's in path defined in this context. * @return count of lineTo calls made for this path. */ public int getLineToCount() { int retval; GeometricPath path = getDefinedPath(); if (path == null) retval = 0; else retval = path.getLineToCount(); return(retval); } /** * Returns geometric length of current path. * @return length of current path. */ public double getPathLength() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getLength(resolution); return(retval); } /** * Returns geometric area of current path. * @return area of current path. */ public double getPathArea() throws MapyrusException { double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = 0.0; else retval = path.getArea(resolution); return(retval); } /** * Returns geometric centroid of current path. * @return centroid of current path. */ public Point2D.Double getPathCentroid() throws MapyrusException { Point2D.Double retval; GeometricPath path = getDefinedPath(); double resolution = getResolution(); if (path == null) retval = new Point2D.Double(); else retval = path.getCentroid(resolution); return(retval); } /** * Returns rotation angle for each each moveTo point in current path * @return array of rotation angles relative to rotation in current * transformation matrix. */ public ArrayList getMoveToRotations() { ArrayList retval; GeometricPath path = getDefinedPath(); if (path == null) retval = null; else retval = path.getMoveToRotations(); return(retval); } /** * Returns coordinate for each each moveTo point in current path. * @return array of Point2D.Float objects relative to current transformation matrix. */ public ArrayList getMoveTos() throws MapyrusException { ArrayList retval = null; GeometricPath path = getDefinedPath(); AffineTransform inverse; ArrayList moveTos; try { if (path != null) { /* * If there is no transformation matrix then we can return original * coordinates, otherwise we must convert all coordinates to be relative * to the current transformation matrix and build a new list. */ if (mCtm.isIdentity()) { retval = path.getMoveTos(); } else { inverse = mCtm.createInverse(); moveTos = path.getMoveTos(); retval = new ArrayList(moveTos.size()); for (int i = 0; i < moveTos.size(); i++) { Point2D.Float pt = (Point2D.Float)(moveTos.get(i)); retval.add(inverse.transform(pt, null)); } } } } catch (NoninvertibleTransformException e) { throw new MapyrusException(e.getMessage()); } return(retval); } /** * Returns bounding box of this geometry. * @return bounding box, or null if no path is defined. */ public Rectangle2D getBounds2D() { Rectangle2D bounds; GeometricPath path = getDefinedPath(); if (path == null) bounds = null; else bounds = path.getBounds2D(); return(bounds); } /** * Returns value of a variable. * @param variable name to lookup. * @return value of variable, or null if it is not defined. */ public Argument getVariableValue(String varName) { Argument retval; /* * Variable is not set if no lookup table is defined. */ if (mVars == null) retval = null; else retval = (Argument)mVars.get(varName); return(retval); } /** * Indicates that a variable is to be stored locally in this context * and not be made available to other contexts. * @param varName name of variable to be treated as local. */ public void setLocalScope(String varName) { /* * Record that variable is local. */ if (mLocalVars == null) mLocalVars = new HashSet(); mLocalVars.add(varName); } /** * Returns true if variable has been defined local in this context * with @see setLocalScope(). * @param varName is name of variable to check. * @return true if variable defined local. */ public boolean hasLocalScope(String varName) { return(mLocalVars != null && mLocalVars.contains(varName)); } /** * Define variable in current context, replacing any existing * variable with the same name. * @param varName name of variable to define. * @param value is value for this variable */ public void defineVariable(String varName, Argument value) { /* * Create new variable. */ if (mVars == null) mVars = new HashMap(); /* * Clone hashmap variables to avoid changes to entries * in one variable being visible to others. */ if (value.getType() == Argument.HASHMAP) value = (Argument)value.clone(); mVars.put(varName, value); } /** * Define an key-value entry in a hashmap in current context, * replacing any existing entry with the same key. * @param hashMapName name of hashmap to add entry to. * @param key is key to add. * @param value is value to add. */ public void defineHashMapEntry(String hashMapName, String key, Argument value) { if (mVars == null) mVars = new HashMap(); /* * Create new entry in a hash map. */ Argument arg = (Argument)mVars.get(hashMapName); if (arg == null || arg.getType() != Argument.HASHMAP) { /* * No hash map with this name used before, * create new one. */ arg = new Argument(); mVars.put(hashMapName, arg); } arg.addHashMapEntry(key, value); } /** * Returns dimensions of a string, drawn to current page with current font. * @param s string to calculate height and width for. * @return height and width of string in millimetres. */ public StringDimension getStringDimension(String s) throws IOException, MapyrusException { StringDimension retval; if (mOutputFormat != null) { /* * Make sure current font is set *and* pass current font * to stringWidth calculation as some output formats set * the font and then forget it. */ setGraphicsAttributes(ATTRIBUTE_FONT); retval = mOutputFormat.getStringDimension(s, mFontName, mFontSize); retval.setSize(retval.getWidth() / mScaling, retval.getHeight() / mScaling); } else { /* * Not possible to accurately calculate width if no page defined. */ retval = new StringDimension(); } return(retval); } }
package mjc.analysis; import mjc.node.EOF; import mjc.node.Node; import mjc.node.Start; import mjc.node.Token; /** * Simple visitor to print AST to standard output. */ public class ASTPrinter extends DepthFirstAdapter { private int indent; // Indentation level. private StringBuilder builder; // Builder for the output. public void print(Start tree) { tree.apply(this); } @Override public void inStart(Start node) { indent = 0; builder = new StringBuilder(); } @Override public void outStart(Start node) { System.out.print(builder.toString()); } @Override public void defaultIn(final Node node) { indent(); builder.append(node.getClass().getSimpleName() + '\n'); indent += 2; } @Override public void defaultOut(final Node node) { indent -= 2; } @Override public void defaultCase(Node node) { if (node instanceof EOF) return; indent(); Token token = (Token) node; String name = token.getClass().getSimpleName(); String text = token.getText(); builder.append(String.format("%s(%s)\n", name, text)); } private void indent() { for (int i = 0; i < indent; ++i) builder.append(' '); } }
package org.mockito; import java.util.Arrays; import org.mockito.exceptions.Reporter; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.internal.MockHandler; import org.mockito.internal.progress.MockingProgress; import org.mockito.internal.progress.OngoingStubbing; import org.mockito.internal.progress.ThreadSafeMockingProgress; import org.mockito.internal.progress.VerificationMode; import org.mockito.internal.progress.VerificationModeImpl; import org.mockito.internal.stubbing.Returns; import org.mockito.internal.stubbing.ReturnsVoid; import org.mockito.internal.stubbing.Stubber; import org.mockito.internal.stubbing.StubberImpl; import org.mockito.internal.stubbing.ThrowsException; import org.mockito.internal.stubbing.VoidMethodStubbable; import org.mockito.internal.util.MockUtil; import org.mockito.stubbing.Answer; @SuppressWarnings("unchecked") public class Mockito extends Matchers { private Mockito() {} private static final Reporter REPORTER = new Reporter(); static final MockingProgress MOCKING_PROGRESS = new ThreadSafeMockingProgress(); /** * Creates mock object of given class or interface. * <p> * * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock) { return mock(classToMock, null); } /** * Creates mock with a name. Naming mocks can be helpful for debugging. * Remember that naming mocks is not a solution for complex test/code which uses too many mocks. * <p> * If you use &#064;Mock annotation then you've got naming mocks for free. &#064;Mock uses field name as mock name. * <p> * * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock, String name) { return MockUtil.createMock(classToMock, MOCKING_PROGRESS, name, null); } /** * Creates a spy of the real object. Example: * * <pre> * List list = new LinkedList(); * List spy = Mockito.spy(list); * * //optionally, you can stub out some methods: * stub(spy.size()).toReturn(100); * * //using the spy calls <b>real</b> methods * spy.add("one"); * spy.add("two"); * * //prints "one" - the first element of a list * System.out.println(spy.get(0)); * * //size() method was stubbed - 100 is printed * System.out.println(spy.size()); * * //optionally, you can verify * verify(spy).add("one"); * verify(spy).add("two"); * </pre> * * <h3>IMPORTANT</h3> * * Sometimes it's impossible to use {@link Mockito#stub(Object)} for stubbing spies. Example: * * <pre> * List list = new LinkedList(); * List spy = Mockito.spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * stub(spy.get(0)).toReturn("foo"); * * //You have to use doReturn() for stubbing * doReturn("foo").when(spy).get(0); * </pre> * * <p> * See examples in javadoc for {@link Mockito} class * * @param <T> * @param object * to spy on * @return a spy of the real object */ public static <T> T spy(T object) { return MockUtil.createMock((Class<T>) object.getClass(), MOCKING_PROGRESS, null, object); } @SuppressWarnings("unchecked") public static <T> OngoingStubbing<T> stub(T methodCall) { MOCKING_PROGRESS.stubbingStarted(); OngoingStubbing stubbable = MOCKING_PROGRESS.pullOngoingStubbing(); if (stubbable == null) { REPORTER.missingMethodInvocation(); } return stubbable; } public static <T> T verify(T mock) { return verify(mock, times(1)); } /** * Verifies certain behavior happened at least once / exact number of times / never. E.g: * <pre> * verify(mock, times(5)).someMethod("was called five times"); * * verify(mock, atLeastOnce()).someMethod("was called at least once"); * * //you can use flexible argument matchers, e.g: * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>); * </pre> * * <b>times(1) is the default</b> and can be omitted * <p> * See examples in javadoc for {@link Mockito} class * * @param mock to be verified * @param mode times(x), atLeastOnce() or never() * * @return mock object itself */ public static <T> T verify(T mock, VerificationMode mode) { if (mock == null) { REPORTER.nullPassedToVerify(); } else if (!MockUtil.isMock(mock)) { REPORTER.notAMockPassedToVerify(); } MOCKING_PROGRESS.verificationStarted(mode); return mock; } public static void verifyNoMoreInteractions(Object... mocks) { assertMocksNotEmpty(mocks); MOCKING_PROGRESS.validateState(); for (Object mock : mocks) { try { if (mock == null) { REPORTER.nullPassedToVerifyNoMoreInteractions(); } MockUtil.getMockHandler(mock).verifyNoMoreInteractions(); } catch (NotAMockException e) { REPORTER.notAMockPassedToVerifyNoMoreInteractions(); } } } /** * Verifies that no interactions happened on given mocks. * <pre> * verifyZeroInteractions(mockOne, mockTwo); * </pre> * * Instead of verifyZeroInteractions() you can call verifyNoMoreInteractions() but * the first one is more explicit and can read better. * <p> * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified */ public static void verifyZeroInteractions(Object... mocks) { verifyNoMoreInteractions(mocks); } private static void assertMocksNotEmpty(Object[] mocks) { if (mocks == null || mocks.length == 0) { REPORTER.mocksHaveToBePassedToVerifyNoMoreInteractions(); } } /** * Stubs void method with an exception. E.g: * * <pre> * stubVoid(mock).toThrow(new RuntimeException()).on().someMethod(); * * //you can stub with different behavior for consecutive calls. * //Last stubbing (e.g. toReturn()) determines the behavior for further consecutive calls. * stub(mock) * .toThrow(new RuntimeException()) * .toReturn() * .on().someMethod(); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param mock * to stub * @return stubbable object that allows stubbing with throwable */ public static <T> VoidMethodStubbable<T> stubVoid(T mock) { MockHandler<T> handler = MockUtil.getMockHandler(mock); MOCKING_PROGRESS.stubbingStarted(); return handler.voidMethodStubbable(mock); } /** * Sometimes you cannot stub using {@link Mockito#stub(Object)}. * <p> * When should you use doReturn() for stubbing? * <p> * 1. Overriding a previous exception-stubbing: * * <pre> * stub(mock.foo()).toThrow(new RuntimeException()); * * //Impossible: real method is called so mock.foo() throws RuntimeException * stub(mock.foo()).toReturn("bar"); * * //You have to use doReturn() for stubbing * doReturn("bar").when(mock).foo(); * </pre> * * 2. When spying real objects but calling real methods on a spy brings side effects * * <pre> * List list = new LinkedList(); * List spy = Mockito.spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * stub(spy.get(0)).toReturn("foo"); * * //You have to use doReturn() for stubbing * doReturn("foo").when(spy).get(0); * </pre> * * @param toBeReturned * @return */ public static Stubber doReturn(Object toBeReturned) { return doAnswer(new Returns(toBeReturned)); } public static Stubber doReturn() { return doAnswer(new ReturnsVoid()); } public static Stubber doThrow(Throwable toBeThrown) { return doAnswer(new ThrowsException(toBeThrown)); } public static Stubber doAnswer(Answer answer) { MOCKING_PROGRESS.stubbingStarted(); return new StubberImpl().doAnswer(answer); } /** * Creates InOrder object that allows verifying mocks in order. * * <pre> * InOrder inOrder = inOrder(firstMock, secondMock); * * inOrder.verify(firstMock).add("was called first"); * inOrder.verify(secondMock).add("was called second"); * </pre> * * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one * but only those that you are interested in testing in order. * <p> * Also, you can create InOrder object passing only mocks that relevant for in-order verification. * * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified in order * * @return InOrder object to be used to verify in order */ public static InOrder inOrder(Object... mocks) { if (mocks == null || mocks.length == 0) { REPORTER.mocksHaveToBePassedWhenCreatingInOrder(); } for (Object mock : mocks) { if (mock == null) { REPORTER.nullPassedWhenCreatingInOrder(); } else if (!MockUtil.isMock(mock)) { REPORTER.notAMockPassedWhenCreatingInOrder(); } } InOrder inOrderVerifier = new InOrderVerifier(Arrays.asList(mocks)); return inOrderVerifier; } /** * Allows at-least-once verification. E.g: * <pre> * verify(mock, atLeastOnce()).someMethod("some arg"); * </pre> * * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode atLeastOnce() { return VerificationModeImpl.atLeastOnce(); } /** * Allows verifying exact number of invocations. E.g: * <pre> * verify(mock, times(2)).someMethod("some arg"); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param wantedNumberOfInvocations wanted number of invocations * * @return verification mode */ public static VerificationMode times(int wantedNumberOfInvocations) { return VerificationModeImpl.times(wantedNumberOfInvocations); } /** * Alias to times(0), see {@link Mockito#times(int)} * <p> * Verifies that interaction did not happen * <pre> * verify(mock, never()).someMethod(); * </pre> * * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode never() { return times(0); } }
package org.cri.redmetrics; import java.io.IOException; import java.nio.file.Paths; import java.sql.SQLException; import org.cri.configurator.Config; import org.cri.configurator.Configs; import org.cri.redmetrics.db.Db; public class Main { public static void main(String[] args) throws SQLException { Config<String, String> config; String requiredOptions[] = {"databaseURL", "listenPort", "dbusername", "dbassword"}; try { config = Configs.getSimpleConfig(Paths.get("./redmetrics.conf"), requiredOptions); System.out.println("Using local redmetrics.conf"); } catch(IOException ioex) { try { config = Configs.getSimpleConfig(Paths.get("/etc/redmetrics.conf"), requiredOptions); System.out.println("Using /etc/redmetrics.conf"); } catch (IOException ex) { System.err.println("Error, missing redmetrics.conf"); return; } } Db db = new Db(config.get("databaseURL"), config.get("dbusername"), config.get("dbassword")); Server server = new Server(Integer.parseInt(config.get("listenPort")), db); server.start(); } }
package org.mockito; import org.mockito.internal.MockitoCore; import org.mockito.internal.progress.DeprecatedOngoingStubbing; import org.mockito.internal.progress.NewOngoingStubbing; import org.mockito.internal.returnvalues.EmptyReturnValues; import org.mockito.internal.returnvalues.GloballyConfiguredReturnValues; import org.mockito.internal.returnvalues.MockReturnValues; import org.mockito.internal.returnvalues.MoreEmptyReturnValues; import org.mockito.internal.returnvalues.RealReturnValues; import org.mockito.internal.returnvalues.SmartNullReturnValues; import org.mockito.internal.stubbing.Stubber; import org.mockito.internal.stubbing.VoidMethodStubbable; import org.mockito.internal.stubbing.answers.CallsRealMethod; import org.mockito.internal.stubbing.answers.DoesNothing; import org.mockito.internal.stubbing.answers.Returns; import org.mockito.internal.stubbing.answers.ThrowsException; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.internal.verification.api.VerificationMode; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @SuppressWarnings("unchecked") public class Mockito extends Matchers { private static final MockitoCore MOCKITO_CORE = new MockitoCore(); /** * Default ReturnValues used by the framework. * <p> * {@link ReturnValues} defines the return values of unstubbed invocations. * <p> * This implementation first tries the global configuration. * If there is no global configuration then it uses {@link EmptyReturnValues} (returns zeros, empty collections, nulls, etc.) */ public static final ReturnValues RETURNS_DEFAULTS = new GloballyConfiguredReturnValues(); /** * Optional ReturnValues to be used with {@link Mockito#mock(Class, ReturnValues)} * <p> * {@link ReturnValues} defines the return values of unstubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException. * This implementation of ReturnValues makes unstubbed methods <b>return SmartNull instead of null</b>. * SmartNull gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace. * <p> * SmartNullReturnValues first tries to return ordinary return values (see {@link MoreEmptyReturnValues}) * then it tries to return SmartNull. If the return type is final then plain null is returned. * <p> * SmartNullReturnValues will be probably the default return values strategy in Mockito 2.0 * <p> * Example: * <pre> * Foo mock = (Foo.class, RETURNS_SMART_NULLS); * * //calling unstubbed method here: * Stuff stuff = mock.getStuff(); * * //using object returned by unstubbed call: * stuff.doSomething(); * * //Above doesn't yield NullPointerException this time! * //Instead, SmartNullPointerException is thrown. * //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace. * </pre> */ public static final ReturnValues RETURNS_SMART_NULLS = new SmartNullReturnValues(); /** * Optional ReturnValues to be used with {@link Mockito#mock(Class, ReturnValues)} * <p> * {@link ReturnValues} defines the return values of unstubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * <p> * MockReturnValues first tries to return ordinary return values (see {@link MoreEmptyReturnValues}) * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain null is returned. * <p> */ public static final ReturnValues RETURNS_MOCKS = new MockReturnValues(); /** * TODO: THIS INTERFACE MIGHT CHANGE IN 1.8 * TODO: mention partial mocks warning * * Optional ReturnValues to be used with {@link Mockito#mock(Class, ReturnValues)} * <p> * {@link ReturnValues} defines the return values of unstubbed invocations. * <p> * This implementation can be helpful when working with legacy code. * When this implementation is used, unstubbed methods will delegate to the real implementation. * This is a way to create a partial mock object that calls real methods by default. * <p> * Example: * <pre> * Foo mock = mock(Foo.class, CALLS_REAL_METHODS); * * // this calls the real implementation of Foo.getSomething() * value = mock.getSomething(); * * when(mock.getSomething()).thenReturn(fakeValue); * * // now fakeValue is returned * value = mock.getSomething(); * </pre> */ public static final ReturnValues CALLS_REAL_METHODS = new RealReturnValues(); /** * Creates mock object of given class or interface. * <p> * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock) { return MOCKITO_CORE.mock(classToMock, null, null, RETURNS_DEFAULTS); } /** * Creates mock with a name. Naming mocks can be helpful for debugging. * <p> * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators. * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks. * <p> * <b>If you use &#064;Mock annotation then you've got naming mocks for free!</b> &#064;Mock uses field name as mock name. {@link Mock Read more.} * <p> * * See examples in javadoc for {@link Mockito} class * * @param classToMock class or interface to mock * @return mock object */ public static <T> T mock(Class<T> classToMock, String name) { return MOCKITO_CORE.mock(classToMock, name, null, RETURNS_DEFAULTS); } /** * Creates mock with a specified strategy for its return values. * It's quite advanced feature and typically you don't need it to write decent tests. * However it can be helpful for working with legacy systems. * <p> * Obviously return values are used only when you don't stub the method call. * * <pre> * Foo mock = mock(Foo.class, Mockito.RETURNS_SMART_NULLS); * Foo mockTwo = mock(Foo.class, new YourOwnReturnValues()); * </pre> * * <p>See examples in javadoc for {@link Mockito} class</p> * * @param classToMock class or interface to mock * @param returnValues default return values for unstubbed methods * * @return mock object */ public static <T> T mock(Class<T> classToMock, ReturnValues returnValues) { return MOCKITO_CORE.mock(classToMock, null, (T) null, returnValues); } /** * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed. * <p> * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code. * <p> * Spying on real objects is often associated with "partial mocking" concept. * However, Mockito spies are not partial mocks. Mockito spy is meant to help testing other classes - not the spy itself. * Therefore spy will not help if you intend to verify if method calls other method on the same object. * In this case I suggest being OO/SRPy (for example you might extract new class/interface...) * <p> * Example: * * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //optionally, you can stub out some methods: * when(spy.size()).thenReturn(100); * * //using the spy calls <b>real</b> methods * spy.add("one"); * spy.add("two"); * * //prints "one" - the first element of a list * System.out.println(spy.get(0)); * * //size() method was stubbed - 100 is printed * System.out.println(spy.size()); * * //optionally, you can verify * verify(spy).add("one"); * verify(spy).add("two"); * </pre> * * <h4>Important gotcha on spying real objects!</h4> * * 1. Sometimes it's impossible to use {@link Mockito#when(Object)} for stubbing spies. Example: * * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing * doReturn("foo").when(spy).get(0); * </pre> * * 2. Watch out for final methods. * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble. * What will happen is the real method will be called *on mock* but *not on the real instance* you passed to the spy() method. * Typically you may get a NullPointerException because mock instances don't have fields initiated. * * <p> * See examples in javadoc for {@link Mockito} class * * @param object * to spy on * @return a spy of the real object */ public static <T> T spy(T object) { return MOCKITO_CORE.mock((Class<T>) object.getClass(), null, object, RETURNS_DEFAULTS); } /** * <pre> * //Instead of: * stub(mock.count()).toReturn(10); * * //Please do: * when(mock.count()).thenReturn(10); * </pre> * * Many users found stub() confusing therefore stub() has been deprecated in favor of {@link Mockito#when(Object)} * <p> * How to fix deprecation warnings? Typically it's just few minutes of search & replace job: * <pre> * Mockito.stub; <i>replace with:</i> Mockito.when; * stub( <i>replace with:</i> when( * .toReturn( <i>replace with:</i> .thenReturn( * .toThrow( <i>replace with:</i> .thenThrow( * .toAnswer( <i>replace with:</i> .thenAnswer( * </pre> * If you're an existing user then sorry for making your code littered with deprecation warnings. * This change was required to make Mockito better. * * @param methodCall * method call * @return DeprecatedOngoingStubbing object to set stubbed value/exception */ @Deprecated public static <T> DeprecatedOngoingStubbing<T> stub(T methodCall) { return MOCKITO_CORE.stub(methodCall); } public static <T> NewOngoingStubbing<T> when(T methodCall) { return MOCKITO_CORE.when(methodCall); } public static <T> T verify(T mock) { return MOCKITO_CORE.verify(mock, times(1)); } public static <T> void reset(T ... mocks) { MOCKITO_CORE.reset(mocks); } /** * Verifies certain behavior happened at least once / exact number of times / never. E.g: * <pre> * verify(mock, times(5)).someMethod("was called five times"); * * verify(mock, atLeast(2)).someMethod("was called at least two times"); * * //you can use flexible argument matchers, e.g: * verify(mock, atLeastOnce()).someMethod(<b>anyString()</b>); * </pre> * * <b>times(1) is the default</b> and can be omitted * <p> * See examples in javadoc for {@link Mockito} class * * @param mock to be verified * @param mode times(x), atLeastOnce() or never() * * @return mock object itself */ public static <T> T verify(T mock, VerificationMode mode) { return MOCKITO_CORE.verify(mock, mode); } public static void verifyNoMoreInteractions(Object... mocks) { MOCKITO_CORE.verifyNoMoreInteractions(mocks); } /** * Verifies that no interactions happened on given mocks. * <pre> * verifyZeroInteractions(mockOne, mockTwo); * </pre> * This method will also detect invocations * that occurred before the test method, for example: in setUp(), &#064;Before method or in constructor. * Consider writing nice code that makes interactions only in test methods. * <p> * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified */ public static void verifyZeroInteractions(Object... mocks) { MOCKITO_CORE.verifyNoMoreInteractions(mocks); } /** * <pre> * //Instead of: * stubVoid(mock).toThrow(e).on().someVoidMethod(); * * //Please do: * doThrow(e).when(mock).someVoidMethod(); * </pre> * * doThrow() replaces stubVoid() because of improved readability and consistency with the family of doAnswer() methods. * <p> * Originally, stubVoid() was used for stubbing void methods with exceptions. E.g: * * <pre> * stubVoid(mock).toThrow(new RuntimeException()).on().someMethod(); * * //you can stub with different behavior for consecutive calls. * //Last stubbing (e.g. toReturn()) determines the behavior for further consecutive calls. * stubVoid(mock) * .toThrow(new RuntimeException()) * .toReturn() * .on().someMethod(); * </pre> * * See examples in javadoc for {@link Mockito} class * * @deprecated Use {@link Mockito#doThrow(Throwable)} method for stubbing voids * * @param mock * to stub * @return stubbable object that allows stubbing with throwable */ public static <T> VoidMethodStubbable<T> stubVoid(T mock) { return MOCKITO_CORE.stubVoid(mock); } /** * Use doThrow() when you want to stub the void method with an exception. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre> * doThrow(new RuntimeException()).when(mock).someVoidMethod(); * </pre> * * @param toBeThrown to be thrown when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doThrow(Throwable toBeThrown) { return MOCKITO_CORE.doAnswer(new ThrowsException(toBeThrown)); } /** * Use doCallRealMethod() when you want to call the real implementation of a method. * <p> * TODO: mention partial mocks warning * <p> * Example: * <pre> * Foo mock = mock(Foo.class); * doCallRealMethod().when(mock).someVoidMethod(); * * // this will call the real implementation of Foo.someVoidMethod() * mock.someVoidMethod(); * </pre> * * @return stubber - to select a method for stubbing */ public static Stubber doCallRealMethod() { return MOCKITO_CORE.doAnswer(new CallsRealMethod()); } /** * Use doAnswer() when you want to stub a void method with generic {@link Answer}. * <p> * Stubbing voids requires different approach from {@link Mockito#when(Object)} because the compiler does not like void methods inside brackets... * <p> * Example: * * <pre> * doAnswer(new Answer() { * public Object answer(InvocationOnMock invocation) { * Object[] args = invocation.getArguments(); * Mock mock = invocation.getMock(); * return null; * }}) * .when(mock).someMethod(); * </pre> * * @param answer to answer when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doAnswer(Answer answer) { return MOCKITO_CORE.doAnswer(answer); } /** * Use doNothing() for setting void methods to do nothing. <b>Beware that void methods on mocks do nothing by default!</b> * However, there are rare situations when doNothing() comes handy: * <p> * 1. Stubbing consecutive calls on a void method: * <pre> * doNothing(). * doThrow(new RuntimeException()) * .when(mock).someVoidMethod(); * * //does nothing the first time: * mock.someVoidMethod(); * * //throws RuntimeException the next time: * mock.someVoidMethod(); * </pre> * * 2. When you spy real objects and you want the void method to do nothing: * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //let's make clear() do nothing * doNothing().when(spy).clear(); * * spy.add("one"); * * //clear() does nothing, so the list still contains "one" * spy.clear(); * </pre> * * @return stubber - to select a method for stubbing */ public static Stubber doNothing() { return MOCKITO_CORE.doAnswer(new DoesNothing()); } /** * Use doReturn() in those rare occasions when you cannot use {@link Mockito#when(Object)}. * <p> * <b>Beware that {@link Mockito#when(Object)} is always recommended for stubbing because it is argument type-safe * and more readable</b> (especially when stubbing consecutive calls). * <p> * Here are those rare occasions when doReturn() comes handy: * <p> * * 1. When spying real objects and calling real methods on a spy brings side effects * * <pre> * List list = new LinkedList(); * List spy = spy(list); * * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty) * when(spy.get(0)).thenReturn("foo"); * * //You have to use doReturn() for stubbing: * doReturn("foo").when(spy).get(0); * </pre> * * 2. Overriding a previous exception-stubbing: * * <pre> * when(mock.foo()).thenThrow(new RuntimeException()); * * //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. * when(mock.foo()).thenReturn("bar"); * * //You have to use doReturn() for stubbing: * doReturn("bar").when(mock).foo(); * </pre> * * Above scenarios shows a tradeoff of Mockito's ellegant syntax. Note that the scenarios are very rare, though. * Spying should be sporadic and overriding exception-stubbing is very rare. * * @param toBeReturned to be returned when the stubbed method is called * @return stubber - to select a method for stubbing */ public static Stubber doReturn(Object toBeReturned) { return MOCKITO_CORE.doAnswer(new Returns(toBeReturned)); } /** * Creates InOrder object that allows verifying mocks in order. * * <pre> * InOrder inOrder = inOrder(firstMock, secondMock); * * inOrder.verify(firstMock).add("was called first"); * inOrder.verify(secondMock).add("was called second"); * </pre> * * Verification in order is flexible - <b>you don't have to verify all interactions</b> one-by-one * but only those that you are interested in testing in order. * <p> * Also, you can create InOrder object passing only mocks that are relevant for in-order verification. * * See examples in javadoc for {@link Mockito} class * * @param mocks to be verified in order * * @return InOrder object to be used to verify in order */ public static InOrder inOrder(Object... mocks) { return MOCKITO_CORE.inOrder(mocks); } /** * Allows verifying exact number of invocations. E.g: * <pre> * verify(mock, times(2)).someMethod("some arg"); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param wantedNumberOfInvocations wanted number of invocations * * @return verification mode */ public static VerificationMode times(int wantedNumberOfInvocations) { return VerificationModeFactory.times(wantedNumberOfInvocations); } /** * Alias to times(0), see {@link Mockito#times(int)} * <p> * Verifies that interaction did not happen. E.g: * <pre> * verify(mock, never()).someMethod(); * </pre> * * <p> * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode never() { return times(0); } /** * Allows at-least-once verification. E.g: * <pre> * verify(mock, atLeastOnce()).someMethod("some arg"); * </pre> * Alias to atLeast(1) * * See examples in javadoc for {@link Mockito} class * * @return verification mode */ public static VerificationMode atLeastOnce() { return VerificationModeFactory.atLeastOnce(); } /** * Allows at-least-x verification. E.g: * <pre> * verify(mock, atLeast(3)).someMethod("some arg"); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param minNumberOfInvocations minimum number of invocations * * @return verification mode */ public static VerificationMode atLeast(int minNumberOfInvocations) { return VerificationModeFactory.atLeast(minNumberOfInvocations); } /** * Allows at-most-x verification. E.g: * <pre> * verify(mock, atMost(3)).someMethod("some arg"); * </pre> * * See examples in javadoc for {@link Mockito} class * * @param maxNumberOfInvocations max number of invocations * * @return verification mode */ public static VerificationMode atMost(int maxNumberOfInvocations) { return VerificationModeFactory.atMost(maxNumberOfInvocations); } public static void validateMockitoUsage() { MOCKITO_CORE.validateMockitoUsage(); } }
package org.jenetics.util; import static java.lang.Math.min; import static org.jenetics.util.object.nonNull; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; import javolution.context.StackContext; import javolution.util.FastList; public final class Array<T> extends ArraySeq<T> implements MSeq<T>, RandomAccess { private static final long serialVersionUID = 2L; @SuppressWarnings("rawtypes") private static final Array EMPTY = new Array(0); /** * Return the empty array. * * @param <T> the element type. * @return empty array. */ @SuppressWarnings("unchecked") public static <T> Array<T> empty() { return (Array<T>)EMPTY; } Array(final ArrayRef array, final int start, final int end) { super(array, start, end); } /** * Create a new array with the given length. * * @param length the array length. * @throws NegativeArraySizeException if the specified {@code length} * is negative */ public Array(final int length) { super(length); } /** * Create a new array with length one. The array will be initialized with * the given value. * * @param first the only element of the array. */ public Array(final T first) { this(1); _array.data[0] = first; } /** * Create a new array with length two. The array will be initialized with * the given values. * * @param first first array element. * @param second second array element. */ public Array( final T first, final T second ) { this(2); _array.data[0] = first; _array.data[1] = second; } /** * Create a new array with length three. The array will be initialized with * the given values. * * @param first first array element. * @param second second array element. * @param third third array element. */ public Array( final T first, final T second, final T third ) { this(3); _array.data[0] = first; _array.data[1] = second; _array.data[2] = third; } /** * Create a new array with length four. The array will be initialized with * the given values. * * @param first first array element. * @param second second array element. * @param third third array element. * @param fourth fourth array element. */ public Array( final T first, final T second, final T third, final T fourth ) { this(4); _array.data[0] = first; _array.data[1] = second; _array.data[2] = third; _array.data[3] = fourth; } /** * Create a new array with length five. The array will be initialized with * the given values. * * @param first first array element. * @param second second array element. * @param third third array element. * @param fourth fourth array element. * @param fifth fifth array element. */ public Array( final T first, final T second, final T third, final T fourth, final T fifth ) { this(5); _array.data[0] = first; _array.data[1] = second; _array.data[2] = third; _array.data[3] = fourth; _array.data[4] = fifth; } /** * Create a new array from the given values. * * @param first first array element. * @param second second array element. * @param third third array element. * @param fourth fourth array element. * @param fifth fifth array element. * @param rest the rest of the array element. * @throws NullPointerException if the {@code rest} array is {@code null}. */ @SafeVarargs public Array( final T first, final T second, final T third, final T fourth, final T fifth, final T... rest ) { this(5 + rest.length); _array.data[0] = first; _array.data[1] = second; _array.data[2] = third; _array.data[3] = fourth; _array.data[4] = fifth; System.arraycopy(rest, 0, _array.data, 5, rest.length); } /** * Create a new array from the given values. * * @param values the array values. * @throws NullPointerException if the {@code values} array is {@code null}. */ public Array(final T[] values) { this(values.length); System.arraycopy(values, 0, _array.data, 0, values.length); } /** * Create a new Array from the values of the given Collection. The order of * the elements are determined by the iterator of the Collection. * * @param values the array values. * @throws NullPointerException if the {@code values} array is {@code null}. */ public Array(final Collection<? extends T> values) { this(values.size()); int index = 0; for (Iterator<? extends T> it = values.iterator(); it.hasNext(); ++index) { _array.data[index] = it.next(); } } /** * Selects all elements of this list which satisfy a predicate. * * @param predicate the predicate used to test elements. * @return a new array consisting of all elements of this list that satisfy * the given {@code predicate}. The order of the elements is * preserved. * @throws NullPointerException if the given {@code predicate} is * {@code null}. */ public Array<T> filter(final Function<? super T, Boolean> predicate) { StackContext.enter(); try { final FastList<T> filtered = FastList.newInstance(); for (int i = 0, n = length(); i < n; ++i) { @SuppressWarnings("unchecked") final T value = (T)_array.data[i + _start]; if (predicate.apply((T)value) == Boolean.TRUE) { filtered.add(value); } } final Array<T> copy = new Array<>(filtered.size()); int index = 0; for (FastList.Node<T> n = filtered.head(), end = filtered.tail(); (n = n.getNext()) != end;) { copy.set(index++, n.getValue()); } return copy; } finally { StackContext.exit(); } } @Override public void set(final int index, final T value) { checkIndex(index); _array.cloneIfSealed(); _array.data[index + _start] = value; } public void sort() { sort(0, length()); } public void sort(final int from, final int to) { sort(from, to, new Comparator<T>() { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public int compare(final T o1, final T o2) { return ((Comparable)o1).compareTo(o2); } }); } public void sort(final Comparator<? super T> comparator) { sort(0, length(), comparator); } public void sort( final int from, final int to, final Comparator<? super T> comparator ) { checkIndex(from, to); if (from > to) { throw new IllegalArgumentException(String.format( "From index > to index: %d > %d.", from, to )); } nonNull(comparator, "Comparator"); _array.cloneIfSealed(); quicksort(from, to - 1, comparator); } private void quicksort( final int left, final int right, final Comparator<? super T> comparator ) { if (right > left) { final int j = partition(left, right, comparator); quicksort(left, j - 1, comparator); quicksort(j + 1, right, comparator); } } @SuppressWarnings("unchecked") private int partition( final int left, final int right, final Comparator<? super T> comparator ) { final T pivot = (T)_array.data[left + _start]; int i = left; int j = right + 1; while (true) { do { ++i; } while ( i < right && comparator.compare((T)_array.data[i + _start], pivot) < 0 ); do { --j; } while ( j > left && comparator.compare((T)_array.data[j + _start], pivot) > 0 ); if (j <= i) { break; } uncheckedSwap(i, j); } uncheckedSwap(left, j); return j; } private void uncheckedSwap(final int i, final int j) { final Object temp = _array.data[i + _start]; _array.data[i + _start] = _array.data[j + _start]; _array.data[j + _start] = temp; } /** * Reverses the given array in place. */ public Array<T> reverse() { return reverse(0, length()); } public Array<T> reverse(final int from, final int to) { checkIndex(from, to); _array.cloneIfSealed(); int i = from; int j = to; while (i < j) { --j; uncheckedSwap(i, j); ++i; } return this; } public void swap(final int i, final int j) { checkIndex(i); checkIndex(j); _array.cloneIfSealed(); uncheckedSwap(i, j); } // public void swap(final Array<T> array, final int i, final int j) { @Override public Array<T> fill(final T value) { _array.cloneIfSealed(); for (int i = _start; i < _end; ++i) { _array.data[i] = value; } return this; } @Override public Array<T> fill(final Iterator<? extends T> it) { _array.cloneIfSealed(); for (int i = _start; i < _end && it.hasNext(); ++i) { _array.data[i] = it.next(); } return this; } @Override public Array<T> fill(final T[] values) { _array.cloneIfSealed(); System.arraycopy(values, 0, _array.data, _start, min(length(), values.length)); return this; } @Override public Array<T> fill(final Factory<? extends T> factory) { nonNull(factory); _array.cloneIfSealed(); for (int i = _start; i < _end; ++i) { _array.data[i] = factory.newInstance(); } return this; } @Override public ISeq<T> toISeq() { _array._sealed = true; return new ArrayISeq<>(new ArrayRef(_array.data), _start, _end); } /** * Create a new array which contains the values of {@code this} and the * given {@code value}. The length of the new array is * {@code this.length() + 1}. The returned array is not sealed. * * @param value the value to append to this array. * @return a new array which contains the values of {@code this} and the * given {@code value} */ public Array<T> append(final T value) { final Array<T> array = new Array<>(length() + 1); System.arraycopy(_array.data, _start, array._array.data, 0, length()); array._array.data[array.length() - 1] = value; return array; } /** * Create a new array which contains the values of {@code this} and the * given {@code array}. The length of the new array is * {@code this.length() + array.length()}. The returned array is not sealed. * * @param array the array to append to this array. * @return a new array which contains the values of {@code this} and the * given {@code array} * @throws NullPointerException if the {@code arrays} is {@code null}. */ public Array<T> append(final Array<? extends T> array) { final Array<T> appended = new Array<>(length() + array.length()); System.arraycopy( _array.data, _start, appended._array.data, 0, length() ); System.arraycopy( array._array.data, array._start, appended._array.data, length(), array.length() ); return appended; } /** * Create a new array which contains the values of {@code this} and the * given {@code values}. The length of the new array is * {@code this.length() + values.size()}. The returned array is not sealed. * * @param values the array to append to this array. * @return a new array which contains the values of {@code this} and the * given {@code array} * @throws NullPointerException if the {@code values} is {@code null}. */ public Array<T> append(final Collection<? extends T> values) { nonNull(values, "Values"); final Array<T> array = new Array<>(length() + values.size()); System.arraycopy(_array.data, _start, array._array.data, 0, length()); int index = length(); for (Iterator<? extends T> it = values.iterator(); it.hasNext(); ++index) { array._array.data[index] = it.next(); } return array; } /** * Create a new array with element type {@code B}. * * @param <B> the element type of the new array. * @param converter the array element converter. * @return a new array with element type {@code B}. * @throws NullPointerException if the element {@code converter} is * {@code null}. */ public <B> Array<B> map(final Function<? super T, ? extends B> converter) { nonNull(converter, "Converter"); final int length = length(); final Array<B> result = new Array<>(length); assert (result._array.data.length == length); for (int i = length; --i <= 0;) { @SuppressWarnings("unchecked") final T value = (T)_array.data[i + _start]; result._array.data[i] = converter.apply(value); } return result; } @Override public Array<T> copy() { return new Array<>(new ArrayRef(toArray()), 0, length()); } @Override public Array<T> subSeq(final int start, final int end) { checkIndex(start, end); return new Array<>(_array, start + _start, end + _start); } @Override public Array<T> subSeq(final int start) { return subSeq(start, length()); } @Override public List<T> asList() { return new ArrayMSeqList<>(this); } @Override public ListIterator<T> listIterator() { return new ArrayMSeqIterator<>(this); } }
package org.jpmml.lightgbm; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import org.dmg.pmml.DataType; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningFunction; import org.dmg.pmml.Predicate; import org.dmg.pmml.SimplePredicate; import org.dmg.pmml.True; import org.dmg.pmml.tree.CountingBranchNode; import org.dmg.pmml.tree.CountingLeafNode; import org.dmg.pmml.tree.Node; import org.dmg.pmml.tree.TreeModel; import org.jpmml.converter.BinaryFeature; import org.jpmml.converter.CategoricalFeature; import org.jpmml.converter.CategoryManager; import org.jpmml.converter.ContinuousFeature; import org.jpmml.converter.Feature; import org.jpmml.converter.ModelUtil; import org.jpmml.converter.PredicateManager; import org.jpmml.converter.Schema; import org.jpmml.converter.ValueUtil; public class Tree { private int num_leaves_; private int num_cat_; private int[] left_child_; private int[] right_child_; private int[] split_feature_real_; private double[] threshold_; private int[] decision_type_; private double[] leaf_value_; private int[] leaf_count_; private double[] internal_value_; private int[] internal_count_; private int[] cat_boundaries_; private long[] cat_threshold_; public void load(Section section){ this.num_leaves_ = section.getInt("num_leaves"); this.num_cat_ = section.getInt("num_cat"); if(this.num_leaves_ == 1){ this.leaf_value_ = section.getDoubleArray("leaf_value", this.num_leaves_); this.leaf_count_ = new int[]{0}; } else if(this.num_leaves_ > 1){ this.left_child_ = section.getIntArray("left_child", this.num_leaves_ - 1); this.right_child_ = section.getIntArray("right_child", this.num_leaves_ - 1); this.split_feature_real_ = section.getIntArray("split_feature", this.num_leaves_ - 1); this.threshold_ = section.getDoubleArray("threshold", this.num_leaves_ - 1); this.decision_type_ = section.getIntArray("decision_type", this.num_leaves_ - 1); this.leaf_value_ = section.getDoubleArray("leaf_value", this.num_leaves_); this.leaf_count_ = section.getIntArray("leaf_count", this.num_leaves_); this.internal_value_ = section.getDoubleArray("internal_value", this.num_leaves_ - 1); this.internal_count_ = section.getIntArray("internal_count", this.num_leaves_ - 1); } else { throw new IllegalArgumentException("Expected one or more leaves, got " + this.num_leaves_ + " leaves"); } // End if if(this.num_cat_ > 0){ this.cat_boundaries_ = section.getIntArray("cat_boundaries", this.num_cat_ + 1); this.cat_threshold_ = section.getUnsignedIntArray("cat_threshold", -1); } } public boolean isEmpty(){ return (this.num_leaves_ == 1); } public TreeModel encodeTreeModel(PredicateManager predicateManager, Schema schema){ Node root = encodeNode(0, True.INSTANCE, new CategoryManager(), predicateManager, schema); TreeModel treeModel = new TreeModel(MiningFunction.REGRESSION, ModelUtil.createMiningSchema(schema.getLabel()), root) .setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT) .setMissingValueStrategy(TreeModel.MissingValueStrategy.DEFAULT_CHILD); return treeModel; } public Node encodeNode(int index, Predicate predicate, CategoryManager categoryManager, PredicateManager predicateManager, Schema schema){ Integer id = Integer.valueOf(~index); // Non-leaf (aka internal) node if(!isEmpty() && (index >= 0)){ Feature feature = schema.getFeature(this.split_feature_real_[index]); double threshold_ = this.threshold_[index]; int decision_type_ = this.decision_type_[index]; CategoryManager leftCategoryManager = categoryManager; CategoryManager rightCategoryManager = categoryManager; Predicate leftPredicate; Predicate rightPredicate; boolean defaultLeft = hasDefaultLeftMask(decision_type_); if(feature instanceof BinaryFeature){ BinaryFeature binaryFeature = (BinaryFeature)feature; if(hasCategoricalMask(decision_type_)){ throw new IllegalArgumentException("Expected a false (off) categorical split mask for binary feature " + binaryFeature.getName() + ", got true (on)"); } // End if if(threshold_ != 0.5d){ throw new IllegalArgumentException("Expected 0.5 as a threshold value for binary feature " + binaryFeature.getName() + ", got " + threshold_); } Object value = binaryFeature.getValue(); leftPredicate = predicateManager.createSimplePredicate(binaryFeature, SimplePredicate.Operator.NOT_EQUAL, value); rightPredicate = predicateManager.createSimplePredicate(binaryFeature, SimplePredicate.Operator.EQUAL, value); } else if(feature instanceof BinaryCategoricalFeature){ BinaryCategoricalFeature binaryCategoricalFeature = (BinaryCategoricalFeature)feature; if(!hasCategoricalMask(decision_type_)){ throw new IllegalArgumentException("Expected a true (on) categorical split mask for binary categorical feature " + binaryCategoricalFeature.getName() + ", got false (off)"); } FieldName name = binaryCategoricalFeature.getName(); List<?> values = binaryCategoricalFeature.getValues(); int cat_idx = ValueUtil.asInt(threshold_); List<Object> leftValues = selectValues(false, values, Objects::nonNull, cat_idx, true); List<Object> rightValues = selectValues(false, values, Objects::nonNull, cat_idx, false); Object value = values.get(1); if(leftValues.size() == 0 && rightValues.size() == 1){ leftCategoryManager = leftCategoryManager; rightCategoryManager = rightCategoryManager.fork(name, rightValues); leftPredicate = predicateManager.createSimplePredicate(binaryCategoricalFeature, SimplePredicate.Operator.NOT_EQUAL, value); rightPredicate = predicateManager.createSimplePredicate(binaryCategoricalFeature, SimplePredicate.Operator.EQUAL, value); defaultLeft = true; } else if(leftValues.size() == 1 && rightValues.size() == 0){ leftCategoryManager = leftCategoryManager.fork(name, leftValues); rightCategoryManager = rightCategoryManager; leftPredicate = predicateManager.createSimplePredicate(binaryCategoricalFeature, SimplePredicate.Operator.EQUAL, value); rightPredicate = predicateManager.createSimplePredicate(binaryCategoricalFeature, SimplePredicate.Operator.NOT_EQUAL, value); defaultLeft = false; } else { throw new IllegalArgumentException("Neither left nor right branch is selectable"); } } else if(feature instanceof CategoricalFeature){ CategoricalFeature categoricalFeature = (CategoricalFeature)feature; if(!hasCategoricalMask(decision_type_)){ throw new IllegalArgumentException("Expected a true (on) categorical split mask for categorical feature " + categoricalFeature.getName() + ", got false (off)"); } FieldName name = categoricalFeature.getName(); boolean indexAsValue = (categoricalFeature instanceof DirectCategoricalFeature); List<?> values = categoricalFeature.getValues(); java.util.function.Predicate<Object> valueFilter = categoryManager.getValueFilter(name); int cat_idx = ValueUtil.asInt(threshold_); List<Object> leftValues = selectValues(indexAsValue, values, valueFilter, cat_idx, true); List<Object> rightValues = selectValues(indexAsValue, values, valueFilter, cat_idx, false); Set<?> parentValues = categoryManager.getValue(name); if(leftValues.size() == 0){ throw new IllegalArgumentException("Left branch is not selectable"); } // End if if(parentValues != null && rightValues.size() == parentValues.size()){ throw new IllegalArgumentException("Right branch is not selectable"); } leftCategoryManager = categoryManager.fork(name, leftValues); rightCategoryManager = categoryManager.fork(name, rightValues); leftPredicate = predicateManager.createPredicate(categoricalFeature, leftValues); if(rightValues.size() > 0){ rightPredicate = predicateManager.createPredicate(categoricalFeature, rightValues); } else { rightPredicate = True.INSTANCE; } defaultLeft = false; } else { ContinuousFeature continuousFeature = feature.toContinuousFeature(); if(hasCategoricalMask(decision_type_)){ throw new IllegalArgumentException("Expected a false (off) categorical split mask for continuous feature " + continuousFeature.getName() + ", got true (on)"); } Number value = threshold_; DataType dataType = continuousFeature.getDataType(); switch(dataType){ case INTEGER: if(value.doubleValue() == Tree.THRESHOLD_ZERO){ value = 0; } break; default: break; } leftPredicate = predicateManager.createSimplePredicate(continuousFeature, SimplePredicate.Operator.LESS_OR_EQUAL, value); rightPredicate = predicateManager.createSimplePredicate(continuousFeature, SimplePredicate.Operator.GREATER_THAN, value); } Node leftChild = encodeNode(this.left_child_[index], leftPredicate, leftCategoryManager, predicateManager, schema); Node rightChild = encodeNode(this.right_child_[index], rightPredicate, rightCategoryManager, predicateManager, schema); Node result = new CountingBranchNode(this.leaf_value_[index], predicate) .setId(id) .setDefaultChild(defaultLeft ? leftChild.getId() : rightChild.getId()) .setRecordCount(ValueUtil.narrow(this.internal_count_[index])) .addNodes(leftChild, rightChild); return result; } else // Leaf node { if(!isEmpty()){ index = ~index; } Node result = new CountingLeafNode(this.leaf_value_[index], predicate) .setId(id) .setRecordCount(ValueUtil.narrow(this.leaf_count_[index])); return result; } } private List<Object> selectValues(boolean indexAsValue, List<?> values, java.util.function.Predicate<Object> valueFilter, int cat_idx, boolean left){ List<Object> result; if(left){ result = new ArrayList<>(); } else { result = new ArrayList<>(values); } int n = (this.cat_boundaries_[cat_idx + 1] - this.cat_boundaries_[cat_idx]); for(int i = 0; i < n; i++){ for(int j = 0; j < 32; j++){ int cat = (i * 32) + j; if(findInBitset(this.cat_threshold_, this.cat_boundaries_[cat_idx], n, cat)){ Object value; if(indexAsValue){ value = cat; } else { value = values.get(cat); } // End if if(left){ result.add(value); } else { result.remove(value); } } } } result.removeIf(value -> !valueFilter.test(value)); return result; } Boolean isBinary(int feature){ Boolean result = null; if(isEmpty()){ return result; } for(int i = 0; i < this.split_feature_real_.length; i++){ if(this.split_feature_real_[i] == feature){ if(hasCategoricalMask(this.decision_type_[i])){ return Boolean.FALSE; } // End if if(this.threshold_[i] != 0.5d){ return Boolean.FALSE; } result = Boolean.TRUE; } } return result; } Boolean isCategorical(int feature){ Boolean result = null; if(isEmpty()){ return result; } for(int i = 0; i < this.split_feature_real_.length; i++){ if(this.split_feature_real_[i] == feature){ if(!hasCategoricalMask(this.decision_type_[i])){ return Boolean.FALSE; } result = Boolean.TRUE; } } return result; } static private boolean hasCategoricalMask(int decision_type){ return getDecisionType(decision_type, Tree.MASK_CATEGORICAL) == Tree.MASK_CATEGORICAL; } static private boolean hasDefaultLeftMask(int decision_type){ return getDecisionType(decision_type, Tree.MASK_DEFAULT_LEFT) == Tree.MASK_DEFAULT_LEFT; } static int getDecisionType(int decision_type, int mask){ return (decision_type & mask); } static int getMissingType(int decision_type){ return getDecisionType((decision_type >> 2), 3); } static private boolean findInBitset(long[] bits, int bitOffset, int n, int pos){ int i1 = pos / 32; if(i1 >= n){ return false; } int i2 = pos % 32; return ((bits[bitOffset + i1] >> i2) & 1) == 1; } private static final int MASK_CATEGORICAL = 1; private static final int MASK_DEFAULT_LEFT = 2; private static final double THRESHOLD_ZERO = 1.0000000180025095E-35; }