gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.internal.gosu.compiler.protocols.gosuclass;
import gw.fs.IFile;
import gw.internal.gosu.compiler.GosuClassLoader;
import gw.internal.gosu.compiler.SingleServingGosuClassLoader;
import gw.internal.gosu.parser.TypeLord;
import gw.internal.gosu.parser.java.compiler.JavaParser;
import gw.lang.javac.ClassJavaFileObject;
import gw.lang.javac.JavaCompileIssuesException;
import gw.lang.parser.ILanguageLevel;
import gw.lang.reflect.IHasJavaClass;
import gw.lang.reflect.IInjectableClassLoader;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.GosuClassPathThing;
import gw.lang.reflect.gs.ICompilableType;
import gw.lang.reflect.gs.IGosuProgram;
import gw.lang.reflect.gs.ISourceFileHandle;
import gw.lang.reflect.java.IJavaBackedType;
import gw.lang.reflect.java.IJavaType;
import gw.lang.reflect.module.IModule;
import gw.lang.reflect.module.TypeSystemLockHelper;
import gw.util.GosuExceptionUtil;
import gw.util.Pair;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
/**
*/
public class GosuClassesUrlConnection extends URLConnection {
private static final String[] JAVA_NAMESPACES_TO_IGNORE = {
"java/", "javax/", "sun/"
};
private static final String META_INF_MANIFEST_MF = "META-INF/MANIFEST.MF";
private ICompilableType _type;
private JavaFileObject _javaSrcFile;
private String _javaFqn;
private ClassLoader _loader;
private boolean _bDirectory;
private boolean _bInvalid;
public GosuClassesUrlConnection( URL url ) {
super( url );
}
@Override
public void connect() throws IOException {
if( _bInvalid ) {
throw new IOException();
}
connectImpl();
if( _bInvalid ) {
throw new IOException();
}
}
private boolean connectImpl() {
if( _bInvalid ) {
return false;
}
if( _type == null && _javaSrcFile == null && !_bDirectory ) {
String strPath = URLDecoder.decode( getURL().getPath() );
String strClass = strPath.substring( 1 );
if( isManifest( strClass ) ) {
// Some tools (Equinox) expect to find a jar manifest file in the path entry, so we fake an empty one here
return true;
}
if( !ignoreJavaClass( strClass ) ) {
String strType = strClass.replace( '/', '.' );
int iIndexClass = strType.lastIndexOf( ".class" );
if( iIndexClass > 0 ) {
strType = strType.substring( 0, iIndexClass );
maybeAssignGosuType( findClassLoader( getURL().getHost() ), strType );
}
else if( strPath.endsWith( "/" ) ) {
_bDirectory = true;
}
}
_bInvalid = _type == null && _javaSrcFile == null && !_bDirectory;
}
return !_bInvalid;
}
private boolean isManifest( String strClass ) {
return strClass.equalsIgnoreCase( META_INF_MANIFEST_MF );
}
private ClassLoader findClassLoader( String host ) {
int identityHash = Integer.parseInt( host );
ClassLoader loader = TypeSystem.getGosuClassLoader().getActualLoader();
while( loader != null ) {
if( System.identityHashCode( loader ) == identityHash ) {
return loader;
}
loader = loader.getParent();
}
throw new IllegalStateException( "Can't find ClassLoader with identity hash: " + identityHash );
}
private void maybeAssignGosuType( ClassLoader loader, String strType ) {
if( strType.contains( IGosuProgram.NAME_PREFIX + "eval_" ) ) {
// Never load an eval class here, they should always load in a single-serving loader
return;
}
TypeSystemLockHelper.getTypeSystemLockWithMonitor( loader );
try {
IModule global = TypeSystem.getGlobalModule();
IType type;
TypeSystem.pushModule( global );
try {
String gosuType = strType.replace( '$', '.' ); // gosu does not use '$' for inner class delimiter
type = TypeSystem.getByFullNameIfValidNoJava( gosuType );
if( ILanguageLevel.Util.STANDARD_GOSU() && (type == null || type instanceof IJavaType) ) {
// If there were a class file for the Java type on disk, it would have loaded by now (the gosuclass protocol is last).
// Therefore we compile and load the java class from the Java source file, eventually a JavaType based on the resulting class
// may load, if a source-based one hasn't already loaded.
try
{
Pair<JavaFileObject, String> pair = JavaParser.instance().findJavaSource( strType );
if( pair != null )
{
_javaSrcFile = pair.getFirst();
_javaFqn = strType;
_loader = loader;
}
}
catch( NoClassDefFoundError e )
{
// tools.jar likely not in the path...
System.out.println( "!! Unable to dynamically compile Java from source. tools.jar is missing from classpath." );
}
}
}
finally {
TypeSystem.popModule( global );
}
if( type instanceof ICompilableType ) {
if( !isInSingleServingLoader( type.getEnclosingType() ) ) {
if( !GosuClassPathThing.canWrapChain() ) {
if( !hasClassFileOnDiskInParentLoaderPath( loader, type ) ) {
_type = (ICompilableType)type;
_loader = loader;
}
}
else {
handleChainedLoading( loader, (ICompilableType)type );
}
}
}
}
catch( Exception e ) {
throw GosuExceptionUtil.forceThrow( e, "Type: " + strType );
}
finally {
TypeSystem.unlock();
}
}
//## hack: total hack to handle misconfigured classloaders where parent loader and child loader have overlapping paths
//## perf: this is probably not an insignificant perf issue while class loading i.e., the onslaught of ClassNotFoundExceptions handled here is puke worthy
private boolean hasClassFileOnDiskInParentLoaderPath( ClassLoader loader, IType type ) {
if( !(loader instanceof IInjectableClassLoader) ) {
return false;
}
ClassLoader parent = loader.getParent();
while( parent instanceof IInjectableClassLoader ) {
parent = parent.getParent();
}
IType outer = TypeLord.getOuterMostEnclosingClass( type );
try {
parent.loadClass( outer.getName() );
return true;
}
catch( ClassNotFoundException e ) {
return false;
}
}
private void handleChainedLoading( ClassLoader loader, ICompilableType type ) {
String ext = getFileExt( type );
if( ext == null ) {
// This is a program or some other intangible, make sure we load these in the base loader
if( loader == TypeSystem.getGosuClassLoader().getActualLoader() ||
type.getSourceFileHandle().isIncludeModulePath() ) {
_type = (ICompilableType)type;
_loader = loader;
}
}
else if( isResourceInLoader( loader, ext ) ) {
_type = (ICompilableType)type;
_loader = loader;
}
}
// private void crap( ICompilableType type, ClassLoader loader, String ext ) {
// System.out.println( "Loading: " + type.getName() + " ext: " + ext );
// System.out.println( "Source File: " + type.getSourceFileHandle().getFile() == null ? "none" : type.getSourceFileHandle().getFile().getPath().getFileSystemPathString() );
// System.out.println( "Module: " + type.getTypeLoader().getModule().getName() );
// System.out.println( "Current Loader: " + loader.getClass() );
// System.out.println( "Gosu Loader: " + TypeSystem.getGosuClassLoader().getActualLoader().getClass() );
// System.out.println( "Loader Chain from current: " + loaderChain( loader ) );
// if( ext != null ) {
// System.out.println( "Resource in loader?: " + isResourceInLoader( loader, ext ) );
// }
// }
private String loaderChain( ClassLoader loader ) {
if( loader == null ) {
return "<null>";
}
return loader.getClass().getName() + " -> " + loaderChain( loader.getParent() );
}
/**
* @param type a type that is dynamically compiled to bytecode from source by Gosu
* @return the corresponding file extension to replace the URL's .class extension when
* searching for the source file to compile. Otherwise if the type has no physical
* file or the file is not obtained from the classpath corresponding with a ClassLoader,
* returns null.
*/
private String getFileExt( ICompilableType type ) {
while( type instanceof ICompilableType ) {
ISourceFileHandle sfh = type.getSourceFileHandle();
IFile file = sfh.getFile();
if( file != null ) {
if( !sfh.isStandardPath() ) {
// The path is not in the target classpath of any ClassLoader e.g., it's added to Gosu's type sys repo in StandardEntityAccess#getAdditionalSourceRoots()
return null;
}
return '.' + file.getExtension();
}
type = type.getEnclosingType();
}
return null;
}
private static Method _findResource = null;
private boolean isResourceInLoader( ClassLoader loader, String ext ) {
String strPath = URLDecoder.decode( getURL().getPath() );
strPath = strPath.substring( 1 );
int iIndex = strPath.indexOf( "$" ); // Get the location of the top-level type (only one file for a nesting of types)
iIndex = iIndex < 0 ? strPath.lastIndexOf( ".class" ) : iIndex;
if( iIndex > 0 ) {
strPath = strPath.substring( 0, iIndex ) + ext;
}
if( loader instanceof URLClassLoader ) {
return ((URLClassLoader)loader).findResource( strPath ) != null;
}
else {
try {
if( _findResource == null ) {
_findResource = ClassLoader.class.getDeclaredMethod( "findResource", new Class[] {String.class} );
}
return _findResource.invoke( loader, strPath ) != null;
}
catch( Exception e ) {
throw new RuntimeException( e );
}
}
}
private boolean isInSingleServingLoader( IType type ) {
if( type instanceof IJavaBackedType ) {
return ((IJavaBackedType)type).getBackingClass().getClassLoader() instanceof SingleServingGosuClassLoader;
}
if( type instanceof IHasJavaClass ) {
return ((IHasJavaClass)type).getBackingClass().getClassLoader() instanceof SingleServingGosuClassLoader;
}
return false;
}
private boolean ignoreJavaClass( String strClass ) {
for( String namespace : JAVA_NAMESPACES_TO_IGNORE ) {
if( strClass.startsWith( namespace ) ) {
return true;
}
}
return false;
}
@Override
public InputStream getInputStream() throws IOException {
if( _type != null || _javaSrcFile != null ) {
// Avoid compiling until the bytes are actually requested;
// sun.misc.URLClassPath grabs the inputstream twice, the first time is for practice :)
return new LazyByteArrayInputStream();
}
else if( _bDirectory ) {
return new ByteArrayInputStream( new byte[0] );
}
else if( getURL().getPath().toUpperCase().endsWith( META_INF_MANIFEST_MF ) ) {
return new ByteArrayInputStream( new byte[0] );
}
throw new IOException( "Invalid or missing Gosu class for: " + url.toString() );
}
public boolean isValid() {
return connectImpl();
}
class LazyByteArrayInputStream extends InputStream {
protected byte _buf[];
protected int _pos;
protected int _mark;
protected int _count;
private void init() {
if( _buf == null ) {
TypeSystemLockHelper.getTypeSystemLockWithMonitor( _loader );
try {
//System.out.println( "Compiling: " + _type.getName() );
if( _type != null ) {
_buf = GosuClassLoader.instance().getBytes( _type );
}
else if( _javaSrcFile != null ) {
_buf = compileJavaClass();
}
_pos = 0;
_count = _buf.length;
}
catch( Throwable e ) {
logExceptionForFailedCompilation( e );
throw GosuExceptionUtil.forceThrow( e );
}
finally {
TypeSystem.unlock();
}
}
}
private void logExceptionForFailedCompilation( Throwable e )
{
// Log the exception, it tends to get swallowed esp. if the class doesn't parse.
//
// Note this is sometimes OK because the failure is recoverable. For example,
// a Gosu class references a Java class which in turn extends the Gosu class.
// Due the the circular reference at the header level, the Java compiler will
// fail to compile the Gosu class via this Url loader (because the Gosu class
// needs the Java class, which is compiling). In this case the DefaultTypeLoader
// catches the exception and generates a Java stub for the Gosu class and returns
// that as the definitive JavaClassInfo. Thus, we don't really want to log
// a nasty message here or print the stack trace, if it's recoverable.
//System.out.println( "!! Failed to compile: " + _type.getName() + " (don't worry, these are mostly recoverable, mostly)" );
//e.printStackTrace();
}
private byte[] compileJavaClass()
{
DiagnosticCollector<JavaFileObject> errorHandler = new DiagnosticCollector<>();
ClassJavaFileObject cls = JavaParser.instance().compile( _javaFqn, Arrays.asList( "-g", "-nowarn", "-Xlint:none", "-proc:none", "-parameters" ), errorHandler );
if( cls != null )
{
return cls.getBytes();
}
throw new JavaCompileIssuesException( errorHandler );
}
public int read() {
init();
return (_pos < _count) ? (_buf[_pos++] & 0xff) : -1;
}
@Override
public int read( byte[] b ) throws IOException {
init();
return super.read( b );
}
public int read( byte b[], int off, int len ) {
init();
if( b == null ) {
throw new NullPointerException();
}
else if( off < 0 || len < 0 || len > b.length - off ) {
throw new IndexOutOfBoundsException();
}
if( _pos >= _count ) {
return -1;
}
if( _pos + len > _count ) {
len = _count - _pos;
}
if( len <= 0 ) {
return 0;
}
System.arraycopy( _buf, _pos, b, off, len );
_pos += len;
return len;
}
public long skip( long n ) {
if( _pos + n > _count ) {
n = _count - _pos;
}
if( n < 0 ) {
return 0;
}
_pos += n;
return n;
}
public int available() {
init();
return _count - _pos;
}
public boolean markSupported() {
return true;
}
public void mark( int readAheadLimit ) {
_mark = _pos;
}
public void reset() {
_pos = _mark;
}
public void close() throws IOException {
}
}
}
| |
/*
* Copyright (c) 2007 BUSINESS OBJECTS SOFTWARE LIMITED
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Business Objects nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* RelativeDateValueNode.java
* Creation date: (04/06/01 10:48:36 AM)
* By: Michael Cheng
*/
package org.openquark.cal.valuenode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.openquark.cal.compiler.DataConstructor;
import org.openquark.cal.compiler.QualifiedName;
import org.openquark.cal.compiler.SourceModel;
import org.openquark.cal.compiler.TypeExpr;
import org.openquark.cal.compiler.io.InputPolicy;
import org.openquark.cal.compiler.io.OutputPolicy;
import org.openquark.cal.module.Cal.Utilities.CAL_RelativeTime;
import org.openquark.util.UnsafeCast;
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.util.Calendar;
/**
* A specialized AlgebraicValueNode to handle values of the CAL RelativeTime.RelativeDate type.
*
* Creation date: (04/06/01 10:48:36 AM)
* @author Michael Cheng
*/
public class RelativeDateValueNode extends RelativeTemporalValueNode {
/**
* A custom ValueNodeProvider for the RelativeDateValueNode.
* @author Frank Worsley
*/
public static class RelativeDateValueNodeProvider extends ValueNodeProvider<RelativeDateValueNode> {
public static final QualifiedName DATE_NAME = CAL_RelativeTime.TypeConstructors.RelativeDate;
public RelativeDateValueNodeProvider(ValueNodeBuilderHelper builderHelper) {
super(builderHelper);
}
/**
* @see org.openquark.cal.valuenode.ValueNodeProvider#getValueNodeClass()
*/
@Override
public Class<RelativeDateValueNode> getValueNodeClass() {
return RelativeDateValueNode.class;
}
/**
* {@inheritDoc}
*/
@Override
public RelativeDateValueNode getNodeInstance(Object value, DataConstructor dataConstructor, TypeExpr typeExpr) {
// Check for handleability.
if (!typeExpr.isNonParametricType(DATE_NAME)) {
return null;
}
return new RelativeDateValueNode((Date) value, typeExpr);
}
}
/**
* RelativeDateValueNode constructor.
* @param dateValue the value of this value node. If null current time will be used.
* @param typeExprParam the type expression of this value node. Must be of Date type.
*/
public RelativeDateValueNode(Date dateValue, TypeExpr typeExprParam) {
super(typeExprParam, dateValue);
checkTypeConstructorName(typeExprParam, RelativeDateValueNodeProvider.DATE_NAME);
}
@Override
public boolean containsParametricValue() {
return false;
}
/**
* Makes a copy of this ValueNode, but with another TypeExpr instance (of the same type).
* This is a deep copy, with respect to value nodes and the associated type expression.
* Note: if the new TypeExpr is a different type from the present TypeExpr, an error is thrown.
* Creation date: (06/07/01 8:43:30 AM)
* @param newTypeExpr the new type of the copied node.
* @return ValueNode
*/
@Override
public RelativeDateValueNode copyValueNode(TypeExpr newTypeExpr) {
checkCopyType(newTypeExpr);
return new RelativeDateValueNode(getDateValue(), newTypeExpr);
}
/**
* Returns the source model representation of the expression represented by
* this ValueNode.
*
* @return SourceModel.Expr
*/
@Override
public SourceModel.Expr getCALSourceModel() {
Calendar calendar = getCalendarValue();
int dateYear = calendar.get(Calendar.YEAR);
// Add 1 because Java's Date has month starting at 0.
int dateMonth = calendar.get(Calendar.MONTH) + 1;
int dateDay = calendar.get(Calendar.DAY_OF_MONTH);
return CAL_RelativeTime.Functions.makeRelativeDateValue(dateYear, dateMonth, dateDay);
}
/**
* Returns the Date value.
* Creation date: (13/06/01 2:29:17 PM)
* @return Date
*/
public Date getDateValue() {
return getJavaDate();
}
@Override
public Object getValue() {
return getDateValue();
}
/**
* Returns the display text representation of the expression represented by this ValueNode.
* @return String
*/
@Override
public String getTextValue() {
return getTextValue(DateFormat.FULL, -1);
}
/**
* Return an output policy which describes how to marshall a value represented
* by a value node from CAL to Java.
* @return - the output policy associated with the ValueNode instance.
*/
@Override
public OutputPolicy getOutputPolicy() {
return OutputPolicy.DEFAULT_OUTPUT_POLICY;
}
/**
* Set a value which is the result of the marshaller described by
* 'getOutputPolicy()'.
* @param value - the java value
*/
@Override
public void setOutputJavaValue(Object value) {
if (!(value instanceof List)) {
throw new IllegalArgumentException("Error in RelativeDateValueNode.setOutputJavaValue: output must be an instance of List, not an instance of: " + value.getClass().getName());
}
List<Integer> dateTuple = UnsafeCast.asTypeOf(value, Collections.<Integer>emptyList());
Calendar cal = getCalendarValue();
cal.set(Calendar.YEAR, (dateTuple.get(0)).intValue());
cal.set(Calendar.MONTH, (dateTuple.get(1)).intValue() - 1);
cal.set(Calendar.DAY_OF_MONTH, (dateTuple.get(2)).intValue());
setJavaDate(cal.getTime());
}
/**
* Return an input policy which describes how to marshall a value represented
* by a value node from Java to CAL.
* @return - the input policy associated with ValueNode instance.
*/
@Override
public InputPolicy getInputPolicy () {
return InputPolicy.makeTypedDefaultInputPolicy(getTypeExpr().toSourceModel().getTypeExprDefn());
}
/**
* Return an array of objects which are the values needed by the marshaller
* described by 'getInputPolicy()'.
* @return - an array of Java objects corresponding to the value represented by a value node instance.
*/
@Override
public Object[] getInputJavaValues() {
List<Integer> dateTuple = new ArrayList<Integer> (3); //(year, month, day)
Calendar calendarDateTime = getCalendarValue ();
dateTuple.add(Integer.valueOf(calendarDateTime.get(Calendar.YEAR)));
// Add 1 because Java's Date has month starting at 0.
dateTuple.add(Integer.valueOf(calendarDateTime.get(Calendar.MONTH) + 1));
dateTuple.add(Integer.valueOf(calendarDateTime.get(Calendar.DAY_OF_MONTH)));
return new Object[]{dateTuple};
}
}
| |
package org.jasig.openregistry.test.service;
import org.jasig.openregistry.test.domain.MockPerson;
import org.jasig.openregistry.test.domain.MockSorPerson;
import org.openregistry.core.domain.Person;
import org.openregistry.core.domain.PersonNotFoundException;
import org.openregistry.core.domain.sor.ReconciliationCriteria;
import org.openregistry.core.domain.sor.SorPerson;
import org.openregistry.core.domain.sor.SorPersonAlreadyExistsException;
import org.openregistry.core.domain.sor.SorRole;
import org.openregistry.core.service.PersonService;
import org.openregistry.core.service.SearchCriteria;
import org.openregistry.core.service.ServiceExecutionResult;
import org.openregistry.core.service.reconciliation.PersonMatch;
import org.openregistry.core.service.reconciliation.ReconciliationException;
import org.openregistry.core.service.reconciliation.ReconciliationResult;
import org.springframework.util.Assert;
import javax.validation.ConstraintViolation;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* @since 1.0
*/
public class MockPersonService implements PersonService {
private MockPerson providedMockPerson;
//Default ctor
public MockPersonService() {
}
public MockPersonService(MockPerson providedMockPerson) {
this.providedMockPerson = providedMockPerson;
}
@Override
public Person findPersonById(Long id) {
return this.providedMockPerson != null ? this.providedMockPerson : new MockPerson(-1000L);
}
@Override
public Person fetchCompleteCalculatedPerson(Long id) {
return this.providedMockPerson != null ? this.providedMockPerson : new MockPerson(-1000L);
}
@Override
public Person findPersonByIdentifier(String identifierType, String identifierValue) {
if (this.providedMockPerson.getIdentifiersByType().get(identifierType).getFirst().getValue().equals(identifierValue))
return providedMockPerson;
return null;
}
@Override
public SorPerson findByPersonIdAndSorIdentifier(Long id, String sourceSorIdentifier) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public SorPerson findBySorIdentifierAndSource(String sorSource, String sorId) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public SorPerson findByIdentifierAndSource(String identifierType, String identifierValue, String sorSource) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public List<SorPerson> findByIdentifier(String identifierType, String identifierValue) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<SorPerson> getSorPersonsFor(Person person) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public List<SorPerson> getSorPersonsFor(Long personId) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean deleteSystemOfRecordPerson(SorPerson sorPerson, boolean mistake, String terminationTypes) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean deleteSystemOfRecordPerson(String sorSource, String sorId, boolean mistake, String terminationTypes) throws PersonNotFoundException, IllegalArgumentException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean deleteSystemOfRecordRole(SorPerson sorPerson, SorRole sorRole, boolean mistake, String terminationTypes) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public ServiceExecutionResult<SorRole> validateAndSaveRoleForSorPerson(SorPerson sorPerson, final SorRole sorRole) throws IllegalArgumentException {
// Assert.notNull(sorPerson, "SorPerson cannot be null.");
// Assert.notNull(sorRole, "SorRole cannot be null.");
if(sorPerson ==null ||sorRole ==null )
throw new IllegalArgumentException();
return new ServiceExecutionResult<SorRole>() {
@Override
public Date getExecutionDate() {
return null;
}
@Override
public boolean succeeded() {
return true;
}
@Override
public SorRole getTargetObject() {
return sorRole;
}
@Override
public Set<ConstraintViolation> getValidationErrors() {
return null;
}
};
}
@Override
public ServiceExecutionResult<Person> validateAndSavePersonAndRole(ReconciliationCriteria reconciliationCriteria) throws IllegalArgumentException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ServiceExecutionResult<Person> addPerson(ReconciliationCriteria reconciliationCriteria) throws ReconciliationException, IllegalArgumentException {
return simulateAddingAPerson(reconciliationCriteria != null);
}
@Override
public ServiceExecutionResult<Person> forceAddPerson(ReconciliationCriteria reconciliationCriteria) throws IllegalArgumentException, IllegalStateException {
return simulateAddingAPerson(reconciliationCriteria != null);
}
@Override
public ServiceExecutionResult<Person> addPersonAndLink(ReconciliationCriteria reconciliationCriteria, Person person) throws IllegalArgumentException, IllegalStateException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public ServiceExecutionResult<ReconciliationResult> reconcile(ReconciliationCriteria reconciliationCriteria) throws IllegalArgumentException {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public List<PersonMatch> searchForPersonBy(SearchCriteria searchCriteria) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public ServiceExecutionResult<SorPerson> updateSorPerson(final SorPerson sorPerson) {
return new ServiceExecutionResult<SorPerson>() {
@Override
public Date getExecutionDate() {
return new Date();
}
@Override
public boolean succeeded() {
return sorPerson != null;
}
@Override
public SorPerson getTargetObject() {
if(sorPerson!=null){
MockSorPerson sorPerson = new MockSorPerson(-2000L);
sorPerson.setPersonId(providedMockPerson.getId());
return sorPerson;
}
return null;
}
@Override
public Set<ConstraintViolation> getValidationErrors() {
return Collections.emptySet();
}
};
}
@Override
public ServiceExecutionResult<SorRole> updateSorRole(SorPerson sorPerson,final SorRole sorRole) {
if(sorPerson ==null ||sorRole ==null )
throw new IllegalArgumentException();
return new ServiceExecutionResult<SorRole>() {
@Override
public Date getExecutionDate() {
return null;
}
@Override
public boolean succeeded() {
return true;
}
@Override
public SorRole getTargetObject() {
return sorRole;
}
@Override
public Set<ConstraintViolation> getValidationErrors() {
return null;
}
};
}
@Override
public boolean removeSorName(SorPerson sorPerson, Long nameId) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean moveAllSystemOfRecordPerson(Person fromPerson, Person toPerson) {
return moveSystemOfRecordPerson(fromPerson, toPerson, new MockSorPerson());
}
@Override
public boolean moveSystemOfRecordPerson(Person fromPerson, Person toPerson, SorPerson sorPerson) {
return true;
}
@Override
public boolean moveSystemOfRecordPersonToNewPerson(Person fromPerson, SorPerson sorPerson) {
sorPerson.setPersonId(fromPerson.getId());
return true;
}
@Override
public boolean expireRole(SorRole role) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public boolean renewRole(SorRole role) {
throw new UnsupportedOperationException("Not yet implemented");
}
private ServiceExecutionResult<Person> simulateAddingAPerson(final boolean successful) {
return new ServiceExecutionResult<Person>() {
@Override
public Date getExecutionDate() {
return new Date();
}
@Override
public boolean succeeded() {
return successful;
}
@Override
public Person getTargetObject() {
return providedMockPerson != null ? providedMockPerson : new MockPerson(-1000L);
}
@Override
public Set<ConstraintViolation> getValidationErrors() {
return Collections.emptySet();
}
};
}
}
| |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Linking this library statically or dynamically with other modules
* is making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give
* you permission to link this library with independent modules to
* produce an executable, regardless of the license terms of these
* independent modules, and to copy and distribute the resulting
* executable under terms of your choice, provided that you also meet,
* for each linked independent module, the terms and conditions of the
* license of that module. An independent module is a module which
* is not derived from or based on this library. If you modify this
* library, you may extend this exception to your version of the
* library, but you are not obligated to do so. If you do not wish
* to do so, delete this exception statement from your version.
*
* Project: github.com/rickyepoderi/wbxml-stream
*
*/
package es.rickyepoderi.wbxml.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
/**
* <p>Interface for read only XML Namespace context processing. </p>
*
* <p>An XML Namespace has the properties:</p>
*
* Namespace URI: Namespace name expressed as a URI to which the prefix is bound
* prefix: syntactically, this is the part of the attribute name following the
* XMLConstants.XMLNS_ATTRIBUTE ("xmlns") in the Namespace declaration
* example: <element xmlns:prefix="http://Namespace-name-URI">
*
* <p>All get*(*) methods operate in the current scope for Namespace URI and prefix
* resolution.</p>
*
* <p>Note that a Namespace URI can be bound to multiple prefixes in the current scope.
* This can occur when multiple XMLConstants.XMLNS_ATTRIBUTE ("xmlns") Namespace
* declarations occur in the same Start-Tag and refer to the same Namespace URI. e.g.</p>
*
* <pre>
* <element xmlns:prefix1="http://Namespace-name-URI"
* xmlns:prefix2="http://Namespace-name-URI"<
* </pre>
*
* <p>This can also occur when the same Namespace URI is used in multiple
* XMLConstants.XMLNS_ATTRIBUTE ("xmlns") Namespace declarations in the logical
* parent element hierarchy. e.g.</p>
*
* <pre>
* <parent xmlns:prefix1="http://Namespace-name-URI">
* <child xmlns:prefix2="http://Namespace-name-URI">
* ...
* </child>
* </parent>
* </pre>
*
* <P>A prefix can only be bound to a single Namespace URI in the current scope.</p>
*
* @author ricky
*/
public class WbXmlNamespaceContext implements NamespaceContext {
/**
* logger for the class.
*/
protected static final Logger log = Logger.getLogger(WbXmlNamespaceContext.class.getName());
/**
* Map for prefix to namespaces.
*/
private Map<String, String> prefixToNamespace = null;
/**
* Map for namespace to prefix (the same namespace can have several prefixes).
*/
private Map<String, Set<String>> namespaceToPrefix = null;
/**
* The default namespace (no prefix).
*/
private String defaultNamespace = null;
/**
* Empty connstructor.
*/
public WbXmlNamespaceContext() {
this(null);
}
/**
* Constructor setting the default namespace.
* @param defaultNamespace The default namespace.
*/
public WbXmlNamespaceContext(String defaultNamespace) {
prefixToNamespace = new HashMap<String, String>();
namespaceToPrefix = new HashMap<String, Set<String>>();
this.defaultNamespace = defaultNamespace;
}
/**
* Check if the default namespace has been set.
* @return true if set, false otherwise
*/
public boolean isDefaultNamespaceDefined() {
return this.defaultNamespace != null;
}
/**
* Setter for the default namespace.
* @param defaultNamespace The default namespace
*/
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
/**
* Getter for the default namespace
* @return The default namespace
*/
public String getDefaultNamespace() {
return this.defaultNamespace;
}
/**
* Add a new prefix/namespace to the context.
* @param prefix The prefirx for the namespace
* @param namespaceURI The namespace URI
*/
public void addPrefix(String prefix, String namespaceURI) {
log.log(Level.FINE, "addPrefix({0}, {1})", new Object[] {prefix, namespaceURI});
if (prefix == null || namespaceURI == null) {
throw new IllegalArgumentException("Prefix or namespaceURI cannot be null!");
}
prefixToNamespace.put(prefix, namespaceURI);
Set<String> prefixes = namespaceToPrefix.get(namespaceURI);
if (prefixes == null) {
prefixes = new HashSet<String>();
}
prefixes.add(prefix);
namespaceToPrefix.put(namespaceURI, prefixes);
}
/**
* Get Namespace URI bound to a prefix in the current scope.
* @param prefix The prefix to get the URI from
* @return The namespaceURI or null
*/
@Override
public String getNamespaceURI(String prefix) {
log.log(Level.FINE, "getNamespaceURI({0})", prefix);
if (prefix == null) {
throw new IllegalArgumentException("Prefix cannot be null!");
} else if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
// check if the namespace is the default one
if (defaultNamespace == null) {
return XMLConstants.NULL_NS_URI;
} else {
return defaultNamespace;
}
} else if (prefix.equals(XMLConstants.XML_NS_PREFIX)) {
return XMLConstants.XML_NS_URI;
} else if (prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) {
return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
} else {
String namespace = prefixToNamespace.get(prefix);
if (namespace != null) {
return prefixToNamespace.get(prefix);
} else {
return XMLConstants.NULL_NS_URI;
}
}
}
/**
* Get prefix bound to Namespace URI in the current scope.
* To get all prefixes bound to a Namespace URI in the current scope,
* use getPrefixes(String namespaceURI).
* @param namespaceURI URI of Namespace to lookup
* @return prefix bound to Namespace URI in current context
*/
@Override
public String getPrefix(String namespaceURI) {
log.log(Level.FINE, "getPrefix({0})", namespaceURI);
Iterator<String> i = getPrefixes(namespaceURI);
if (i.hasNext()) {
return i.next();
} else {
return null;
}
}
/**
* Get all prefixes bound to a Namespace URI in the current scope.
* @param namespaceURI URI of Namespace to lookup
* @return Iterator for all prefixes bound to the Namespace URI in the current scope
*/
@Override
public Iterator<String> getPrefixes(String namespaceURI) {
log.log(Level.FINE, "getPrefix({0})", namespaceURI);
if (namespaceURI == null) {
throw new IllegalArgumentException("namespaceURI cannot be null!");
} else if (namespaceURI.equals(defaultNamespace)) {
return Arrays.asList(new String[]{XMLConstants.DEFAULT_NS_PREFIX}).iterator();
} else if (namespaceURI.equals(XMLConstants.XML_NS_URI)) {
return Arrays.asList(new String[]{XMLConstants.XML_NS_PREFIX}).iterator();
} else if (namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
return Arrays.asList(XMLConstants.XMLNS_ATTRIBUTE).iterator();
} else {
Set<String> prefixes = namespaceToPrefix.get(namespaceURI);
if (prefixes != null && !prefixes.isEmpty()) {
return prefixes.iterator();
} else {
return new ArrayList<String>().iterator();
}
}
}
/**
* Clone the context duplicating the maps.
* @return The new cloned context
*/
@Override
public WbXmlNamespaceContext clone() {
WbXmlNamespaceContext nsctx = new WbXmlNamespaceContext();
nsctx.defaultNamespace = this.defaultNamespace;
nsctx.namespaceToPrefix.putAll(this.namespaceToPrefix);
nsctx.prefixToNamespace.putAll(this.prefixToNamespace);
return nsctx;
}
}
| |
package rod_design_compute;
public class RRR extends RodGroup{
private Point B;
private Point C;
private Point D;
private Rod L2;
private Rod L3;
//M only define 1 / -1
private int M;
//L2
private Point E2;
Boolean flag2;
//L3
private Point E3;
Boolean flag3;
private Rod BE2;
private Rod DE3;
public RRR(){
B = new Point();
C = new Point();
D = new Point();
E2 = new Point();
E3 = new Point();
BE2 = new Rod();
DE3 = new Rod();
L2 = new Rod();
L3 = new Rod();
flag2 = false;
flag3 = false;
M = 1;
super.setType(RRR);
}
public RRR(Point B_, Point D_, double L2_, double L3_, int M_){
B = B_;
C = new Point();
D = D_;
L2 = new Rod(L2_, 0.0, 0.0, 0.0);
L3 = new Rod(L3_, 0.0, 0.0, 0.0);
E2 = new Point();
E3 = new Point();
flag2 = false;
flag3 = false;
BE2 = new Rod();
DE3 = new Rod();
if((M_!=1)&&(M_!=-1)){
M = 1;
}
else {
M = M_;
}
calculate_RRR();
super.setType(RRR);
}
public RRR(Point B_, Point D_, double L2_, double L3_, int M_, Point E_, int num){
B = B_;
C = new Point();
D = D_;
L2 = new Rod(L2_, 0.0, 0.0, 0.0);
L3 = new Rod(L3_, 0.0, 0.0, 0.0);
BE2 = new Rod();
DE3 = new Rod();
if(num == 2)
{
E2 = E_;
flag2 = true;
flag3 = false;
E3 = new Point();
}
else
{
flag2 = false;
flag3 = true;
E2 = new Point();
E3 = E_;
}
if((M_!=1)&&(M_!=-1)){
M = 1;
}
else {
M = M_;
}
calculate_E();
calculate_RRR();
super.setType(RRR);
}
public void calculate_E(){
double d = Math.sqrt(Math.pow(D.X-B.X, 2) + Math.pow(D.Y - B.Y, 2));
double sigm = Math.atan((D.Y - B.Y)/(D.X - B.X));
double gama = Math.acos((Math.pow(d, 2) + Math.pow(L2.length, 2) - Math.pow(L3.length, 2))/(2*d*L2.length));
double fai2 = sigm + M * gama;
C.X = B.X + L2.length * Math.cos(fai2);
C.Y = B.Y + L2.length * Math.sin(fai2);
double fai3 = Math.atan((C.Y - D.Y)/(C.X - D.X));
double omig2 = ((D.Vx - B.Vx)*(C.X - D.X) + (D.Vy - B.Vy)*(C.Y - D.Y))/((C.Y - D.Y)*(C.X - B.X) - (C.Y - B.Y)*(C.X -D.X));
double omig3 = ((D.Vx - B.Vx)*(C.X - B.X) + (D.Vy - B.Vy)*(C.Y - B.Y))/((C.Y - D.Y)*(C.X - B.X) - (C.Y - B.Y)*(C.X -D.X));
C.Vx = B.Vx - omig2 * (C.Y - B.Y);
C.Vy = B.Vy + omig2 * (C.X - B.X);
double E = D.ax - B.ax + Math.pow(omig2, 2) * (C.X - B.X) - Math.pow(omig3, 2) * (C.X - D.X);
double F = D.ay - B.ay + Math.pow(omig2, 2) * (C.Y - B.Y) - Math.pow(omig3, 2) * (C.Y - D.Y);
double ypslon2 = (E * (C.X - D.X) + F * (C.Y -D.Y))/((C.X - B.X)*(C.Y - D.Y) - (C.X - D.X)*(C.Y - B.Y));
double ypslon3 = (E * (C.X - B.X) + F * (C.Y -B.Y))/((C.X - B.X)*(C.Y - D.Y) - (C.X - D.X)*(C.Y - B.Y));
C.ax = B.ax - Math.pow(omig2, 2) * (C.X - B.X) - ypslon2*(C.Y - B.Y);
C.ay = B.ay - Math.pow(omig2, 2) * (C.Y - B.Y) + ypslon2*(C.X - B.X);
L2.angle = fai2;
L2.angle_speed = omig2;
L2.angle_acc = ypslon2;
L3.angle = fai3;
L3.angle_speed = omig3;
L3.angle_acc = ypslon3;
//E3 DE3
DE3.length = Math.sqrt(Math.pow((D.X - E3.X), 2) + Math.pow((D.Y - E3.Y), 2));
if(((E3.X - D.X)!=0)&((E3.Y - D.Y)!=0))
{
if((E3.X - D.X)>0)
{
DE3.angle = Math.atan((D.Y - E3.Y)/(D.X - E3.X));
}
else
{
DE3.angle = Math.atan((D.Y - E3.Y)/(D.X - E3.X)) + Math.PI;
}
}
else
{
if(((E3.X - D.X)==0)&((E3.Y - D.Y)>0))
{
DE3.angle = Math.PI/2;
}
else if (((E3.X - D.X)==0)&((E3.Y - D.Y)<0))
{
DE3.angle = - Math.PI/2;
}
else if(((E3.X - D.X)>0)&((E3.Y - D.Y)==0))
{
DE3.angle = 0;
}
else if(((E3.X - D.X)<0)&((E3.Y - D.Y)==0))
{
DE3.angle = - Math.PI;
}
else
{
DE3.angle = 0;
}
}
DE3.angle = DE3.angle - L3.angle;
//E2 BE2
BE2.length = Math.sqrt(Math.pow((B.X - E2.X), 2) + Math.pow((B.Y - E2.Y), 2));
if(((E2.X - B.X)!=0)&((E2.Y - B.Y)!=0))
{
if((E2.X - B.X)>0)
{
BE2.angle = Math.atan((E2.Y - B.Y)/(E2.X - B.X));
}
else
{
BE2.angle = Math.atan((E2.Y - B.Y)/(E2.X - B.X)) + Math.PI;
}
}
else
{
if(((E2.X - B.X)==0)&((E2.Y - B.Y)>0))
{
BE2.angle = Math.PI/2;
}
else if (((E2.X - B.X)==0)&((E2.Y - B.Y)<0))
{
BE2.angle = - Math.PI/2;
}
else if(((E2.X - B.X)>0)&((E2.Y - B.Y)==0))
{
BE2.angle = 0;
}
else if(((E2.X - B.X)<0)&((E2.Y - B.Y)==0))
{
BE2.angle = - Math.PI;
}
else
{
BE2.angle = 0;
}
}
BE2.angle = BE2.angle - L2.angle;
}
public void calculate_RRR(){
double d = Math.sqrt(Math.pow(D.X-B.X, 2) + Math.pow(D.Y - B.Y, 2));
double sigm = Math.atan((D.Y - B.Y)/(D.X - B.X));
double gama = Math.acos((Math.pow(d, 2) + Math.pow(L2.length, 2) - Math.pow(L3.length, 2))/(2*d*L2.length));
double fai2 = sigm + M * gama;
C.X = B.X + L2.length * Math.cos(fai2);
C.Y = B.Y + L2.length * Math.sin(fai2);
double fai3 = Math.atan((C.Y - D.Y)/(C.X - D.X));
double omig2 = ((D.Vx - B.Vx)*(C.X - D.X) + (D.Vy - B.Vy)*(C.Y - D.Y))/((C.Y - D.Y)*(C.X - B.X) - (C.Y - B.Y)*(C.X -D.X));
double omig3 = ((D.Vx - B.Vx)*(C.X - B.X) + (D.Vy - B.Vy)*(C.Y - B.Y))/((C.Y - D.Y)*(C.X - B.X) - (C.Y - B.Y)*(C.X -D.X));
C.Vx = B.Vx - omig2 * (C.Y - B.Y);
C.Vy = B.Vy + omig2 * (C.X - B.X);
double E = D.ax - B.ax + Math.pow(omig2, 2) * (C.X - B.X) - Math.pow(omig3, 2) * (C.X - D.X);
double F = D.ay - B.ay + Math.pow(omig2, 2) * (C.Y - B.Y) - Math.pow(omig3, 2) * (C.Y - D.Y);
double ypslon2 = (E * (C.X - D.X) + F * (C.Y -D.Y))/((C.X - B.X)*(C.Y - D.Y) - (C.X - D.X)*(C.Y - B.Y));
double ypslon3 = (E * (C.X - B.X) + F * (C.Y -B.Y))/((C.X - B.X)*(C.Y - D.Y) - (C.X - D.X)*(C.Y - B.Y));
C.ax = B.ax - Math.pow(omig2, 2) * (C.X - B.X) - ypslon2*(C.Y - B.Y);
C.ay = B.ay - Math.pow(omig2, 2) * (C.Y - B.Y) + ypslon2*(C.X - B.X);
L2.angle = fai2;
L2.angle_speed = omig2;
L2.angle_acc = ypslon2;
L3.angle = fai3;
L3.angle_speed = omig3;
L3.angle_acc = ypslon3;
DE3.angle_acc = L3.angle_acc;
DE3.angle_speed = L3.angle_speed;
E3.X = D.X + DE3.length * Math.cos(DE3.angle + L3.angle);
E3.Y = D.Y + DE3.length * Math.sin(DE3.angle + L3.angle);
E3.Vx = D.Vx - DE3.angle_speed * (E3.Y - D.Y);
E3.Vy = D.Vy + DE3.angle_speed * (E3.X - D.X);
E3.ax = D.ax - Math.pow(DE3.angle_speed , 2) * (E3.X - D.X) - DE3.angle_acc * (E3.Y - D.Y);
E3.ay = D.ay - Math.pow(DE3.angle_speed, 2) * (E3.Y - D.Y) + DE3.angle_acc * (E3.X - D.X);
BE2.angle_acc = L2.angle_acc;
BE2.angle_speed = L2.angle_speed;
E2.X = B.X + BE2.length * Math.cos(BE2.angle + L2.angle);
E2.Y = B.Y + BE2.length * Math.sin(BE2.angle + L2.angle);
E2.Vx = B.Vx - BE2.angle_speed * (E2.Y - B.Y);
E2.Vy = B.Vy + BE2.angle_speed * (E2.X - B.X);
E2.ax = B.ax - Math.pow(BE2.angle_speed , 2) * (E2.X - B.X) - BE2.angle_acc * (E2.Y - B.Y);
E2.ay = B.ay - Math.pow(BE2.angle_speed, 2) * (E2.Y - B.Y) + BE2.angle_acc * (E2.X - B.X);
}
public Boolean decide(){
double BC = Math.sqrt(Math.pow(B.X-C.X, 2) + Math.pow(B.Y - C.Y, 2));
double L = L2.length + L3.length;
if(BC <= L)
return true;
else
return false;
}
public void copyanother(RRR rrr){
this.B.copyanother(rrr.getPointB());
this.C.copyanother(rrr.getPointC());
this.D.copyanother(rrr.getPointD());
this.L2.copyanother(rrr.getrodL2());
this.L3.copyanother(rrr.getrodL3());
this.M = rrr.M;
this.flag2 = rrr.flag2;
this.flag3 = rrr.flag3;
this.BE2.copyanother(rrr.getrodBE2());
this.DE3.copyanother(rrr.getrodDE3());
if(flag2 == true)
this.setPointE(rrr.getPointE(), 2);
else if(flag3 == true)
this.setPointE(rrr.getPointE(), 3);
}
public void computeSpeedAndAccelerate(){
B.velocity = Math.sqrt(Math.pow(B.Vx, 2) + Math.pow(B.Vy, 2));
B.accelerate = Math.sqrt(Math.pow(B.ax, 2) + Math.pow(B.ay, 2));
C.velocity = Math.sqrt(Math.pow(C.Vx, 2) + Math.pow(C.Vy, 2));
C.accelerate = Math.sqrt(Math.pow(C.ax, 2) + Math.pow(C.ay, 2));
D.velocity = Math.sqrt(Math.pow(D.Vx, 2) + Math.pow(D.Vy, 2));
D.accelerate = Math.sqrt(Math.pow(D.ax, 2) + Math.pow(D.ay, 2));
}
public Point getNextPoint(){
return C;
}
public Point getPointB(){
return this.B;
}
public Point getPointC(){
//calculate_RRR();
return this.C;
}
public Point getPointD(){
return this.D;
}
public Point getPointE(){
if(flag2 == true)
{
return E2;
}
else if(flag3 == true)
{
return E3;
}
else
{
return null;
}
}
public Rod getrodL2(){
//calculate_RRR();
return this.L2;
}
public Rod getrodL3(){
//calculate_RRR();
return this.L3;
}
public Rod getrodBE2(){
//calculate_RRR();
return this.BE2;
}
public Rod getrodDE3(){
//calculate_RRR();
return this.DE3;
}
public void setPointB(Point B_){
this.B.copyanother(B_);
calculate_RRR();
}
/*public void setPointC(Point C_){
C = C_;
calculate_RRR();
}
*/
public void setPointD(Point D_){
this.D.copyanother(D_);
calculate_RRR();
}
public void setLengthL2(double L2_){
this.L2.length = L2_;
calculate_RRR();
}
public void setLengthL3(double L3_){
this.L3.length = L3_;
calculate_RRR();
}
public void setM(int M_){
if ((M_==1)||(M_==-1)){
this.M = M_;
calculate_RRR();
}
}
public void setPointE(Point E_, int num)
{
if(num == 2)
{
this.E2.copyanother(E_);
}
else if(num == 3)
{
this.E3.copyanother(E_);
}
else
{
}
}
}
| |
/*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.states;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.CStateChange;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseState;
import com.google.security.zynamics.zylib.gui.zygraph.editmode.IMouseStateChange;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.AbstractZyGraph;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.edges.ZyGraphEdge;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.CStateFactory;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.editmode.helpers.CEditNodeHelper;
import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.nodes.ZyGraphNode;
import y.base.Node;
import y.view.HitInfo;
import java.awt.event.MouseEvent;
import javax.swing.SwingUtilities;
/**
* This class represents the mouse state that is reached as soon as the user moves the mouse into a
* node.
*/
public final class CNodeEditState implements IMouseState {
/**
* State factory that creates new state objects when necessary.
*/
private final CStateFactory<?, ?> m_factory;
/**
* The graph the entered node belongs to.
*/
private final AbstractZyGraph<?, ?> m_graph;
/**
* The entered node.
*/
private final Node m_node;
private boolean m_isDragging = false;
/**
* Creates a new state object.
*
* @param factory State factory that creates new state objects when necessary.
* @param graph The graph the entered node belongs to.
* @param node The entered node.
*/
public CNodeEditState(final CStateFactory<?, ?> factory, final AbstractZyGraph<?, ?> graph,
final Node node) {
m_factory = factory;
m_graph = graph;
m_node = node;
}
/**
* Returns the graph the entered node belongs to.
*
* @return The graph the entered node belongs to.
*/
public AbstractZyGraph<?, ?> getGraph() {
return m_graph;
}
/**
* Returns the entered node.
*
* @return The entered node.
*/
public Node getNode() {
return m_node;
}
@Override
public CStateFactory<? extends ZyGraphNode<?>, ? extends ZyGraphEdge<?, ?, ?>> getStateFactory() {
return m_factory;
}
@Override
public IMouseStateChange mouseDragged(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
m_isDragging = true;
CEditNodeHelper.select(graph, m_node, event);
return new CStateChange(this, false);
}
@Override
public IMouseStateChange mouseMoved(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
return new CStateChange(this, true);
}
@Override
public IMouseStateChange mousePressed(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
final double x = graph.getEditMode().translateX(event.getX());
final double y = graph.getEditMode().translateY(event.getY());
final HitInfo hitInfo = graph.getGraph().getHitInfo(x, y);
if (hitInfo.hasHitNodes()) {
final Node n = hitInfo.getHitNode();
if (SwingUtilities.isLeftMouseButton(event) && !event.isAltDown()) {
if (n == m_node) {
if (!m_isDragging) {
// Change caret
CEditNodeHelper.setCaretStart(graph, n, event);
} else {
m_isDragging = false;
}
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedLeftState(n, event), true);
}
} else if (SwingUtilities.isRightMouseButton(event)) {
if (n == m_node) {
// Do nothing
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedRightState(n, event), true);
}
} else if (SwingUtilities.isMiddleMouseButton(event)
|| (event.isAltDown() && SwingUtilities.isLeftMouseButton(event))) {
if (n == m_node) {
// m_factory.createNodeEditExitState(m_node, event);
if (!m_isDragging) {
// Change caret
CEditNodeHelper.setCaretStart(graph, n, event);
} else {
m_isDragging = false;
}
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedMiddleState(n, event), true);
}
} else {
// A button was pressed that does not have any special functionality.
return new CStateChange(this, false);
}
} else if (hitInfo.hasHitNodeLabels()) {
throw new IllegalStateException();
} else if (hitInfo.hasHitEdges()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createEdgePressedLeftState(hitInfo.getHitEdge(), event),
true);
} else if (hitInfo.hasHitEdgeLabels()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createEdgePressedLeftState(hitInfo.getHitEdgeLabel()
.getEdge(), event), true);
} else if (hitInfo.hasHitBends()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createBendPressedLeftState(hitInfo.getHitBend(), event),
true);
} else if (hitInfo.hasHitPorts()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createDefaultState(), true);
} else {
// User left-pressed the background.
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createBackgroundPressedLeftState(event), true);
}
}
@Override
public IMouseStateChange mouseReleased(final MouseEvent event, final AbstractZyGraph<?, ?> graph) {
final double x = graph.getEditMode().translateX(event.getX());
final double y = graph.getEditMode().translateY(event.getY());
final HitInfo hitInfo = graph.getGraph().getHitInfo(x, y);
if (hitInfo.hasHitNodes()) {
final Node n = hitInfo.getHitNode();
if (SwingUtilities.isLeftMouseButton(event) && !event.isAltDown()) {
if (n == m_node) {
if (!m_isDragging) {
// Change caret
CEditNodeHelper.setCaretEnd(graph, n, event);
} else {
m_isDragging = false;
}
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedLeftState(n, event), true);
}
} else if (SwingUtilities.isRightMouseButton(event)) {
if (n == m_node) {
// Show context menu
// NH 10.08.2010
// m_factory.editNodeRightClicked(m_node, event, x, y);
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedRightState(n, event), true);
}
} else if (SwingUtilities.isMiddleMouseButton(event)
|| (event.isAltDown() && SwingUtilities.isLeftMouseButton(event))) {
if (n == m_node) {
// m_factory.createNodeEditExitState(m_node, event);
if (!m_isDragging) {
// Change caret
CEditNodeHelper.setCaretEnd(graph, n, event);
} else {
m_isDragging = false;
}
return new CStateChange(this, false);
} else {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createNodePressedMiddleState(n, event), true);
}
} else {
// A button was pressed that does not have any special functionality.
return new CStateChange(this, false);
}
} else if (hitInfo.hasHitNodeLabels()) {
throw new IllegalStateException();
} else if (hitInfo.hasHitEdges()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createEdgePressedLeftState(hitInfo.getHitEdge(), event),
true);
} else if (hitInfo.hasHitEdgeLabels()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createEdgePressedLeftState(hitInfo.getHitEdgeLabel()
.getEdge(), event), true);
} else if (hitInfo.hasHitBends()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createBendPressedLeftState(hitInfo.getHitBend(), event),
true);
} else if (hitInfo.hasHitPorts()) {
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createDefaultState(), true);
} else {
// User left-pressed the background.
m_factory.createNodeEditExitState(m_node, event);
return new CStateChange(m_factory.createBackgroundPressedLeftState(event), true);
}
}
}
| |
package glassPaxos;
import glassPaxos.network.NodeIdentifier;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class Configuration {
/*
* This is usually the max number of nodes per role.
* For example, if you have 1000 clients, 5 acceptors, and
* 5 learners, then set this number to 1000.
*/
//public static final int MAX_MSG_SIZE = 1048576;
public static final int MAX_MSG_SIZE = 5242880;
public static final int MAX_NODE_ID = 1000;
//public static final long MAX_SNAPSHOT_CHUNK_SIZE = 1000L;
public static final long MAX_SNAPSHOT_CHUNK_SIZE = 5242880L; //5M
public enum PROTOCOL_TYPE {
THRIFTY, STD, CHEAP
}
public static PROTOCOL_TYPE protocolType;
/* timeout in millisecond */
public static long pingTimeout;
public static long requestTimeout;
public static long prepareTimeout;
public static long acceptTimeout;
public static long learnerTimeout;
public static int showPerformanceInterval;
public static int checkpointInterval;
//public static int freeCacheInterval;
public static int maxAccSyncDiff; // acceptor sync accept chunkSize
public static int maxSyncDiff; // sync decision/accept chunkSize
public static int maxPendingCatchupSync; // max pending requests of decision/accept catchupSyncMsg
public static int maxDecisionGap; // decision gap threshold for learner to catchup leader
public static int catchupSnapshotThrottle; // threshold for learner handling pending catchupSnapshot
public static int catchupDecisionThrottle; // threshold for leader handling pending catchupDecision
public static int catchupLeaLogThreshold; // threshold for leader handling pending learnerLog decision
public static int leaCatchupTimeCap; // expected execution time of learner catchup procedure (s)
public static int batchingSize; //batching size (#request)
public static boolean enableBatching; //enable batching mode
public static int maxLogCacheSize; //max cache size for acceptorLog and pending decisions
public static boolean enableDecInParallel; //enable acceptors send decision in parallel
public static boolean enableLeaderFastPath; //enable leader put accept/accepted in event queue directly
public static boolean enableFailDetection; //enable handleFailure logic
/* request */
public static int maxOutgoingRequests;
public static int maxPendingRequests;
public static int numTestPaths;
public static int numClients;
public static int numLearners;
public static int numAcceptors;
public static int numQuorumAcceptors;
public static int numQuorumLearners;
public final static HashMap<Integer, NodeIdentifier> clientIDs = new HashMap<>(); //index [1,...numClients]
public final static HashMap<Integer, NodeIdentifier> acceptorIDs = new HashMap<>();
public final static HashMap<Integer, NodeIdentifier> learnerIDs = new HashMap<>();
/* log and snapshot directories */
public static String acceptorGCStatFile; // store additional acceptor stats
public static String acceptorLogDir; // store acceptorMessage
public static String catchupAccLogDir; // store catchup acceptorMessage
public static String learnerLogDir; // store new decisionMsg during learner catchup
public static String catchupLeaLogDir; // store missing decisionMsg during learner catchup
public static String learnerSnapshotDir; // persistent snapshot files
public static String learnerFakeSnapshotFile; // store fake snapshot files
public static int debugLevel;
public static PropertiesConfiguration gpConf;
/* Logger configuration */
private static HashMap<String, Integer> activeLogger = new HashMap<String, Integer>();
public static boolean isLoggerActive(String name){
return activeLogger.containsKey(name);
}
public static int getLoggerLevel(String name){
return activeLogger.get(name);
}
public static void addActiveLogger(String name, int level){
activeLogger.put(name, level);
}
public static void removeActiveLogger(String name){
activeLogger.remove(name);
}
/* Network configuration */
private static HashMap<NodeIdentifier, InetSocketAddress> nodes =
new HashMap<NodeIdentifier, InetSocketAddress>();
public static InetSocketAddress getNodeAddress(NodeIdentifier node){
return nodes.get(node);
}
public static void addNodeAddress(NodeIdentifier node, InetSocketAddress address){
nodes.put(node, address);
}
public static void initConfiguration(String confFile) throws ConfigurationException {
gpConf = new PropertiesConfiguration(confFile);
configNodeAddress(NodeIdentifier.Role.CLIENT, "client", gpConf.getInt("clientPort"));
configNodeAddress(NodeIdentifier.Role.ACCEPTOR, "acceptor", gpConf.getInt("acceptorPort"));
configNodeAddress(NodeIdentifier.Role.LEARNER, "learner", gpConf.getInt("learnerPort"));
numClients = clientIDs.size();
numAcceptors = acceptorIDs.size();
numLearners = learnerIDs.size();
numQuorumAcceptors = numAcceptors/2 + 1;
numQuorumLearners = numLearners/2 + 1;
String pType = gpConf.getString("protocolType", "THRIFTY");
protocolType = PROTOCOL_TYPE.valueOf(pType);
acceptorGCStatFile = gpConf.getString("acceptorGCStatFile");
acceptorLogDir = gpConf.getString("acceptorLogDir");
catchupAccLogDir = gpConf.getString("catchupAccLogDir");
learnerLogDir = gpConf.getString("learnerLogDir");
catchupLeaLogDir = gpConf.getString("catchupLeaLogDir");
learnerSnapshotDir = gpConf.getString("learnerSnapShotDir");
learnerFakeSnapshotFile = gpConf.getString("learnerFakeSnapshotFile");
/* requests */
maxOutgoingRequests = gpConf.getInt("outgoingRequests", 500);
maxPendingRequests = gpConf.getInt("pendingRequests", 200);
/* timeout */
pingTimeout = gpConf.getInt("pingTimeout", 200);
requestTimeout = gpConf.getInt("requestTimeout", 2000);
prepareTimeout = gpConf.getInt("prepareTimeout", 200);
acceptTimeout = gpConf.getInt("acceptTimeout", 800);
learnerTimeout = gpConf.getInt("learnerTimeout", 2000);
/* log checkpoint */
showPerformanceInterval = gpConf.getInt("showPerformanceInterval", 10);
checkpointInterval = gpConf.getInt("checkpointInterval", 3000000);
//freeCacheInterval = gpConf.getInt("freeCacheInterval", 2000);
maxAccSyncDiff = gpConf.getInt("maxAccSyncDiff", 2000);
maxSyncDiff = gpConf.getInt("maxSyncDiff", 2000);
maxDecisionGap = gpConf.getInt("maxDecisionGap", 50);
maxPendingCatchupSync = gpConf.getInt("maxPendingCatchupSync", 10);
catchupSnapshotThrottle = gpConf.getInt("catchupSnapshotThrottle", 15000);
catchupDecisionThrottle = gpConf.getInt("catchupDecisionThrottle", 15000);
catchupLeaLogThreshold = gpConf.getInt("catchupLeaLogThreshold", 10000);
leaCatchupTimeCap = gpConf.getInt("leaCatchupTimeCap", 200);
numTestPaths = gpConf.getInt("numTestPaths", 1024*1024);
debugLevel = gpConf.getInt("debugLevel", 1); //default value is INFO
batchingSize = gpConf.getInt("batchingSize", 50);
enableBatching = gpConf.getBoolean("enableBatching", false);
if (!enableBatching) batchingSize = 1;
maxLogCacheSize = gpConf.getInt("maxLogCacheSize", 400000); //default 400k
enableDecInParallel = gpConf.getBoolean("enableDecInParallel", false);
enableLeaderFastPath = gpConf.getBoolean("enableLeaderFastPath", false);
enableFailDetection = gpConf.getBoolean("enableFailDetection", true);
}
public static void changeDebugLevel(int value) {
debugLevel = value;
}
public static void showNodeConfig() {
System.out.format("\n== show node configuration ==\n");
Set nodeSet = clientIDs.entrySet();
System.out.format("%d clients: %s\n", numClients, nodeSet);
nodeSet = acceptorIDs.entrySet();
System.out.format("%d acceptors: %s\n", numAcceptors, nodeSet);
nodeSet = learnerIDs.entrySet();
System.out.format("%d learners: %s\n", numLearners, nodeSet);
System.out.format("quorum %d acceptors, %d learners\n", numQuorumAcceptors, numQuorumLearners);
System.out.format("use protocol %s batchingMode=%b cacheSz=%d\n", protocolType.name(),
enableBatching, maxLogCacheSize);
}
public static void displayMemoryInfo(String idInfo) {
System.out.printf("%s memory(mb) max %d free %d\n", idInfo,
Runtime.getRuntime().maxMemory()/(1024*1024),
Runtime.getRuntime().freeMemory()/(1024*1024));
}
public static void configNodeAddress(NodeIdentifier.Role role, String keys, int startPort) {
Iterator<String> names = gpConf.getKeys(keys);
int idx = 1;
while (names.hasNext()) {
String name = names.next();
InetSocketAddress iAddress = new InetSocketAddress(gpConf.getString(name), startPort+idx);
NodeIdentifier node = new NodeIdentifier(role, idx);
addNodeAddress(node, iAddress);
//System.out.format("=> add NodeAddress <%s, %s>, IDs <%d, %s>\n",
// node, nodes.get(node), idx, node);
if (role == NodeIdentifier.Role.CLIENT) {
clientIDs.put(idx, node);
} else if (role == NodeIdentifier.Role.ACCEPTOR) {
acceptorIDs.put(idx, node);
} else {
learnerIDs.put(idx, node);
}
idx++;
}
//return idx-1;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.metron.management;
import com.jakewharton.fliptables.FlipTable;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.metron.stellar.common.shell.VariableResult;
import org.apache.metron.stellar.common.shell.cli.PausableInput;
import org.apache.metron.stellar.common.utils.ConversionUtils;
import org.apache.metron.stellar.dsl.BaseStellarFunction;
import org.apache.metron.stellar.dsl.Context;
import org.apache.metron.stellar.dsl.ParseException;
import org.apache.metron.stellar.dsl.Stellar;
import org.apache.metron.stellar.dsl.StellarFunction;
import org.jboss.aesh.console.Console;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.invoke.MethodHandles;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.metron.stellar.dsl.Context.Capabilities.CONSOLE;
public class ShellFunctions {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static Map<String, VariableResult> getVariables(Context context) {
return (Map<String, VariableResult>) context.getCapability(Context.Capabilities.SHELL_VARIABLES).get();
}
@Stellar(
namespace = "SHELL"
,name = "MAP2TABLE"
,description = "Take a map and return a table"
,params = {"map - Map"
}
,returns = "The map in table form"
)
public static class Map2Table extends BaseStellarFunction {
@Override
public Object apply(List<Object> args) {
if(args.size() < 1) {
return null;
}
Map<Object, Object> map = (Map<Object, Object>) args.get(0);
if(map == null) {
map = new HashMap<>();
}
String[] headers = {"KEY", "VALUE"};
String[][] data = new String[map.size()][2];
int i = 0;
for(Map.Entry<Object, Object> kv : map.entrySet()) {
data[i++] = new String[] {kv.getKey().toString(), kv.getValue().toString()};
}
return FlipTable.of(headers, data);
}
}
@Stellar(
namespace = "SHELL"
,name = "LIST_VARS"
,description = "Return the variables in a tabular form"
,params = {
"wrap : Length of string to wrap the columns"
}
,returns = "A tabular representation of the variables."
)
public static class ListVars implements StellarFunction {
@Override
public Object apply(List<Object> args, Context context) throws ParseException {
Map<String, VariableResult> variables = getVariables(context);
String[] headers = {"VARIABLE", "VALUE", "EXPRESSION"};
String[][] data = new String[variables.size()][3];
int wordWrap = -1;
if(args.size() > 0) {
wordWrap = ConversionUtils.convert(args.get(0), Integer.class);
}
int i = 0;
for(Map.Entry<String, VariableResult> kv : variables.entrySet()) {
VariableResult result = kv.getValue();
data[i++] = new String[] { toWrappedString(kv.getKey().toString(), wordWrap)
, toWrappedString(result.getResult(), wordWrap)
, toWrappedString(result.getExpression().get(), wordWrap)
};
}
return FlipTable.of(headers, data);
}
private static String toWrappedString(Object o, int wrap) {
String s = "" + o;
if(wrap <= 0) {
return s;
}
return WordUtils.wrap(s, wrap);
}
@Override
public void initialize(Context context) {
}
@Override
public boolean isInitialized() {
return true;
}
}
@Stellar(
namespace = "SHELL"
,name = "VARS2MAP"
,description = "Take a set of variables and return a map"
,params = {"variables* - variable names to use to create map "
}
,returns = "A map associating the variable name with the stellar expression."
)
public static class Var2Map implements StellarFunction {
@Override
public Object apply(List<Object> args, Context context) throws ParseException {
Map<String, VariableResult> variables = getVariables(context);
LinkedHashMap<String, String> ret = new LinkedHashMap<>();
for(Object arg : args) {
if(arg == null) {
continue;
}
String variable = (String)arg;
VariableResult result = variables.get(variable);
if(result != null && result.getExpression().isPresent()) {
ret.put(variable, result.getExpression().orElseGet(() -> ""));
}
}
return ret;
}
@Override
public void initialize(Context context) {
}
@Override
public boolean isInitialized() {
return true;
}
}
@Stellar(
namespace = "SHELL"
,name = "GET_EXPRESSION"
,description = "Get a stellar expression from a variable"
,params = {"variable - variable name"
}
,returns = "The stellar expression associated with the variable."
)
public static class GetExpression implements StellarFunction {
@Override
public Object apply(List<Object> args, Context context) throws ParseException {
Map<String, VariableResult> variables = getVariables(context);
if(args.size() == 0) {
return null;
}
String variable = (String) args.get(0);
if(variable == null) {
return null;
}
VariableResult result = variables.get(variable);
if(result != null && result.getExpression().isPresent()) {
return result.getExpression().get();
}
return null;
}
@Override
public void initialize(Context context) {
}
@Override
public boolean isInitialized() {
return true;
}
}
@Stellar(
namespace = "SHELL"
,name = "EDIT"
,description = "Open an editor (optionally initialized with text) and return " +
"whatever is saved from the editor. The editor to use is pulled " +
"from `EDITOR` or `VISUAL` environment variable."
,params = { "string - (Optional) A string whose content is used to initialize the editor."
}
,returns = "The content that the editor saved after editor exit."
)
public static class Edit implements StellarFunction {
private String getEditor() {
// if we have editor in the system properties, it should
// override the env so we check that first
String editor = System.getProperty("EDITOR");
if(org.apache.commons.lang3.StringUtils.isEmpty(editor)) {
editor = System.getenv().get("EDITOR");
}
if(org.apache.commons.lang3.StringUtils.isEmpty(editor)) {
editor = System.getenv("VISUAL");
}
if(org.apache.commons.lang3.StringUtils.isEmpty(editor)) {
editor = "/bin/vi";
}
return editor;
}
@Override
public Object apply(List<Object> args, Context context) throws ParseException {
File outFile = null;
String editor = getEditor();
try {
outFile = File.createTempFile("stellar_shell", "out");
if(args.size() > 0) {
String arg = (String)args.get(0);
try(PrintWriter pw = new PrintWriter(outFile)) {
IOUtils.write(arg, pw);
}
}
} catch (IOException e) {
String message = "Unable to create temp file: " + e.getMessage();
LOG.error(message, e);
throw new IllegalStateException(message, e);
}
Optional<Object> console = context.getCapability(CONSOLE, false);
try {
PausableInput.INSTANCE.pause();
//shut down the IO for the console
ProcessBuilder processBuilder = new ProcessBuilder(editor, outFile.getAbsolutePath());
processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
Process p = processBuilder.start();
// wait for termination.
p.waitFor();
try (BufferedReader br = new BufferedReader(new FileReader(outFile))) {
String ret = IOUtils.toString(br).trim();
return ret;
}
} catch (Exception e) {
String message = "Unable to read output: " + e.getMessage();
LOG.error(message, e);
return null;
}
} finally {
try {
PausableInput.INSTANCE.unpause();
if(console.isPresent()) {
((Console)console.get()).pushToInputStream("\b\n");
}
} catch (IOException e) {
LOG.error("Unable to unpause: {}", e.getMessage(), e);
}
if(outFile.exists()) {
outFile.delete();
}
}
}
@Override
public void initialize(Context context) {
}
@Override
public boolean isInitialized() {
return true;
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.script;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.indexedscripts.delete.DeleteIndexedScriptRequest;
import org.elasticsearch.action.indexedscripts.get.GetIndexedScriptRequest;
import org.elasticsearch.action.indexedscripts.put.PutIndexedScriptRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.HasContextAndHeaders;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.cache.Cache;
import org.elasticsearch.common.cache.CacheBuilder;
import org.elasticsearch.common.cache.RemovalListener;
import org.elasticsearch.common.cache.RemovalNotification;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.query.TemplateQueryParser;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.lookup.SearchLookup;
import org.elasticsearch.watcher.FileChangesListener;
import org.elasticsearch.watcher.FileWatcher;
import org.elasticsearch.watcher.ResourceWatcherService;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import static java.util.Collections.unmodifiableMap;
/**
*
*/
public class ScriptService extends AbstractComponent implements Closeable {
static final String DISABLE_DYNAMIC_SCRIPTING_SETTING = "script.disable_dynamic";
public static final String DEFAULT_SCRIPTING_LANGUAGE_SETTING = "script.default_lang";
public static final Setting<Integer> SCRIPT_CACHE_SIZE_SETTING = Setting.intSetting("script.cache.max_size", 100, 0, false, Setting.Scope.CLUSTER);
public static final String SCRIPT_CACHE_EXPIRE_SETTING = "script.cache.expire";
public static final String SCRIPT_INDEX = ".scripts";
public static final String DEFAULT_LANG = "groovy";
public static final String SCRIPT_AUTO_RELOAD_ENABLED_SETTING = "script.auto_reload_enabled";
private final String defaultLang;
private final Set<ScriptEngineService> scriptEngines;
private final Map<String, ScriptEngineService> scriptEnginesByLang;
private final Map<String, ScriptEngineService> scriptEnginesByExt;
private final ConcurrentMap<CacheKey, CompiledScript> staticCache = ConcurrentCollections.newConcurrentMap();
private final Cache<CacheKey, CompiledScript> cache;
private final Path scriptsDirectory;
private final ScriptModes scriptModes;
private final ScriptContextRegistry scriptContextRegistry;
private final ParseFieldMatcher parseFieldMatcher;
private Client client = null;
private final ScriptMetrics scriptMetrics = new ScriptMetrics();
/**
* @deprecated Use {@link org.elasticsearch.script.Script.ScriptField} instead. This should be removed in
* 2.0
*/
@Deprecated
public static final ParseField SCRIPT_LANG = new ParseField("lang","script_lang");
/**
* @deprecated Use {@link ScriptType#getParseField()} instead. This should
* be removed in 2.0
*/
@Deprecated
public static final ParseField SCRIPT_FILE = new ParseField("script_file");
/**
* @deprecated Use {@link ScriptType#getParseField()} instead. This should
* be removed in 2.0
*/
@Deprecated
public static final ParseField SCRIPT_ID = new ParseField("script_id");
/**
* @deprecated Use {@link ScriptType#getParseField()} instead. This should
* be removed in 2.0
*/
@Deprecated
public static final ParseField SCRIPT_INLINE = new ParseField("script");
@Inject
public ScriptService(Settings settings, Environment env, Set<ScriptEngineService> scriptEngines,
ResourceWatcherService resourceWatcherService, ScriptContextRegistry scriptContextRegistry) throws IOException {
super(settings);
this.parseFieldMatcher = new ParseFieldMatcher(settings);
if (Strings.hasLength(settings.get(DISABLE_DYNAMIC_SCRIPTING_SETTING))) {
throw new IllegalArgumentException(DISABLE_DYNAMIC_SCRIPTING_SETTING + " is not a supported setting, replace with fine-grained script settings. \n" +
"Dynamic scripts can be enabled for all languages and all operations by replacing `script.disable_dynamic: false` with `script.inline: on` and `script.indexed: on` in elasticsearch.yml");
}
this.scriptEngines = scriptEngines;
this.scriptContextRegistry = scriptContextRegistry;
int cacheMaxSize = SCRIPT_CACHE_SIZE_SETTING.get(settings);
TimeValue cacheExpire = settings.getAsTime(SCRIPT_CACHE_EXPIRE_SETTING, null);
logger.debug("using script cache with max_size [{}], expire [{}]", cacheMaxSize, cacheExpire);
this.defaultLang = settings.get(DEFAULT_SCRIPTING_LANGUAGE_SETTING, DEFAULT_LANG);
CacheBuilder<CacheKey, CompiledScript> cacheBuilder = CacheBuilder.builder();
if (cacheMaxSize >= 0) {
cacheBuilder.setMaximumWeight(cacheMaxSize);
}
if (cacheExpire != null) {
cacheBuilder.setExpireAfterAccess(cacheExpire.nanos());
}
this.cache = cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build();
Map<String, ScriptEngineService> enginesByLangBuilder = new HashMap<>();
Map<String, ScriptEngineService> enginesByExtBuilder = new HashMap<>();
for (ScriptEngineService scriptEngine : scriptEngines) {
for (String type : scriptEngine.types()) {
enginesByLangBuilder.put(type, scriptEngine);
}
for (String ext : scriptEngine.extensions()) {
enginesByExtBuilder.put(ext, scriptEngine);
}
}
this.scriptEnginesByLang = unmodifiableMap(enginesByLangBuilder);
this.scriptEnginesByExt = unmodifiableMap(enginesByExtBuilder);
this.scriptModes = new ScriptModes(this.scriptEnginesByLang, scriptContextRegistry, settings);
// add file watcher for static scripts
scriptsDirectory = env.scriptsFile();
if (logger.isTraceEnabled()) {
logger.trace("Using scripts directory [{}] ", scriptsDirectory);
}
FileWatcher fileWatcher = new FileWatcher(scriptsDirectory);
fileWatcher.addListener(new ScriptChangesListener());
if (settings.getAsBoolean(SCRIPT_AUTO_RELOAD_ENABLED_SETTING, true)) {
// automatic reload is enabled - register scripts
resourceWatcherService.add(fileWatcher);
} else {
// automatic reload is disable just load scripts once
fileWatcher.init();
}
}
//This isn't set in the ctor because doing so creates a guice circular
@Inject(optional=true)
public void setClient(Client client) {
this.client = client;
}
@Override
public void close() throws IOException {
IOUtils.close(scriptEngines);
}
private ScriptEngineService getScriptEngineServiceForLang(String lang) {
ScriptEngineService scriptEngineService = scriptEnginesByLang.get(lang);
if (scriptEngineService == null) {
throw new IllegalArgumentException("script_lang not supported [" + lang + "]");
}
return scriptEngineService;
}
private ScriptEngineService getScriptEngineServiceForFileExt(String fileExtension) {
ScriptEngineService scriptEngineService = scriptEnginesByExt.get(fileExtension);
if (scriptEngineService == null) {
throw new IllegalArgumentException("script file extension not supported [" + fileExtension + "]");
}
return scriptEngineService;
}
/**
* Checks if a script can be executed and compiles it if needed, or returns the previously compiled and cached script.
*/
public CompiledScript compile(Script script, ScriptContext scriptContext, HasContextAndHeaders headersContext, Map<String, String> params) {
if (script == null) {
throw new IllegalArgumentException("The parameter script (Script) must not be null.");
}
if (scriptContext == null) {
throw new IllegalArgumentException("The parameter scriptContext (ScriptContext) must not be null.");
}
String lang = script.getLang();
if (lang == null) {
lang = defaultLang;
}
ScriptEngineService scriptEngineService = getScriptEngineServiceForLang(lang);
if (canExecuteScript(lang, scriptEngineService, script.getType(), scriptContext) == false) {
throw new ScriptException("scripts of type [" + script.getType() + "], operation [" + scriptContext.getKey() + "] and lang [" + lang + "] are disabled");
}
// TODO: fix this through some API or something, thats wrong
// special exception to prevent expressions from compiling as update or mapping scripts
boolean expression = "expression".equals(script.getLang());
boolean notSupported = scriptContext.getKey().equals(ScriptContext.Standard.UPDATE.getKey());
if (expression && notSupported) {
throw new ScriptException("scripts of type [" + script.getType() + "]," +
" operation [" + scriptContext.getKey() + "] and lang [" + lang + "] are not supported");
}
return compileInternal(script, headersContext, params);
}
/**
* Compiles a script straight-away, or returns the previously compiled and cached script,
* without checking if it can be executed based on settings.
*/
public CompiledScript compileInternal(Script script, HasContextAndHeaders context, Map<String, String> params) {
if (script == null) {
throw new IllegalArgumentException("The parameter script (Script) must not be null.");
}
String lang = script.getLang() == null ? defaultLang : script.getLang();
ScriptType type = script.getType();
//script.getScript() could return either a name or code for a script,
//but we check for a file script name first and an indexed script name second
String name = script.getScript();
if (logger.isTraceEnabled()) {
logger.trace("Compiling lang: [{}] type: [{}] script: {}", lang, type, name);
}
ScriptEngineService scriptEngineService = getScriptEngineServiceForLang(lang);
if (type == ScriptType.FILE) {
CacheKey cacheKey = new CacheKey(scriptEngineService, name, null, params);
//On disk scripts will be loaded into the staticCache by the listener
CompiledScript compiledScript = staticCache.get(cacheKey);
if (compiledScript == null) {
throw new IllegalArgumentException("Unable to find on disk file script [" + name + "] using lang [" + lang + "]");
}
return compiledScript;
}
//script.getScript() will be code if the script type is inline
String code = script.getScript();
if (type == ScriptType.INDEXED) {
//The look up for an indexed script must be done every time in case
//the script has been updated in the index since the last look up.
final IndexedScript indexedScript = new IndexedScript(lang, name);
name = indexedScript.id;
code = getScriptFromIndex(indexedScript.lang, indexedScript.id, context);
}
CacheKey cacheKey = new CacheKey(scriptEngineService, type == ScriptType.INLINE ? null : name, code, params);
CompiledScript compiledScript = cache.get(cacheKey);
if (compiledScript == null) {
//Either an un-cached inline script or indexed script
//If the script type is inline the name will be the same as the code for identification in exceptions
try {
compiledScript = new CompiledScript(type, name, lang, scriptEngineService.compile(code, params));
} catch (Exception exception) {
throw new ScriptException("Failed to compile " + type + " script [" + name + "] using lang [" + lang + "]", exception);
}
//Since the cache key is the script content itself we don't need to
//invalidate/check the cache if an indexed script changes.
scriptMetrics.onCompilation();
cache.put(cacheKey, compiledScript);
}
return compiledScript;
}
public void queryScriptIndex(GetIndexedScriptRequest request, final ActionListener<GetResponse> listener) {
String scriptLang = validateScriptLanguage(request.scriptLang());
GetRequest getRequest = new GetRequest(request, SCRIPT_INDEX).type(scriptLang).id(request.id())
.version(request.version()).versionType(request.versionType())
.preference("_local"); //Set preference for no forking
client.get(getRequest, listener);
}
private String validateScriptLanguage(String scriptLang) {
if (scriptLang == null) {
scriptLang = defaultLang;
} else if (scriptEnginesByLang.containsKey(scriptLang) == false) {
throw new IllegalArgumentException("script_lang not supported [" + scriptLang + "]");
}
return scriptLang;
}
String getScriptFromIndex(String scriptLang, String id, HasContextAndHeaders context) {
if (client == null) {
throw new IllegalArgumentException("Got an indexed script with no Client registered.");
}
scriptLang = validateScriptLanguage(scriptLang);
GetRequest getRequest = new GetRequest(SCRIPT_INDEX, scriptLang, id);
getRequest.copyContextAndHeadersFrom(context);
GetResponse responseFields = client.get(getRequest).actionGet();
if (responseFields.isExists()) {
return getScriptFromResponse(responseFields);
}
throw new IllegalArgumentException("Unable to find script [" + SCRIPT_INDEX + "/"
+ scriptLang + "/" + id + "]");
}
private void validate(BytesReference scriptBytes, String scriptLang) {
try {
XContentParser parser = XContentFactory.xContent(scriptBytes).createParser(scriptBytes);
parser.nextToken();
Template template = TemplateQueryParser.parse(scriptLang, parser, parseFieldMatcher, "params", "script", "template");
if (Strings.hasLength(template.getScript())) {
//Just try and compile it
try {
ScriptEngineService scriptEngineService = getScriptEngineServiceForLang(scriptLang);
//we don't know yet what the script will be used for, but if all of the operations for this lang with
//indexed scripts are disabled, it makes no sense to even compile it.
if (isAnyScriptContextEnabled(scriptLang, scriptEngineService, ScriptType.INDEXED)) {
Object compiled = scriptEngineService.compile(template.getScript(), Collections.emptyMap());
if (compiled == null) {
throw new IllegalArgumentException("Unable to parse [" + template.getScript() +
"] lang [" + scriptLang + "] (ScriptService.compile returned null)");
}
} else {
logger.warn(
"skipping compile of script [{}], lang [{}] as all scripted operations are disabled for indexed scripts",
template.getScript(), scriptLang);
}
} catch (Exception e) {
throw new IllegalArgumentException("Unable to parse [" + template.getScript() +
"] lang [" + scriptLang + "]", e);
}
} else {
throw new IllegalArgumentException("Unable to find script in : " + scriptBytes.toUtf8());
}
} catch (IOException e) {
throw new IllegalArgumentException("failed to parse template script", e);
}
}
public void putScriptToIndex(PutIndexedScriptRequest request, ActionListener<IndexResponse> listener) {
String scriptLang = validateScriptLanguage(request.scriptLang());
//verify that the script compiles
validate(request.source(), scriptLang);
IndexRequest indexRequest = new IndexRequest(request).index(SCRIPT_INDEX).type(scriptLang).id(request.id())
.version(request.version()).versionType(request.versionType())
.source(request.source()).opType(request.opType()).refresh(true); //Always refresh after indexing a template
client.index(indexRequest, listener);
}
public void deleteScriptFromIndex(DeleteIndexedScriptRequest request, ActionListener<DeleteResponse> listener) {
String scriptLang = validateScriptLanguage(request.scriptLang());
DeleteRequest deleteRequest = new DeleteRequest(request).index(SCRIPT_INDEX).type(scriptLang).id(request.id())
.refresh(true).version(request.version()).versionType(request.versionType());
client.delete(deleteRequest, listener);
}
@SuppressWarnings("unchecked")
public static String getScriptFromResponse(GetResponse responseFields) {
Map<String, Object> source = responseFields.getSourceAsMap();
if (source.containsKey("template")) {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
Object template = source.get("template");
if (template instanceof Map ){
builder.map((Map<String, Object>)template);
return builder.string();
} else {
return template.toString();
}
} catch (IOException | ClassCastException e) {
throw new IllegalStateException("Unable to parse " + responseFields.getSourceAsString() + " as json", e);
}
} else if (source.containsKey("script")) {
return source.get("script").toString();
} else {
try {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.map(responseFields.getSource());
return builder.string();
} catch (IOException|ClassCastException e) {
throw new IllegalStateException("Unable to parse " + responseFields.getSourceAsString() + " as json", e);
}
}
}
/**
* Compiles (or retrieves from cache) and executes the provided script
*/
public ExecutableScript executable(Script script, ScriptContext scriptContext, HasContextAndHeaders headersContext, Map<String, String> params) {
return executable(compile(script, scriptContext, headersContext, params), script.getParams());
}
/**
* Executes a previously compiled script provided as an argument
*/
public ExecutableScript executable(CompiledScript compiledScript, Map<String, Object> vars) {
return getScriptEngineServiceForLang(compiledScript.lang()).executable(compiledScript, vars);
}
/**
* Compiles (or retrieves from cache) and executes the provided search script
*/
public SearchScript search(SearchLookup lookup, Script script, ScriptContext scriptContext, Map<String, String> params) {
CompiledScript compiledScript = compile(script, scriptContext, SearchContext.current(), params);
return getScriptEngineServiceForLang(compiledScript.lang()).search(compiledScript, lookup, script.getParams());
}
private boolean isAnyScriptContextEnabled(String lang, ScriptEngineService scriptEngineService, ScriptType scriptType) {
for (ScriptContext scriptContext : scriptContextRegistry.scriptContexts()) {
if (canExecuteScript(lang, scriptEngineService, scriptType, scriptContext)) {
return true;
}
}
return false;
}
private boolean canExecuteScript(String lang, ScriptEngineService scriptEngineService, ScriptType scriptType, ScriptContext scriptContext) {
assert lang != null;
if (scriptContextRegistry.isSupportedContext(scriptContext) == false) {
throw new IllegalArgumentException("script context [" + scriptContext.getKey() + "] not supported");
}
ScriptMode mode = scriptModes.getScriptMode(lang, scriptType, scriptContext);
switch (mode) {
case ON:
return true;
case OFF:
return false;
case SANDBOX:
return scriptEngineService.sandboxed();
default:
throw new IllegalArgumentException("script mode [" + mode + "] not supported");
}
}
public ScriptStats stats() {
return scriptMetrics.stats();
}
/**
* A small listener for the script cache that calls each
* {@code ScriptEngineService}'s {@code scriptRemoved} method when the
* script has been removed from the cache
*/
private class ScriptCacheRemovalListener implements RemovalListener<CacheKey, CompiledScript> {
@Override
public void onRemoval(RemovalNotification<CacheKey, CompiledScript> notification) {
scriptMetrics.onCacheEviction();
for (ScriptEngineService service : scriptEngines) {
try {
service.scriptRemoved(notification.getValue());
} catch (Exception e) {
logger.warn("exception calling script removal listener for script service", e);
// We don't rethrow because Guava would just catch the
// exception and log it, which we have already done
}
}
}
}
private class ScriptChangesListener extends FileChangesListener {
private Tuple<String, String> scriptNameExt(Path file) {
Path scriptPath = scriptsDirectory.relativize(file);
int extIndex = scriptPath.toString().lastIndexOf('.');
if (extIndex != -1) {
String ext = scriptPath.toString().substring(extIndex + 1);
String scriptName = scriptPath.toString().substring(0, extIndex).replace(scriptPath.getFileSystem().getSeparator(), "_");
return new Tuple<>(scriptName, ext);
} else {
return null;
}
}
@Override
public void onFileInit(Path file) {
if (logger.isTraceEnabled()) {
logger.trace("Loading script file : [{}]", file);
}
Tuple<String, String> scriptNameExt = scriptNameExt(file);
if (scriptNameExt != null) {
ScriptEngineService engineService = getScriptEngineServiceForFileExt(scriptNameExt.v2());
if (engineService == null) {
logger.warn("no script engine found for [{}]", scriptNameExt.v2());
} else {
try {
//we don't know yet what the script will be used for, but if all of the operations for this lang
// with file scripts are disabled, it makes no sense to even compile it and cache it.
if (isAnyScriptContextEnabled(engineService.types()[0], engineService, ScriptType.FILE)) {
logger.info("compiling script file [{}]", file.toAbsolutePath());
try(InputStreamReader reader = new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8)) {
String script = Streams.copyToString(reader);
CacheKey cacheKey = new CacheKey(engineService, scriptNameExt.v1(), null, Collections.emptyMap());
staticCache.put(cacheKey, new CompiledScript(ScriptType.FILE, scriptNameExt.v1(), engineService.types()[0], engineService.compile(script, Collections.emptyMap())));
scriptMetrics.onCompilation();
}
} else {
logger.warn("skipping compile of script file [{}] as all scripted operations are disabled for file scripts", file.toAbsolutePath());
}
} catch (Throwable e) {
logger.warn("failed to load/compile script [{}]", e, scriptNameExt.v1());
}
}
}
}
@Override
public void onFileCreated(Path file) {
onFileInit(file);
}
@Override
public void onFileDeleted(Path file) {
Tuple<String, String> scriptNameExt = scriptNameExt(file);
if (scriptNameExt != null) {
ScriptEngineService engineService = getScriptEngineServiceForFileExt(scriptNameExt.v2());
assert engineService != null;
logger.info("removing script file [{}]", file.toAbsolutePath());
staticCache.remove(new CacheKey(engineService, scriptNameExt.v1(), null, Collections.emptyMap()));
}
}
@Override
public void onFileChanged(Path file) {
onFileInit(file);
}
}
/**
* The type of a script, more specifically where it gets loaded from:
* - provided dynamically at request time
* - loaded from an index
* - loaded from file
*/
public static enum ScriptType {
INLINE(0, "inline"),
INDEXED(1, "id"),
FILE(2, "file");
private final int val;
private final ParseField parseField;
public static ScriptType readFrom(StreamInput in) throws IOException {
int scriptTypeVal = in.readVInt();
for (ScriptType type : values()) {
if (type.val == scriptTypeVal) {
return type;
}
}
throw new IllegalArgumentException("Unexpected value read for ScriptType got [" + scriptTypeVal + "] expected one of ["
+ INLINE.val + "," + FILE.val + "," + INDEXED.val + "]");
}
public static void writeTo(ScriptType scriptType, StreamOutput out) throws IOException{
if (scriptType != null) {
out.writeVInt(scriptType.val);
} else {
out.writeVInt(INLINE.val); //Default to inline
}
}
private ScriptType(int val, String name) {
this.val = val;
this.parseField = new ParseField(name);
}
public ParseField getParseField() {
return parseField;
}
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
}
private static final class CacheKey {
final String lang;
final String name;
final String code;
final Map<String, String> params;
private CacheKey(final ScriptEngineService service, final String name, final String code, final Map<String, String> params) {
this.lang = service.types()[0];
this.name = name;
this.code = code;
this.params = params;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey)o;
if (!lang.equals(cacheKey.lang)) return false;
if (name != null ? !name.equals(cacheKey.name) : cacheKey.name != null) return false;
if (code != null ? !code.equals(cacheKey.code) : cacheKey.code != null) return false;
return params.equals(cacheKey.params);
}
@Override
public int hashCode() {
int result = lang.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (code != null ? code.hashCode() : 0);
result = 31 * result + params.hashCode();
return result;
}
}
private static class IndexedScript {
private final String lang;
private final String id;
IndexedScript(String lang, String script) {
this.lang = lang;
final String[] parts = script.split("/");
if (parts.length == 1) {
this.id = script;
} else {
if (parts.length != 3) {
throw new IllegalArgumentException("Illegal index script format [" + script + "]" +
" should be /lang/id");
} else {
if (!parts[1].equals(this.lang)) {
throw new IllegalStateException("Conflicting script language, found [" + parts[1] + "] expected + ["+ this.lang + "]");
}
this.id = parts[2];
}
}
}
}
}
| |
package org.sakaiproject.component.app.scheduler;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.sakaiproject.api.app.scheduler.DelayedInvocation;
import org.sakaiproject.api.app.scheduler.ScheduledInvocationManager;
import org.sakaiproject.api.app.scheduler.SchedulerManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.app.scheduler.jobs.ScheduledInvocationRunner;
import org.sakaiproject.db.api.SqlService;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.time.api.Time;
public class ScheduledInvocationManagerImpl implements ScheduledInvocationManager {
private static final Log LOG = LogFactory.getLog(ScheduledInvocationManagerImpl.class);
private static final String SCHEDULED_INVOCATION_RUNNER_DEFAULT_INTERVAL_PROPERTY = "jobscheduler.invocation.interval";
private static final int SCHEDULED_INVOCATION_RUNNER_DEFAULT_INTERVAL = 120; //default: time in seconds, run every 2 mins
/** Dependency: IdManager */
protected IdManager m_idManager = null;
public void setIdManager(IdManager service) {
m_idManager = service;
}
/** Dependency: SqlService */
protected SqlService m_sqlService = null;
public void setSqlService(SqlService service) {
m_sqlService = service;
}
/** Dependency: SchedulerManager */
protected SchedulerManager m_schedulerManager = null;
public void setSchedulerManager(SchedulerManager service) {
m_schedulerManager = service;
}
/** Dependency: ServerConfigurationService */
protected ServerConfigurationService m_serverConfigurationService = null;
public void setServerConfigurationService(ServerConfigurationService service) {
m_serverConfigurationService = service;
}
/** Configuration: Should we autocreate our database tables */
protected boolean autoDdl;
public void setAutoDdl(boolean autoDdl) {
this.autoDdl = autoDdl;
}
public void init() {
LOG.info("init()");
if (autoDdl) {
m_sqlService.ddl(getClass().getClassLoader(), "delayed");
// Create the additional indexes as hibernate currently fails todo this.
// Once hibernate is updated to 3.6 it should be able to manage in it's own.
m_sqlService.ddl(getClass().getClassLoader(), "indexes");
}
try {
registerScheduledInvocationRunner();
} catch (SchedulerException e) {
LOG.error("failed to schedule ScheduledInvocationRunner job", e);
}
}
public void destroy() {
LOG.info("destroy()");
}
protected void registerScheduledInvocationRunner() throws SchedulerException {
//trigger will not start immediately, wait until interval has passed before 1st run
long startTime = System.currentTimeMillis() + getScheduledInvocationRunnerInterval();
JobDetail detail = new JobDetail("org.sakaiproject.component.app.scheduler.ScheduledInvocationManagerImpl.runner",
"org.sakaiproject.component.app.scheduler.ScheduledInvocationManagerImpl", ScheduledInvocationRunner.class);
Trigger trigger = new SimpleTrigger("org.sakaiproject.component.app.scheduler.ScheduledInvocationManagerImpl.runner",
"org.sakaiproject.component.app.scheduler.ScheduledInvocationManagerImpl", new Date(startTime), null, SimpleTrigger.REPEAT_INDEFINITELY,
getScheduledInvocationRunnerInterval());
Scheduler scheduler = m_schedulerManager.getScheduler();
// This removes the jobs if there are no trigger left on it.
scheduler.unscheduleJob(trigger.getName(), trigger.getGroup());
scheduler.scheduleJob(detail, trigger);
}
protected int getScheduledInvocationRunnerInterval() {
// convert seconds to millis
return 1000 * m_serverConfigurationService.getInt(SCHEDULED_INVOCATION_RUNNER_DEFAULT_INTERVAL_PROPERTY, SCHEDULED_INVOCATION_RUNNER_DEFAULT_INTERVAL);
}
/* (non-Javadoc)
* @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#createDelayedInvocation(org.sakaiproject.time.api.Time, java.lang.String, java.lang.String)
*/
public String createDelayedInvocation(Time time, String componentId, String opaqueContext) {
String uuid = m_idManager.createUuid();
LOG.debug("Creating new Delayed Invocation: " + uuid);
String sql = "INSERT INTO SCHEDULER_DELAYED_INVOCATION VALUES(?,?,?,?)";
Object[] fields = new Object[4];
fields[0] = uuid;
fields[1] = time;
fields[2] = componentId;
fields[3] = opaqueContext;
LOG.debug("SQL: " + sql);
if (m_sqlService.dbWrite(sql, fields)) {
LOG.info("Created new Delayed Invocation: uuid=" + uuid);
return uuid;
} else {
LOG.error("Failed to create new Delayed Invocation: componentId=" + componentId +
", opaqueContext=" + opaqueContext);
return null;
}
}
/* (non-Javadoc)
* @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#deleteDelayedInvocation(java.lang.String)
*/
public void deleteDelayedInvocation(String uuid) {
LOG.debug("Removing Delayed Invocation: " + uuid);
String sql = "DELETE FROM SCHEDULER_DELAYED_INVOCATION WHERE INVOCATION_ID = ?";
Object[] fields = new Object[1];
fields[0] = uuid;
LOG.debug("SQL: " + sql);
m_sqlService.dbWrite(sql, fields);
}
/* (non-Javadoc)
* @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#deleteDelayedInvocation(java.lang.String, java.lang.String)
*/
public void deleteDelayedInvocation(String componentId, String opaqueContext) {
LOG.debug("componentId=" + componentId + ", opaqueContext=" + opaqueContext);
//String sql = "DELETE FROM SCHEDULER_DELAYED_INVOCATION WHERE COMPONENT = ? AND CONTEXT = ?";
String sql = "DELETE FROM SCHEDULER_DELAYED_INVOCATION";
Object[] fields = new Object[0];
if (componentId.length() > 0 && opaqueContext.length() > 0) {
// both non-blank
sql += " WHERE COMPONENT = ? AND CONTEXT = ?";
fields = new Object[2];
fields[0] = componentId;
fields[1] = opaqueContext;
} else if (componentId.length() > 0) {
// context blank
sql += " WHERE COMPONENT = ?";
fields = new Object[1];
fields[0] = componentId;
} else if (opaqueContext.length() > 0) {
// component blank
sql += " WHERE CONTEXT = ?";
fields = new Object[1];
fields[0] = opaqueContext;
} else {
// both blank
}
LOG.debug("SQL: " + sql);
if ( m_sqlService.dbWrite(sql, fields) ) {
LOG.info("Removed all scheduled invocations matching: componentId=" + componentId + ", opaqueContext=" + opaqueContext);
} else {
LOG.error("Failure while attempting to remove invocations matching: componentId=" + componentId + ", opaqueContext=" + opaqueContext);
}
}
/* (non-Javadoc)
* @see org.sakaiproject.api.app.scheduler.ScheduledInvocationManager#findDelayedInvocations(java.lang.String, java.lang.String)
*/
public DelayedInvocation[] findDelayedInvocations(String componentId, String opaqueContext) {
LOG.debug("componentId=" + componentId + ", opaqueContext=" + opaqueContext);
//String sql = "SELECT * FROM SCHEDULER_DELAYED_INVOCATION WHERE COMPONENT = ? AND CONTEXT = ?";
String sql = "SELECT * FROM SCHEDULER_DELAYED_INVOCATION";
Object[] fields = new Object[0];
if (componentId.length() > 0 && opaqueContext.length() > 0) {
// both non-blank
sql += " WHERE COMPONENT = ? AND CONTEXT = ?";
fields = new Object[2];
fields[0] = componentId;
fields[1] = opaqueContext;
} else if (componentId.length() > 0) {
// context blank
sql += " WHERE COMPONENT = ?";
fields = new Object[1];
fields[0] = componentId;
} else if (opaqueContext.length() > 0) {
// component blank
sql += " WHERE CONTEXT = ?";
fields = new Object[1];
fields[0] = opaqueContext;
} else {
// both blank
}
List invocations = m_sqlService.dbRead(sql, fields, new DelayedInvocationReader());
return (DelayedInvocation[]) invocations.toArray( new DelayedInvocation[] {} );
}
}
| |
/*
* Copyright 2014 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.sdnip;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.host.HostService;
import org.onosproject.net.host.InterfaceIpAddress;
import org.onosproject.net.host.PortAddresses;
import org.onosproject.sdnip.config.Interface;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Unit tests for the HostToInterfaceAdaptor class.
*/
public class HostToInterfaceAdaptorTest {
private HostService hostService;
private HostToInterfaceAdaptor adaptor;
private Set<PortAddresses> portAddresses;
private Map<ConnectPoint, Interface> interfaces;
private static final ConnectPoint CP1 = new ConnectPoint(
DeviceId.deviceId("of:1"), PortNumber.portNumber(1));
private static final ConnectPoint CP2 = new ConnectPoint(
DeviceId.deviceId("of:1"), PortNumber.portNumber(2));
private static final ConnectPoint CP3 = new ConnectPoint(
DeviceId.deviceId("of:2"), PortNumber.portNumber(1));
private static final ConnectPoint NON_EXISTENT_CP = new ConnectPoint(
DeviceId.deviceId("doesnotexist"), PortNumber.portNumber(1));
@Before
public void setUp() throws Exception {
hostService = createMock(HostService.class);
portAddresses = Sets.newHashSet();
interfaces = Maps.newHashMap();
InterfaceIpAddress ia11 =
new InterfaceIpAddress(IpAddress.valueOf("192.168.1.1"),
IpPrefix.valueOf("192.168.1.0/24"));
createPortAddressesAndInterface(CP1,
Sets.newHashSet(ia11),
MacAddress.valueOf("00:00:00:00:00:01"));
// Two addresses in the same subnet
InterfaceIpAddress ia21 =
new InterfaceIpAddress(IpAddress.valueOf("192.168.2.1"),
IpPrefix.valueOf("192.168.2.0/24"));
InterfaceIpAddress ia22 =
new InterfaceIpAddress(IpAddress.valueOf("192.168.2.2"),
IpPrefix.valueOf("192.168.2.0/24"));
createPortAddressesAndInterface(CP2,
Sets.newHashSet(ia21, ia22),
MacAddress.valueOf("00:00:00:00:00:02"));
// Two addresses in different subnets
InterfaceIpAddress ia31 =
new InterfaceIpAddress(IpAddress.valueOf("192.168.3.1"),
IpPrefix.valueOf("192.168.3.0/24"));
InterfaceIpAddress ia41 =
new InterfaceIpAddress(IpAddress.valueOf("192.168.4.1"),
IpPrefix.valueOf("192.168.4.0/24"));
createPortAddressesAndInterface(CP3,
Sets.newHashSet(ia31, ia41),
MacAddress.valueOf("00:00:00:00:00:03"));
expect(hostService.getAddressBindings()).andReturn(portAddresses).anyTimes();
replay(hostService);
adaptor = new HostToInterfaceAdaptor(hostService);
}
/**
* Creates both a PortAddresses and an Interface for the given inputs and
* places them in the correct global data stores.
*
* @param cp the connect point
* @param ipAddresses the set of interface IP addresses
* @param mac the MAC address
*/
private void createPortAddressesAndInterface(
ConnectPoint cp, Set<InterfaceIpAddress> ipAddresses,
MacAddress mac) {
PortAddresses pa = new PortAddresses(cp, ipAddresses, mac);
portAddresses.add(pa);
expect(hostService.getAddressBindingsForPort(cp)).andReturn(
Collections.singleton(pa)).anyTimes();
Interface intf = new Interface(cp, ipAddresses, mac);
interfaces.put(cp, intf);
}
/**
* Tests {@link HostToInterfaceAdaptor#getInterfaces()}.
* Verifies that the set of interfaces returned matches what is expected
* based on the input PortAddresses data.
*/
@Test
public void testGetInterfaces() {
Set<Interface> adaptorIntfs = adaptor.getInterfaces();
assertEquals(3, adaptorIntfs.size());
assertTrue(adaptorIntfs.contains(this.interfaces.get(CP1)));
assertTrue(adaptorIntfs.contains(this.interfaces.get(CP2)));
assertTrue(adaptorIntfs.contains(this.interfaces.get(CP3)));
}
/**
* Tests {@link HostToInterfaceAdaptor#getInterface(ConnectPoint)}.
* Verifies that the correct interface is returned for a given connect
* point.
*/
@Test
public void testGetInterface() {
assertEquals(this.interfaces.get(CP1), adaptor.getInterface(CP1));
assertEquals(this.interfaces.get(CP2), adaptor.getInterface(CP2));
assertEquals(this.interfaces.get(CP3), adaptor.getInterface(CP3));
// Try and get an interface for a connect point with no addresses
reset(hostService);
expect(hostService.getAddressBindingsForPort(NON_EXISTENT_CP))
.andReturn(Collections.<PortAddresses>emptySet()).anyTimes();
replay(hostService);
assertNull(adaptor.getInterface(NON_EXISTENT_CP));
}
/**
* Tests {@link HostToInterfaceAdaptor#getInterface(ConnectPoint)} in the
* case that the input connect point is null.
* Verifies that a NullPointerException is thrown.
*/
@Test(expected = NullPointerException.class)
public void testGetInterfaceNull() {
adaptor.getInterface(null);
}
/**
* Tests {@link HostToInterfaceAdaptor#getMatchingInterface(IpAddress)}.
* Verifies that the correct interface is returned based on the given IP
* address.
*/
@Test
public void testGetMatchingInterface() {
assertEquals(this.interfaces.get(CP1),
adaptor.getMatchingInterface(IpAddress.valueOf("192.168.1.100")));
assertEquals(this.interfaces.get(CP2),
adaptor.getMatchingInterface(IpAddress.valueOf("192.168.2.100")));
assertEquals(this.interfaces.get(CP3),
adaptor.getMatchingInterface(IpAddress.valueOf("192.168.3.100")));
assertEquals(this.interfaces.get(CP3),
adaptor.getMatchingInterface(IpAddress.valueOf("192.168.4.100")));
// Try and match an address we don't have subnet configured for
assertNull(adaptor.getMatchingInterface(IpAddress.valueOf("1.1.1.1")));
}
/**
* Tests {@link HostToInterfaceAdaptor#getMatchingInterface(IpAddress)} in the
* case that the input IP address is null.
* Verifies that a NullPointerException is thrown.
*/
@Test(expected = NullPointerException.class)
public void testGetMatchingInterfaceNull() {
adaptor.getMatchingInterface(null);
}
}
| |
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.Common.CraftingSkill.CraftParms;
import com.planet_ink.coffee_mud.Abilities.Common.CraftingSkill.CraftingActivity;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ListingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2002-2015 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class Carpentry extends EnhancedCraftingSkill implements ItemCraftor
{
@Override public String ID() { return "Carpentry"; }
private final static String localizedName = CMLib.lang().L("Carpentry");
@Override public String name() { return localizedName; }
private static final String[] triggerStrings =I(new String[] {"CARVE","CARPENTRY"});
@Override public String[] triggerStrings(){return triggerStrings;}
@Override public String supportedResourceString(){return "WOODEN";}
@Override
public String parametersFormat(){ return
"ITEM_NAME\tITEM_LEVEL\tBUILD_TIME_TICKS\tMATERIALS_REQUIRED\t"
+"ITEM_BASE_VALUE\tITEM_CLASS_ID\t"
+"LID_LOCK||STATUE||RIDE_BASIS||WEAPON_CLASS||CODED_WEAR_LOCATION||SMOKE_FLAG\t"
+"CONTAINER_CAPACITY||WEAPON_HANDS_REQUIRED||LIQUID_CAPACITY||LIGHT_DURATION\t"
+"BASE_ARMOR_AMOUNT||BASE_DAMAGE\tCONTAINER_TYPE||ATTACK_MODIFICATION\tCODED_SPELL_LIST";}
//protected static final int RCP_FINALNAME=0;
//protected static final int RCP_LEVEL=1;
//protected static final int RCP_TICKS=2;
protected static final int RCP_WOOD=3;
protected static final int RCP_VALUE=4;
protected static final int RCP_CLASSTYPE=5;
protected static final int RCP_MISCTYPE=6;
protected static final int RCP_CAPACITY=7;
protected static final int RCP_ARMORDMG=8;
protected static final int RCP_CONTAINMASK=9;
protected static final int RCP_SPELL=10;
protected DoorKey key=null;
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((affected!=null)&&(affected instanceof MOB)&&(tickID==Tickable.TICKID_MOB))
{
if(buildingI==null)
unInvoke();
}
return super.tick(ticking,tickID);
}
@Override public String parametersFile(){ return "carpentry.txt";}
@Override protected List<List<String>> loadRecipes(){return super.loadRecipes(parametersFile());}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if((buildingI!=null)&&(!aborted))
{
if(messedUp)
{
if(activity == CraftingActivity.MENDING)
messedUpCrafting(mob);
else
if(activity == CraftingActivity.LEARNING)
{
commonEmote(mob,L("<S-NAME> fail(s) to learn how to make @x1.",buildingI.name()));
buildingI.destroy();
}
else
if(activity == CraftingActivity.REFITTING)
commonEmote(mob,L("<S-NAME> mess(es) up refitting @x1.",buildingI.name()));
else
commonEmote(mob,L("<S-NAME> mess(es) up carving @x1.",buildingI.name()));
}
else
{
if(activity == CraftingActivity.MENDING)
buildingI.setUsesRemaining(100);
else
if(activity==CraftingActivity.LEARNING)
{
deconstructRecipeInto( buildingI, recipeHolder );
buildingI.destroy();
}
else
if(activity == CraftingActivity.REFITTING)
{
buildingI.basePhyStats().setHeight(0);
buildingI.recoverPhyStats();
}
else
{
dropAWinner(mob,buildingI);
if(key!=null)
{
dropAWinner(mob,key);
if(buildingI instanceof Container)
key.setContainer((Container)buildingI);
}
}
}
}
buildingI=null;
key=null;
activity = CraftingActivity.CRAFTING;
}
}
super.unInvoke();
}
@Override
public boolean mayICraft(final Item I)
{
if(I==null)
return false;
if(!super.mayBeCrafted(I))
return false;
if((I.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN)
return false;
if(CMLib.flags().isDeadlyOrMaliciousEffect(I))
return false;
if(I instanceof MusicalInstrument)
return false;
if(I instanceof Rideable)
{
final Rideable R=(Rideable)I;
final int rideType=R.rideBasis();
switch(rideType)
{
case Rideable.RIDEABLE_LADDER:
case Rideable.RIDEABLE_SLEEP:
case Rideable.RIDEABLE_SIT:
case Rideable.RIDEABLE_TABLE:
return true;
default:
return false;
}
}
if(I instanceof Shield)
return true;
if(I instanceof Weapon)
{
final Weapon W=(Weapon)I;
if(((W.weaponClassification()!=Weapon.CLASS_BLUNT)&&(W.weaponClassification()!=Weapon.CLASS_STAFF))
||((W instanceof AmmunitionWeapon) && ((AmmunitionWeapon)W).requiresAmmunition()))
return false;
return true;
}
if(I instanceof Light)
return true;
if(I instanceof Ammunition)
return false;
if(I instanceof Armor)
return (isANativeItem(I.Name()));
if(I instanceof Container)
{
final Container C=(Container)I;
if((C.containTypes()==Container.CONTAIN_CAGED)
||(C.containTypes()==(Container.CONTAIN_BODIES|Container.CONTAIN_CAGED)))
return false;
return true;
}
if((I instanceof Drink)&&(!(I instanceof Potion)))
return true;
if(I instanceof FalseLimb)
return true;
if(I.rawProperLocationBitmap()==Wearable.WORN_HELD)
return true;
return (isANativeItem(I.Name()));
}
public boolean supportsMending(Physical I){ return canMend(null,I,true);}
@Override
protected boolean canMend(MOB mob, Environmental E, boolean quiet)
{
if(!super.canMend(mob,E,quiet))
return false;
if((!(E instanceof Item))
||(!mayICraft((Item)E)))
{
if(!quiet)
commonTell(mob,L("That's not a carpentry item."));
return false;
}
return true;
}
@Override
public String getDecodedComponentsDescription(final MOB mob, final List<String> recipe)
{
return super.getComponentDescription( mob, recipe, RCP_WOOD );
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
if(super.checkStop(mob, commands))
return true;
final CraftParms parsedVars=super.parseAutoGenerate(auto,givenTarget,commands);
givenTarget=parsedVars.givenTarget;
final PairVector<Integer,Integer> enhancedTypes=enhancedTypes(mob,commands);
randomRecipeFix(mob,addRecipes(mob,loadRecipes()),commands,parsedVars.autoGenerate);
if(commands.size()==0)
{
commonTell(mob,L("Carve what? Enter \"carve list\" for a list, \"carve refit <item>\" to resize shoes or armor, \"carve learn <item>\", \"carve scan\", \"carve mend <item>\", or \"carve stop\" to cancel."));
return false;
}
if((!auto)
&&(commands.size()>0)
&&(((String)commands.firstElement()).equalsIgnoreCase("bundle")))
{
bundling=true;
if(super.invoke(mob,commands,givenTarget,auto,asLevel))
return super.bundle(mob,commands);
return false;
}
final List<List<String>> recipes=addRecipes(mob,loadRecipes());
final String str=(String)commands.elementAt(0);
String startStr=null;
int duration=4;
bundling=false;
final int[] cols={
ListingLibrary.ColFixer.fixColWidth(29,mob.session()),
ListingLibrary.ColFixer.fixColWidth(3,mob.session()),
ListingLibrary.ColFixer.fixColWidth(4,mob.session())
};
if(str.equalsIgnoreCase("list"))
{
String mask=CMParms.combine(commands,1);
boolean allFlag=false;
if(mask.equalsIgnoreCase("all"))
{
allFlag=true;
mask="";
}
final StringBuffer buf=new StringBuffer(L("Item <S-NAME> <S-IS-ARE> skilled at carving:\n\r"));
int toggler=1;
final int toggleTop=2;
for(int r=0;r<toggleTop;r++)
buf.append((r>0?" ":"")+CMStrings.padRight(L("Item"),cols[0])+" "+CMStrings.padRight(L("Lvl"),cols[1])+" "+CMStrings.padRight(L("Wood"),cols[2]));
buf.append("\n\r");
for(int r=0;r<recipes.size();r++)
{
final List<String> V=recipes.get(r);
if(V.size()>0)
{
final String item=replacePercent(V.get(RCP_FINALNAME),"");
final int level=CMath.s_int(V.get(RCP_LEVEL));
final String wood=getComponentDescription(mob,V,RCP_WOOD);
if(wood.length()>5)
{
if(toggler>1)
buf.append("\n\r");
toggler=toggleTop;
}
if(((level<=xlevel(mob))||allFlag)
&&((mask.length()==0)||mask.equalsIgnoreCase("all")||CMLib.english().containsString(item,mask)))
{
buf.append(CMStrings.padRight(item,cols[0])+" "+CMStrings.padRight(""+level,cols[1])+" "+CMStrings.padRightPreserve(""+wood,cols[2])+((toggler!=toggleTop)?" ":"\n\r"));
if(++toggler>toggleTop)
toggler=1;
}
}
}
if(toggler!=1)
buf.append("\n\r");
commonTell(mob,buf.toString());
enhanceList(mob);
return true;
}
else
if((commands.firstElement() instanceof String)&&(((String)commands.firstElement())).equalsIgnoreCase("learn"))
{
return doLearnRecipe(mob, commands, givenTarget, auto, asLevel);
}
else
if(str.equalsIgnoreCase("scan"))
return publicScan(mob,commands);
else
if(str.equalsIgnoreCase("mend"))
{
buildingI=null;
activity = CraftingActivity.CRAFTING;
key=null;
messedUp=false;
final Vector newCommands=CMParms.parse(CMParms.combine(commands,1));
buildingI=getTarget(mob,mob.location(),givenTarget,newCommands,Wearable.FILTER_UNWORNONLY);
if(!canMend(mob, buildingI,false))
return false;
activity = CraftingActivity.MENDING;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
startStr=L("<S-NAME> start(s) mending @x1.",buildingI.name());
displayText=L("You are mending @x1",buildingI.name());
verb=L("mending @x1",buildingI.name());
}
else
if(str.equalsIgnoreCase("refit"))
{
buildingI=null;
activity = CraftingActivity.CRAFTING;
messedUp=false;
final Vector newCommands=CMParms.parse(CMParms.combine(commands,1));
buildingI=getTarget(mob,mob.location(),givenTarget,newCommands,Wearable.FILTER_UNWORNONLY);
if(buildingI==null)
return false;
if((buildingI.material()&RawMaterial.MATERIAL_MASK)!=RawMaterial.MATERIAL_WOODEN)
{
commonTell(mob,L("That's not made of wood. That can't be refitted."));
return false;
}
if(!(buildingI instanceof Armor))
{
commonTell(mob,L("You don't know how to refit that sort of thing."));
return false;
}
if(buildingI.phyStats().height()==0)
{
commonTell(mob,L("@x1 is already the right size.",buildingI.name(mob)));
return false;
}
activity = CraftingActivity.REFITTING;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
startStr=L("<S-NAME> start(s) refitting @x1.",buildingI.name());
displayText=L("You are refitting @x1",buildingI.name());
verb=L("refitting @x1",buildingI.name());
}
else
{
buildingI=null;
activity = CraftingActivity.CRAFTING;
aborted=false;
key=null;
messedUp=false;
int amount=-1;
if((commands.size()>1)&&(CMath.isNumber((String)commands.lastElement())))
{
amount=CMath.s_int((String)commands.lastElement());
commands.removeElementAt(commands.size()-1);
}
final String recipeName=CMParms.combine(commands,0);
List<String> foundRecipe=null;
final List<List<String>> matches=matchingRecipeNames(recipes,recipeName,true);
for(int r=0;r<matches.size();r++)
{
final List<String> V=matches.get(r);
if(V.size()>0)
{
final int level=CMath.s_int(V.get(RCP_LEVEL));
if((parsedVars.autoGenerate>0)||(level<=xlevel(mob)))
{
foundRecipe=V;
break;
}
}
}
if(foundRecipe==null)
{
commonTell(mob,L("You don't know how to carve a '@x1'. Try \"carve list\" for a list.",recipeName));
return false;
}
final String woodRequiredStr = foundRecipe.get(RCP_WOOD);
final List<Object> componentsFoundList=getAbilityComponents(mob, woodRequiredStr, "make "+CMLib.english().startWithAorAn(recipeName),parsedVars.autoGenerate);
if(componentsFoundList==null)
return false;
int woodRequired=CMath.s_int(woodRequiredStr);
woodRequired=adjustWoodRequired(woodRequired,mob);
if(amount>woodRequired)
woodRequired=amount;
final String misctype=foundRecipe.get(RCP_MISCTYPE);
final int[] pm={RawMaterial.MATERIAL_WOODEN};
bundling=misctype.equalsIgnoreCase("BUNDLE");
final int[][] data=fetchFoundResourceData(mob,
woodRequired,"wood",pm,
0,null,null,
bundling,
parsedVars.autoGenerate,
enhancedTypes);
if(data==null)
return false;
fixDataForComponents(data,componentsFoundList);
woodRequired=data[0][FOUND_AMT];
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final int lostValue=parsedVars.autoGenerate>0?0:
CMLib.materials().destroyResourcesValue(mob.location(),woodRequired,data[0][FOUND_CODE],0,null)
+CMLib.ableMapper().destroyAbilityComponents(componentsFoundList);
buildingI=CMClass.getItem(foundRecipe.get(RCP_CLASSTYPE));
if(buildingI==null)
{
commonTell(mob,L("There's no such thing as a @x1!!!",foundRecipe.get(RCP_CLASSTYPE)));
return false;
}
duration=getDuration(CMath.s_int(foundRecipe.get(RCP_TICKS)),mob,CMath.s_int(foundRecipe.get(RCP_LEVEL)),4);
String itemName=replacePercent(foundRecipe.get(RCP_FINALNAME),RawMaterial.CODES.NAME(data[0][FOUND_CODE])).toLowerCase();
if(bundling)
itemName="a "+woodRequired+"# "+itemName;
else
itemName=CMLib.english().startWithAorAn(itemName);
buildingI.setName(itemName);
startStr=L("<S-NAME> start(s) carving @x1.",buildingI.name());
displayText=L("You are carving @x1",buildingI.name());
playSound="sawing.wav";
verb=L("carving @x1",buildingI.name());
buildingI.setDisplayText(L("@x1 lies here",itemName));
buildingI.setDescription(itemName+". ");
buildingI.basePhyStats().setWeight(getStandardWeight(woodRequired,bundling));
buildingI.setBaseValue(CMath.s_int(foundRecipe.get(RCP_VALUE)));
buildingI.setMaterial(data[0][FOUND_CODE]);
final int hardness=RawMaterial.CODES.HARDNESS(data[0][FOUND_CODE])-3;
buildingI.basePhyStats().setLevel(CMath.s_int(foundRecipe.get(RCP_LEVEL))+(hardness));
if(buildingI.basePhyStats().level()<1)
buildingI.basePhyStats().setLevel(1);
buildingI.setSecretIdentity(getBrand(mob));
final int capacity=CMath.s_int(foundRecipe.get(RCP_CAPACITY));
final long canContain=getContainerType(foundRecipe.get(RCP_CONTAINMASK));
final int armordmg=CMath.s_int(foundRecipe.get(RCP_ARMORDMG));
if(bundling)
buildingI.setBaseValue(lostValue);
final String spell=(foundRecipe.size()>RCP_SPELL)?foundRecipe.get(RCP_SPELL).trim():"";
addSpells(buildingI,spell);
key=null;
if((buildingI instanceof Container)
&&(!(buildingI instanceof Armor)))
{
if(capacity>0)
{
((Container)buildingI).setCapacity(capacity+woodRequired);
((Container)buildingI).setContainTypes(canContain);
}
if(misctype.equalsIgnoreCase("LID"))
((Container)buildingI).setDoorsNLocks(true,false,true,false,false,false);
else
if(misctype.equalsIgnoreCase("LOCK"))
{
((Container)buildingI).setDoorsNLocks(true,false,true,true,false,true);
((Container)buildingI).setKeyName(Double.toString(Math.random()));
key=(DoorKey)CMClass.getItem("GenKey");
key.setKey(((Container)buildingI).keyName());
key.setName(L("a key"));
key.setDisplayText(L("a small key sits here"));
key.setDescription(L("looks like a key to @x1",buildingI.name()));
key.recoverPhyStats();
key.text();
}
}
if(buildingI instanceof Drink)
{
if(CMLib.flags().isGettable(buildingI))
{
((Drink)buildingI).setLiquidHeld(capacity*50);
((Drink)buildingI).setThirstQuenched(250);
if((capacity*50)<250)
((Drink)buildingI).setThirstQuenched(capacity*50);
((Drink)buildingI).setLiquidRemaining(0);
}
}
if(buildingI instanceof Rideable)
{
setRideBasis((Rideable)buildingI,misctype);
if(capacity==0)
((Rideable)buildingI).setRiderCapacity(1);
else
if(capacity<5)
((Rideable)buildingI).setRiderCapacity(capacity);
}
if(buildingI instanceof Weapon)
{
((Weapon)buildingI).setWeaponClassification(Weapon.CLASS_BLUNT);
setWeaponTypeClass((Weapon)buildingI,misctype,Weapon.TYPE_SLASHING);
buildingI.basePhyStats().setAttackAdjustment((abilityCode()+(hardness*5)-1));
buildingI.basePhyStats().setDamage(armordmg+hardness);
((Weapon)buildingI).setRawProperLocationBitmap(Wearable.WORN_WIELD|Wearable.WORN_HELD);
((Weapon)buildingI).setRawLogicalAnd((capacity>1));
if(!(buildingI instanceof Container))
buildingI.basePhyStats().setAttackAdjustment(buildingI.basePhyStats().attackAdjustment()+(int)canContain);
}
if((buildingI instanceof Armor)&&(!(buildingI instanceof FalseLimb)))
{
((Armor)buildingI).basePhyStats().setArmor(0);
if(armordmg!=0)
((Armor)buildingI).basePhyStats().setArmor(armordmg+(abilityCode()-1));
setWearLocation(buildingI,misctype,hardness);
}
if(buildingI instanceof Light)
{
((Light)buildingI).setDuration(capacity);
if((buildingI instanceof Container)
&&(!misctype.equals("SMOKE")))
{
((Light)buildingI).setDuration(200);
((Container)buildingI).setCapacity(0);
}
}
buildingI.recoverPhyStats();
buildingI.text();
buildingI.recoverPhyStats();
}
messedUp=!proficiencyCheck(mob,0,auto);
if(bundling)
{
messedUp=false;
duration=1;
verb=L("bundling @x1",RawMaterial.CODES.NAME(buildingI.material()).toLowerCase());
startStr=L("<S-NAME> start(s) @x1.",verb);
displayText=L("You are @x1",verb);
}
if(parsedVars.autoGenerate>0)
{
if(key!=null)
commands.add(key);
commands.add(buildingI);
return true;
}
final CMMsg msg=CMClass.getMsg(mob,buildingI,this,getActivityMessageType(),startStr);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
buildingI=(Item)msg.target();
beneficialAffect(mob,mob,asLevel,duration);
enhanceItem(mob,buildingI,enhancedTypes);
}
else
if(bundling)
{
messedUp=false;
aborted=false;
unInvoke();
}
return true;
}
}
| |
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.openapi.models;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Objects;
/**
* StatefulSet represents a set of pods with consistent identities. Identities are defined as: -
* Network: A single stable DNS and hostname. - Storage: As many VolumeClaims as requested. The
* StatefulSet guarantees that a given network identity will always map to the same storage
* identity.
*/
@ApiModel(
description =
"StatefulSet represents a set of pods with consistent identities. Identities are defined as: - Network: A single stable DNS and hostname. - Storage: As many VolumeClaims as requested. The StatefulSet guarantees that a given network identity will always map to the same storage identity.")
@javax.annotation.Generated(
value = "org.openapitools.codegen.languages.JavaClientCodegen",
date = "2021-12-10T19:11:23.904Z[Etc/UTC]")
public class V1StatefulSet implements io.kubernetes.client.common.KubernetesObject {
public static final String SERIALIZED_NAME_API_VERSION = "apiVersion";
@SerializedName(SERIALIZED_NAME_API_VERSION)
private String apiVersion;
public static final String SERIALIZED_NAME_KIND = "kind";
@SerializedName(SERIALIZED_NAME_KIND)
private String kind;
public static final String SERIALIZED_NAME_METADATA = "metadata";
@SerializedName(SERIALIZED_NAME_METADATA)
private V1ObjectMeta metadata;
public static final String SERIALIZED_NAME_SPEC = "spec";
@SerializedName(SERIALIZED_NAME_SPEC)
private V1StatefulSetSpec spec;
public static final String SERIALIZED_NAME_STATUS = "status";
@SerializedName(SERIALIZED_NAME_STATUS)
private V1StatefulSetStatus status;
public V1StatefulSet apiVersion(String apiVersion) {
this.apiVersion = apiVersion;
return this;
}
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should
* convert recognized schemas to the latest internal value, and may reject unrecognized values.
* More info:
* https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
*
* @return apiVersion
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
public String getApiVersion() {
return apiVersion;
}
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
public V1StatefulSet kind(String kind) {
this.kind = kind;
return this;
}
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer
* this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More
* info:
* https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
*
* @return kind
*/
@javax.annotation.Nullable
@ApiModelProperty(
value =
"Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public V1StatefulSet metadata(V1ObjectMeta metadata) {
this.metadata = metadata;
return this;
}
/**
* Get metadata
*
* @return metadata
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public V1ObjectMeta getMetadata() {
return metadata;
}
public void setMetadata(V1ObjectMeta metadata) {
this.metadata = metadata;
}
public V1StatefulSet spec(V1StatefulSetSpec spec) {
this.spec = spec;
return this;
}
/**
* Get spec
*
* @return spec
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public V1StatefulSetSpec getSpec() {
return spec;
}
public void setSpec(V1StatefulSetSpec spec) {
this.spec = spec;
}
public V1StatefulSet status(V1StatefulSetStatus status) {
this.status = status;
return this;
}
/**
* Get status
*
* @return status
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public V1StatefulSetStatus getStatus() {
return status;
}
public void setStatus(V1StatefulSetStatus status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
V1StatefulSet v1StatefulSet = (V1StatefulSet) o;
return Objects.equals(this.apiVersion, v1StatefulSet.apiVersion)
&& Objects.equals(this.kind, v1StatefulSet.kind)
&& Objects.equals(this.metadata, v1StatefulSet.metadata)
&& Objects.equals(this.spec, v1StatefulSet.spec)
&& Objects.equals(this.status, v1StatefulSet.status);
}
@Override
public int hashCode() {
return Objects.hash(apiVersion, kind, metadata, spec, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class V1StatefulSet {\n");
sb.append(" apiVersion: ").append(toIndentedString(apiVersion)).append("\n");
sb.append(" kind: ").append(toIndentedString(kind)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
sb.append(" spec: ").append(toIndentedString(spec)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| |
/* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License
* at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights and
* limitations under the License.
*
* The Original Code is org/mozilla/javascript/Token.java,
* a component of the Rhino Library ( http://www.mozilla.org/rhino/ )
* This file is a modification of the Original Code developed
* for YUI Compressor.
*
* The Initial Developer of the Original Code is Mozilla Foundation
*
* Copyright (c) 2009 Mozilla Foundation. All Rights Reserved.
*
* Contributor(s): Yahoo! Inc. 2009
*
* ***** END LICENSE BLOCK ***** */
package com.yahoo.platform.yui.compressor.org.mozilla.javascript;
/**
* This class implements the JavaScript scanner.
*
* It is based on the C source files jsscan.c and jsscan.h
* in the jsref package.
*
* @see com.yahoo.platform.yui.compressor.org.mozilla.javascript.Parser
*
* @author Mike McCabe
* @author Brendan Eich
*/
public class Token
{
// debug flags
public static final boolean printTrees = false;
static final boolean printICode = false;
static final boolean printNames = printTrees || printICode;
/**
* Token types. These values correspond to JSTokenType values in
* jsscan.c.
*/
public final static int
// start enum
ERROR = -1, // well-known as the only code < EOF
EOF = 0, // end of file token - (not EOF_CHAR)
EOL = 1, // end of line
// Interpreter reuses the following as bytecodes
FIRST_BYTECODE_TOKEN = 2,
ENTERWITH = 2,
LEAVEWITH = 3,
RETURN = 4,
GOTO = 5,
IFEQ = 6,
IFNE = 7,
SETNAME = 8,
BITOR = 9,
BITXOR = 10,
BITAND = 11,
EQ = 12,
NE = 13,
LT = 14,
LE = 15,
GT = 16,
GE = 17,
LSH = 18,
RSH = 19,
URSH = 20,
ADD = 21,
SUB = 22,
MUL = 23,
DIV = 24,
MOD = 25,
NOT = 26,
BITNOT = 27,
POS = 28,
NEG = 29,
NEW = 30,
DELPROP = 31,
TYPEOF = 32,
GETPROP = 33,
GETPROPNOWARN = 34,
SETPROP = 35,
GETELEM = 36,
SETELEM = 37,
CALL = 38,
NAME = 39,
NUMBER = 40,
STRING = 41,
NULL = 42,
THIS = 43,
FALSE = 44,
TRUE = 45,
SHEQ = 46, // shallow equality (===)
SHNE = 47, // shallow inequality (!==)
REGEXP = 48,
BINDNAME = 49,
THROW = 50,
RETHROW = 51, // rethrow caught exception: catch (e if ) use it
IN = 52,
INSTANCEOF = 53,
LOCAL_LOAD = 54,
GETVAR = 55,
SETVAR = 56,
CATCH_SCOPE = 57,
ENUM_INIT_KEYS = 58,
ENUM_INIT_VALUES = 59,
ENUM_INIT_ARRAY= 60,
ENUM_NEXT = 61,
ENUM_ID = 62,
THISFN = 63,
RETURN_RESULT = 64, // to return previously stored return result
ARRAYLIT = 65, // array literal
OBJECTLIT = 66, // object literal
GET_REF = 67, // *reference
SET_REF = 68, // *reference = something
DEL_REF = 69, // delete reference
REF_CALL = 70, // f(args) = something or f(args)++
REF_SPECIAL = 71, // reference for special properties like __proto
YIELD = 72, // JS 1.7 yield pseudo keyword
// For XML support:
DEFAULTNAMESPACE = 73, // default xml namespace =
ESCXMLATTR = 74,
ESCXMLTEXT = 75,
REF_MEMBER = 76, // Reference for x.@y, x..y etc.
REF_NS_MEMBER = 77, // Reference for x.ns::y, x..ns::y etc.
REF_NAME = 78, // Reference for @y, @[y] etc.
REF_NS_NAME = 79; // Reference for ns::y, @ns::y@[y] etc.
// End of interpreter bytecodes
public final static int
LAST_BYTECODE_TOKEN = REF_NS_NAME,
TRY = 80,
SEMI = 81, // semicolon
LB = 82, // left and right brackets
RB = 83,
LC = 84, // left and right curlies (braces)
RC = 85,
LP = 86, // left and right parentheses
RP = 87,
COMMA = 88, // comma operator
ASSIGN = 89, // simple assignment (=)
ASSIGN_BITOR = 90, // |=
ASSIGN_BITXOR = 91, // ^=
ASSIGN_BITAND = 92, // |=
ASSIGN_LSH = 93, // <<=
ASSIGN_RSH = 94, // >>=
ASSIGN_URSH = 95, // >>>=
ASSIGN_ADD = 96, // +=
ASSIGN_SUB = 97, // -=
ASSIGN_MUL = 98, // *=
ASSIGN_DIV = 99, // /=
ASSIGN_MOD = 100; // %=
public final static int
FIRST_ASSIGN = ASSIGN,
LAST_ASSIGN = ASSIGN_MOD,
HOOK = 101, // conditional (?:)
COLON = 102,
OR = 103, // logical or (||)
AND = 104, // logical and (&&)
INC = 105, // increment/decrement (++ --)
DEC = 106,
DOT = 107, // member operator (.)
FUNCTION = 108, // function keyword
EXPORT = 109, // export keyword
IMPORT = 110, // import keyword
IF = 111, // if keyword
ELSE = 112, // else keyword
SWITCH = 113, // switch keyword
CASE = 114, // case keyword
DEFAULT = 115, // default keyword
WHILE = 116, // while keyword
DO = 117, // do keyword
FOR = 118, // for keyword
BREAK = 119, // break keyword
CONTINUE = 120, // continue keyword
VAR = 121, // var keyword
WITH = 122, // with keyword
CATCH = 123, // catch keyword
FINALLY = 124, // finally keyword
VOID = 125, // void keyword
RESERVED = 126, // reserved keywords
EMPTY = 127,
/* types used for the parse tree - these never get returned
* by the scanner.
*/
BLOCK = 128, // statement block
LABEL = 129, // label
TARGET = 130,
LOOP = 131,
EXPR_VOID = 132, // expression statement in functions
EXPR_RESULT = 133, // expression statement in scripts
JSR = 134,
SCRIPT = 135, // top-level node for entire script
TYPEOFNAME = 136, // for typeof(simple-name)
USE_STACK = 137,
SETPROP_OP = 138, // x.y op= something
SETELEM_OP = 139, // x[y] op= something
LOCAL_BLOCK = 140,
SET_REF_OP = 141, // *reference op= something
// For XML support:
DOTDOT = 142, // member operator (..)
COLONCOLON = 143, // namespace::name
XML = 144, // XML type
DOTQUERY = 145, // .() -- e.g., x.emps.emp.(name == "terry")
XMLATTR = 146, // @
XMLEND = 147,
// Optimizer-only-tokens
TO_OBJECT = 148,
TO_DOUBLE = 149,
GET = 150, // JS 1.5 get pseudo keyword
SET = 151, // JS 1.5 set pseudo keyword
LET = 152, // JS 1.7 let pseudo keyword
CONST = 153,
SETCONST = 154,
SETCONSTVAR = 155,
ARRAYCOMP = 156, // array comprehension
LETEXPR = 157,
WITHEXPR = 158,
DEBUGGER = 159,
CONDCOMMENT = 160, // JScript conditional comment
KEEPCOMMENT = 161, // /*! ... */ comment
LAST_TOKEN = 162;
public static String name(int token)
{
if (!printNames) {
return String.valueOf(token);
}
switch (token) {
case ERROR: return "ERROR";
case EOF: return "EOF";
case EOL: return "EOL";
case ENTERWITH: return "ENTERWITH";
case LEAVEWITH: return "LEAVEWITH";
case RETURN: return "RETURN";
case GOTO: return "GOTO";
case IFEQ: return "IFEQ";
case IFNE: return "IFNE";
case SETNAME: return "SETNAME";
case BITOR: return "BITOR";
case BITXOR: return "BITXOR";
case BITAND: return "BITAND";
case EQ: return "EQ";
case NE: return "NE";
case LT: return "LT";
case LE: return "LE";
case GT: return "GT";
case GE: return "GE";
case LSH: return "LSH";
case RSH: return "RSH";
case URSH: return "URSH";
case ADD: return "ADD";
case SUB: return "SUB";
case MUL: return "MUL";
case DIV: return "DIV";
case MOD: return "MOD";
case NOT: return "NOT";
case BITNOT: return "BITNOT";
case POS: return "POS";
case NEG: return "NEG";
case NEW: return "NEW";
case DELPROP: return "DELPROP";
case TYPEOF: return "TYPEOF";
case GETPROP: return "GETPROP";
case GETPROPNOWARN: return "GETPROPNOWARN";
case SETPROP: return "SETPROP";
case GETELEM: return "GETELEM";
case SETELEM: return "SETELEM";
case CALL: return "CALL";
case NAME: return "NAME";
case NUMBER: return "NUMBER";
case STRING: return "STRING";
case NULL: return "NULL";
case THIS: return "THIS";
case FALSE: return "FALSE";
case TRUE: return "TRUE";
case SHEQ: return "SHEQ";
case SHNE: return "SHNE";
case REGEXP: return "OBJECT";
case BINDNAME: return "BINDNAME";
case THROW: return "THROW";
case RETHROW: return "RETHROW";
case IN: return "IN";
case INSTANCEOF: return "INSTANCEOF";
case LOCAL_LOAD: return "LOCAL_LOAD";
case GETVAR: return "GETVAR";
case SETVAR: return "SETVAR";
case CATCH_SCOPE: return "CATCH_SCOPE";
case ENUM_INIT_KEYS: return "ENUM_INIT_KEYS";
case ENUM_INIT_VALUES:return "ENUM_INIT_VALUES";
case ENUM_INIT_ARRAY: return "ENUM_INIT_ARRAY";
case ENUM_NEXT: return "ENUM_NEXT";
case ENUM_ID: return "ENUM_ID";
case THISFN: return "THISFN";
case RETURN_RESULT: return "RETURN_RESULT";
case ARRAYLIT: return "ARRAYLIT";
case OBJECTLIT: return "OBJECTLIT";
case GET_REF: return "GET_REF";
case SET_REF: return "SET_REF";
case DEL_REF: return "DEL_REF";
case REF_CALL: return "REF_CALL";
case REF_SPECIAL: return "REF_SPECIAL";
case DEFAULTNAMESPACE:return "DEFAULTNAMESPACE";
case ESCXMLTEXT: return "ESCXMLTEXT";
case ESCXMLATTR: return "ESCXMLATTR";
case REF_MEMBER: return "REF_MEMBER";
case REF_NS_MEMBER: return "REF_NS_MEMBER";
case REF_NAME: return "REF_NAME";
case REF_NS_NAME: return "REF_NS_NAME";
case TRY: return "TRY";
case SEMI: return "SEMI";
case LB: return "LB";
case RB: return "RB";
case LC: return "LC";
case RC: return "RC";
case LP: return "LP";
case RP: return "RP";
case COMMA: return "COMMA";
case ASSIGN: return "ASSIGN";
case ASSIGN_BITOR: return "ASSIGN_BITOR";
case ASSIGN_BITXOR: return "ASSIGN_BITXOR";
case ASSIGN_BITAND: return "ASSIGN_BITAND";
case ASSIGN_LSH: return "ASSIGN_LSH";
case ASSIGN_RSH: return "ASSIGN_RSH";
case ASSIGN_URSH: return "ASSIGN_URSH";
case ASSIGN_ADD: return "ASSIGN_ADD";
case ASSIGN_SUB: return "ASSIGN_SUB";
case ASSIGN_MUL: return "ASSIGN_MUL";
case ASSIGN_DIV: return "ASSIGN_DIV";
case ASSIGN_MOD: return "ASSIGN_MOD";
case HOOK: return "HOOK";
case COLON: return "COLON";
case OR: return "OR";
case AND: return "AND";
case INC: return "INC";
case DEC: return "DEC";
case DOT: return "DOT";
case FUNCTION: return "FUNCTION";
case EXPORT: return "EXPORT";
case IMPORT: return "IMPORT";
case IF: return "IF";
case ELSE: return "ELSE";
case SWITCH: return "SWITCH";
case CASE: return "CASE";
case DEFAULT: return "DEFAULT";
case WHILE: return "WHILE";
case DO: return "DO";
case FOR: return "FOR";
case BREAK: return "BREAK";
case CONTINUE: return "CONTINUE";
case VAR: return "VAR";
case WITH: return "WITH";
case CATCH: return "CATCH";
case FINALLY: return "FINALLY";
case VOID: return "VOID";
case RESERVED: return "RESERVED";
case EMPTY: return "EMPTY";
case BLOCK: return "BLOCK";
case LABEL: return "LABEL";
case TARGET: return "TARGET";
case LOOP: return "LOOP";
case EXPR_VOID: return "EXPR_VOID";
case EXPR_RESULT: return "EXPR_RESULT";
case JSR: return "JSR";
case SCRIPT: return "SCRIPT";
case TYPEOFNAME: return "TYPEOFNAME";
case USE_STACK: return "USE_STACK";
case SETPROP_OP: return "SETPROP_OP";
case SETELEM_OP: return "SETELEM_OP";
case LOCAL_BLOCK: return "LOCAL_BLOCK";
case SET_REF_OP: return "SET_REF_OP";
case DOTDOT: return "DOTDOT";
case COLONCOLON: return "COLONCOLON";
case XML: return "XML";
case DOTQUERY: return "DOTQUERY";
case XMLATTR: return "XMLATTR";
case XMLEND: return "XMLEND";
case TO_OBJECT: return "TO_OBJECT";
case TO_DOUBLE: return "TO_DOUBLE";
case GET: return "GET";
case SET: return "SET";
case LET: return "LET";
case YIELD: return "YIELD";
case CONST: return "CONST";
case SETCONST: return "SETCONST";
case ARRAYCOMP: return "ARRAYCOMP";
case WITHEXPR: return "WITHEXPR";
case LETEXPR: return "LETEXPR";
case DEBUGGER: return "DEBUGGER";
}
// Token without name
throw new IllegalStateException(String.valueOf(token));
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.connections.infinispan;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.eviction.EvictionType;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.lookup.DummyTransactionManagerLookup;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import javax.naming.InitialContext;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class DefaultInfinispanConnectionProviderFactory implements InfinispanConnectionProviderFactory {
protected static final Logger logger = Logger.getLogger(DefaultInfinispanConnectionProviderFactory.class);
protected Config.Scope config;
protected EmbeddedCacheManager cacheManager;
protected boolean containerManaged;
@Override
public InfinispanConnectionProvider create(KeycloakSession session) {
lazyInit();
return new DefaultInfinispanConnectionProvider(cacheManager);
}
@Override
public void close() {
if (cacheManager != null && !containerManaged) {
cacheManager.stop();
}
cacheManager = null;
}
@Override
public String getId() {
return "default";
}
@Override
public void init(Config.Scope config) {
this.config = config;
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
protected void lazyInit() {
if (cacheManager == null) {
synchronized (this) {
if (cacheManager == null) {
String cacheContainer = config.get("cacheContainer");
if (cacheContainer != null) {
initContainerManaged(cacheContainer);
} else {
initEmbedded();
}
}
}
}
}
protected void initContainerManaged(String cacheContainerLookup) {
try {
cacheManager = (EmbeddedCacheManager) new InitialContext().lookup(cacheContainerLookup);
containerManaged = true;
cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME, getRevisionCacheConfig(true, InfinispanConnectionProvider.REALM_REVISIONS_CACHE_DEFAULT_MAX));
cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME, true);
long maxEntries = cacheManager.getCache(InfinispanConnectionProvider.USER_CACHE_NAME).getCacheConfiguration().eviction().maxEntries();
if (maxEntries <= 0) {
maxEntries = InfinispanConnectionProvider.USER_REVISIONS_CACHE_DEFAULT_MAX;
}
cacheManager.defineConfiguration(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, getRevisionCacheConfig(true, maxEntries));
cacheManager.getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, true);
cacheManager.getCache(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME, true);
logger.debugv("Using container managed Infinispan cache container, lookup={1}", cacheContainerLookup);
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve cache container", e);
}
}
protected void initEmbedded() {
GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder();
boolean clustered = config.getBoolean("clustered", false);
boolean async = config.getBoolean("async", true);
boolean allowDuplicateJMXDomains = config.getBoolean("allowDuplicateJMXDomains", true);
if (clustered) {
gcb.transport().defaultTransport();
}
gcb.globalJmxStatistics().allowDuplicateDomains(allowDuplicateJMXDomains);
cacheManager = new DefaultCacheManager(gcb.build());
containerManaged = false;
logger.debug("Started embedded Infinispan cache container");
ConfigurationBuilder invalidationConfigBuilder = new ConfigurationBuilder();
if (clustered) {
invalidationConfigBuilder.clustering().cacheMode(async ? CacheMode.INVALIDATION_ASYNC : CacheMode.INVALIDATION_SYNC);
}
Configuration invalidationCacheConfiguration = invalidationConfigBuilder.build();
cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_CACHE_NAME, invalidationCacheConfiguration);
cacheManager.defineConfiguration(InfinispanConnectionProvider.USER_CACHE_NAME, invalidationCacheConfiguration);
ConfigurationBuilder sessionConfigBuilder = new ConfigurationBuilder();
if (clustered) {
String sessionsMode = config.get("sessionsMode", "distributed");
if (sessionsMode.equalsIgnoreCase("replicated")) {
sessionConfigBuilder.clustering().cacheMode(async ? CacheMode.REPL_ASYNC : CacheMode.REPL_SYNC);
} else if (sessionsMode.equalsIgnoreCase("distributed")) {
sessionConfigBuilder.clustering().cacheMode(async ? CacheMode.DIST_ASYNC : CacheMode.DIST_SYNC);
} else {
throw new RuntimeException("Invalid value for sessionsMode");
}
sessionConfigBuilder.clustering().hash()
.numOwners(config.getInt("sessionsOwners", 2))
.numSegments(config.getInt("sessionsSegments", 60)).build();
}
Configuration sessionCacheConfiguration = sessionConfigBuilder.build();
cacheManager.defineConfiguration(InfinispanConnectionProvider.SESSION_CACHE_NAME, sessionCacheConfiguration);
cacheManager.defineConfiguration(InfinispanConnectionProvider.OFFLINE_SESSION_CACHE_NAME, sessionCacheConfiguration);
cacheManager.defineConfiguration(InfinispanConnectionProvider.LOGIN_FAILURE_CACHE_NAME, sessionCacheConfiguration);
cacheManager.defineConfiguration(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME, sessionCacheConfiguration);
ConfigurationBuilder replicationConfigBuilder = new ConfigurationBuilder();
if (clustered) {
replicationConfigBuilder.clustering().cacheMode(async ? CacheMode.REPL_ASYNC : CacheMode.REPL_SYNC);
}
Configuration replicationCacheConfiguration = replicationConfigBuilder.build();
cacheManager.defineConfiguration(InfinispanConnectionProvider.WORK_CACHE_NAME, replicationCacheConfiguration);
ConfigurationBuilder counterConfigBuilder = new ConfigurationBuilder();
counterConfigBuilder.invocationBatching().enable()
.transaction().transactionMode(TransactionMode.TRANSACTIONAL);
counterConfigBuilder.transaction().transactionManagerLookup(new DummyTransactionManagerLookup());
counterConfigBuilder.transaction().lockingMode(LockingMode.PESSIMISTIC);
cacheManager.defineConfiguration(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME, getRevisionCacheConfig(false, InfinispanConnectionProvider.REALM_REVISIONS_CACHE_DEFAULT_MAX));
cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME, true);
long maxEntries = cacheManager.getCache(InfinispanConnectionProvider.USER_CACHE_NAME).getCacheConfiguration().eviction().maxEntries();
if (maxEntries <= 0) {
maxEntries = InfinispanConnectionProvider.USER_REVISIONS_CACHE_DEFAULT_MAX;
}
cacheManager.defineConfiguration(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, getRevisionCacheConfig(false, maxEntries));
cacheManager.getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME, true);
}
private Configuration getRevisionCacheConfig(boolean managed, long maxEntries) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.invocationBatching().enable().transaction().transactionMode(TransactionMode.TRANSACTIONAL);
// Workaround: Use Dummy manager even in managed ( wildfly/eap ) environment. Without this workaround, there is an issue in EAP7 overlay.
// After start+end revisions batch is left the JTA transaction in committed state. This is incorrect and causes other issues afterwards.
// TODO: Investigate
// if (!managed)
cb.transaction().transactionManagerLookup(new DummyTransactionManagerLookup());
cb.transaction().lockingMode(LockingMode.PESSIMISTIC);
cb.eviction().strategy(EvictionStrategy.LRU).type(EvictionType.COUNT).size(maxEntries);
return cb.build();
}
}
| |
package com.slickqa.executioner.cmdlineagent;
import com.google.inject.Inject;
import com.slickqa.executioner.base.Addresses;
import com.slickqa.executioner.base.AutoloadComponent;
import com.slickqa.executioner.base.OnStartup;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.Message;
import io.vertx.core.file.FileSystem;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* The actual agent
*/
@AutoloadComponent
public class CommandLineAgent implements OnStartup {
protected EventBus eventBus;
protected CommandLineAgentConfiguration config;
protected Vertx vertx;
protected FileSystem fs;
protected JsonObject agent;
protected String imageAddress;
protected boolean requestedWork;
protected boolean timeToStop;
protected boolean readingFile;
protected Logger log;
protected JsonObject currentWork;
protected Long imageLastModified;
protected int workQueueSize;
@Inject
public CommandLineAgent(EventBus eventBus, CommandLineAgentConfiguration config, Vertx vertx, FileSystem fs) {
this.eventBus = eventBus;
this.config = config;
this.vertx = vertx;
this.fs = fs;
this.imageAddress = Addresses.AgentImageBaseAddress + config.getAgentName();
this.agent = new JsonObject()
.put("name", config.getAgentName())
.put("provides", config.getProvides())
.put("information", config.getAgentInformation())
.put("deploymentId", vertx.getOrCreateContext().deploymentID())
.put("imageAddress", imageAddress)
.put("paused", false);
this.requestedWork = false;
this.timeToStop = false;
this.log = LoggerFactory.getLogger(this.getClass().getName() + "." + config.getAgentName());
this.currentWork = null;
this.imageLastModified = null;
this.readingFile = false;
this.workQueueSize = 0;
}
@Override
public void onStartup() {
eventBus.consumer(Addresses.AgentQuery)
.handler(message -> broadcastInfo());
eventBus.consumer(Addresses.AgentBaseAddress + config.getAgentName())
.handler(message -> message.reply(agentUpdateObject()));
eventBus.consumer(Addresses.WorkQueueInfo, (Message<JsonArray> workQueueMessage) -> this.workQueueSize = workQueueMessage.body().size());
eventBus.consumer(Addresses.AgentStopBaseAddress + config.getAgentName()).handler(message -> {
timeToStop = true;
message.reply(agentUpdateObject());
if(currentWork == null)
askForWork();
});
eventBus.consumer(Addresses.AgentPauseBaseAddress + config.getAgentName()).handler(message -> {
agent.put("paused", true);
message.reply(agentUpdateObject());
broadcastInfo();
});
eventBus.consumer(Addresses.AgentResumeBaseAddress + config.getAgentName()).handler(message -> {
agent.put("paused", false);
message.reply(agentUpdateObject());
broadcastInfo();
});
// try to avoid every agent polling at the exact same time
vertx.setPeriodic(ThreadLocalRandom.current().nextInt(600, 800), this::checkForImageUpdate);
// ask for work every 3-4 seconds if there is work in the work queue
vertx.setPeriodic(new Random(new Date().getTime()).nextInt((4000 - 3000) + 1) + 3000, id -> {
if(workQueueSize > 0) {
askForWork();
}
});
broadcastInfo();
}
public void checkForImageUpdate(Long id) {
if(currentWork != null && !readingFile) {
fs.exists(config.getImageWatchPath(), existsResult -> {
if(existsResult.succeeded() && existsResult.result()) {
fs.props(config.getImageWatchPath(), propsResult -> {
if(propsResult.succeeded()) {
if(imageLastModified == null || propsResult.result().lastModifiedTime() > imageLastModified) {
imageLastModified = propsResult.result().lastModifiedTime();
readingFile = true;
fs.readFile(config.getImageWatchPath(), fileReadResult -> {
if(fileReadResult.succeeded()) {
eventBus.send(imageAddress, fileReadResult.result());
} else {
log.warn("Unable to read file " + config.getImageWatchPath() + ": ", fileReadResult.cause());
}
readingFile = false;
});
}
} else {
log.warn("Something weird happened when trying to read file properties of " + config.getImageWatchPath() + ": ", propsResult.cause());
}
});
}
});
}
}
protected JsonObject agentUpdateObject() {
JsonObject current = agent.copy()
.put("agentUndeployRequested", timeToStop)
.put("requestedWork", requestedWork)
.put("readingFile", readingFile);
if(currentWork != null) {
current = current.put("assignment", currentWork);
}
return current;
}
public void broadcastInfo() {
log.info("Sending update for agent {0}", config.getAgentName());
this.eventBus.publish(Addresses.AgentUpdate, agentUpdateObject());
}
public void askForWork() {
// don't ask for work if we already have some
if(currentWork == null && !requestedWork) {
if(timeToStop) {
log.info("Agent {0} requested to stop!", config.getAgentName());
eventBus.publish(Addresses.AgentDeleteAnnounce, agentUpdateObject());
requestedWork = true; // this will keep us from ever requesting work again and ensure we only send stop once
broadcastInfo();
} else if(!agent.getBoolean("paused")) {
log.info("Asking for work for agent {0}", config.getAgentName());
// avoid requesting work more than once before we get the first response
requestedWork = true;
broadcastInfo();
eventBus.send(Addresses.WorkQueueRequestWork, agent, response -> {
if (response.succeeded() && response.result().body() instanceof JsonObject) {
log.info("Recieved work for agent {0} from WorkQueue: {1}", config.getAgentName(), Json.encodePrettily(response.result().body()));
currentWork = (JsonObject) response.result().body();
requestedWork = false;
startWork();
broadcastInfo();
} else {
requestedWork = false;
log.info("No work for {0} because: {1}", config.getAgentName(), response.cause().getMessage());
broadcastInfo();
}
});
}
}
}
public void startWork() {
vertx.executeBlocking(future -> {
log.info("Starting work for agent {0}.", config.getAgentName());
broadcastInfo(); // do broadcast as we want to update everyone we are running a testa
Path tempFile = null;
try {
tempFile = Files.createTempFile(config.getAgentName(), ".json");
Files.write(tempFile, currentWork.encodePrettily().getBytes());
ProcessBuilder pb = new ProcessBuilder(config.getCommand(), tempFile.toString());
log.info("Running command: {0} {1}", config.getCommand(), tempFile.toString());
Process p = pb.start();
int retcode = p.waitFor();
log.info("Commmand {0} {1} completed with return code {2}", config.getCommand(), tempFile.toString(), retcode);
} catch (IOException e) {
log.error("Problem occurred when trying to do work: ", e);
} catch (InterruptedException e) {
log.error("Problem occurred when waiting for process: ", e);
} finally {
if(tempFile != null) {
try {
Files.delete(tempFile);
} catch (IOException e) {
log.error("Unable to delete temp file " + tempFile + ": ", e);
}
}
}
future.complete();
}, false, whenDone -> {
log.info("Work done, requesting more work for {0}.", config.getAgentName());
currentWork = null;
broadcastInfo();
askForWork();
});
}
}
| |
package com.gdn.venice.persistence;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.math.BigDecimal;
/**
* The persistent class for the ven_order_history database table.
*
*/
@Entity
@Table(name="ven_order_history")
public class VenOrderHistory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="ven_order_history")
@TableGenerator(name="ven_order_history", table="openjpaseq", pkColumnName="id", valueColumnName="sequence_value", allocationSize=1) //flush every 1 insert
@Column(name="order_history_id", unique=true, nullable=false)
private Long orderHistoryId;
@Column(nullable=false, precision=20, scale=2)
private BigDecimal amount;
@Column(name="billing_address_id", nullable=false)
private Long billingAddressId;
@Column(name="billing_amount", nullable=false, precision=20, scale=2)
private BigDecimal billingAmount;
@Column(name="billing_method_id", nullable=false)
private Long billingMethodId;
@Column(name="blocked_flag", nullable=false)
private Boolean blockedFlag;
@Column(name="blocked_timestamp", nullable=false)
private Timestamp blockedTimestamp;
@Column(name="blocking_source_id", nullable=false)
private Long blockingSourceId;
@Column(name="customer_id", nullable=false)
private Long customerId;
@Column(name="delivered_date_time", nullable=false)
private Timestamp deliveredDateTime;
@Column(name="finance_reconcile_flag", nullable=false)
private Boolean financeReconcileFlag;
@Column(name="fraud_check_status_id", nullable=false)
private Long fraudCheckStatusId;
@Column(name="history_timestamp", nullable=false)
private Timestamp historyTimestamp;
@Column(name="ip_address", nullable=false, length=100)
private String ipAddress;
@Column(name="order_date_time", nullable=false)
private Timestamp orderDateTime;
@Column(name="order_id", nullable=false)
private Long orderId;
@Column(name="order_status_id", nullable=false)
private Long orderStatusId;
@Column(name="partial_fulfillment_flag", nullable=false)
private Boolean partialFulfillmentFlag;
@Column(name="wcs_billing_id", nullable=false, length=100)
private String wcsBillingId;
@Column(name="wcs_order_id", nullable=false, length=100)
private String wcsOrderId;
@Column(name="wcs_rma_id", length=100)
private String wcsRmaId;
@Column(name="wcs_rma_timestamp")
private Timestamp wcsRmaTimestamp;
//bi-directional many-to-one association to VenMasterChangeType
@ManyToOne
@JoinColumn(name="master_change_id", nullable=false)
private VenMasterChangeType venMasterChangeType;
public VenOrderHistory() {
}
public Long getOrderHistoryId() {
return this.orderHistoryId;
}
public void setOrderHistoryId(Long orderHistoryId) {
this.orderHistoryId = orderHistoryId;
}
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Long getBillingAddressId() {
return this.billingAddressId;
}
public void setBillingAddressId(Long billingAddressId) {
this.billingAddressId = billingAddressId;
}
public BigDecimal getBillingAmount() {
return this.billingAmount;
}
public void setBillingAmount(BigDecimal billingAmount) {
this.billingAmount = billingAmount;
}
public Long getBillingMethodId() {
return this.billingMethodId;
}
public void setBillingMethodId(Long billingMethodId) {
this.billingMethodId = billingMethodId;
}
public Boolean getBlockedFlag() {
return this.blockedFlag;
}
public void setBlockedFlag(Boolean blockedFlag) {
this.blockedFlag = blockedFlag;
}
public Timestamp getBlockedTimestamp() {
return this.blockedTimestamp;
}
public void setBlockedTimestamp(Timestamp blockedTimestamp) {
this.blockedTimestamp = blockedTimestamp;
}
public Long getBlockingSourceId() {
return this.blockingSourceId;
}
public void setBlockingSourceId(Long blockingSourceId) {
this.blockingSourceId = blockingSourceId;
}
public Long getCustomerId() {
return this.customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public Timestamp getDeliveredDateTime() {
return this.deliveredDateTime;
}
public void setDeliveredDateTime(Timestamp deliveredDateTime) {
this.deliveredDateTime = deliveredDateTime;
}
public Boolean getFinanceReconcileFlag() {
return this.financeReconcileFlag;
}
public void setFinanceReconcileFlag(Boolean financeReconcileFlag) {
this.financeReconcileFlag = financeReconcileFlag;
}
public Long getFraudCheckStatusId() {
return this.fraudCheckStatusId;
}
public void setFraudCheckStatusId(Long fraudCheckStatusId) {
this.fraudCheckStatusId = fraudCheckStatusId;
}
public Timestamp getHistoryTimestamp() {
return this.historyTimestamp;
}
public void setHistoryTimestamp(Timestamp historyTimestamp) {
this.historyTimestamp = historyTimestamp;
}
public String getIpAddress() {
return this.ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public Timestamp getOrderDateTime() {
return this.orderDateTime;
}
public void setOrderDateTime(Timestamp orderDateTime) {
this.orderDateTime = orderDateTime;
}
public Long getOrderId() {
return this.orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Long getOrderStatusId() {
return this.orderStatusId;
}
public void setOrderStatusId(Long orderStatusId) {
this.orderStatusId = orderStatusId;
}
public Boolean getPartialFulfillmentFlag() {
return this.partialFulfillmentFlag;
}
public void setPartialFulfillmentFlag(Boolean partialFulfillmentFlag) {
this.partialFulfillmentFlag = partialFulfillmentFlag;
}
public String getWcsBillingId() {
return this.wcsBillingId;
}
public void setWcsBillingId(String wcsBillingId) {
this.wcsBillingId = wcsBillingId;
}
public String getWcsOrderId() {
return this.wcsOrderId;
}
public void setWcsOrderId(String wcsOrderId) {
this.wcsOrderId = wcsOrderId;
}
public String getWcsRmaId() {
return this.wcsRmaId;
}
public void setWcsRmaId(String wcsRmaId) {
this.wcsRmaId = wcsRmaId;
}
public Timestamp getWcsRmaTimestamp() {
return this.wcsRmaTimestamp;
}
public void setWcsRmaTimestamp(Timestamp wcsRmaTimestamp) {
this.wcsRmaTimestamp = wcsRmaTimestamp;
}
public VenMasterChangeType getVenMasterChangeType() {
return this.venMasterChangeType;
}
public void setVenMasterChangeType(VenMasterChangeType venMasterChangeType) {
this.venMasterChangeType = venMasterChangeType;
}
}
| |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.uimanager;
import javax.annotation.Nullable;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.touch.ReactHitSlopView;
/**
* Class responsible for identifying which react view should handle a given {@link MotionEvent}.
* It uses the event coordinates to traverse the view hierarchy and return a suitable view.
*/
public class TouchTargetHelper {
private static final float[] mEventCoords = new float[2];
private static final PointF mTempPoint = new PointF();
private static final float[] mMatrixTransformCoords = new float[2];
private static final Matrix mInverseMatrix = new Matrix();
/**
* Find touch event target view within the provided container given the coordinates provided
* via {@link MotionEvent}.
*
* @param eventX the X screen coordinate of the touch location
* @param eventY the Y screen coordinate of the touch location
* @param viewGroup the container view to traverse
* @return the react tag ID of the child view that should handle the event
*/
public static int findTargetTagForTouch(
float eventX,
float eventY,
ViewGroup viewGroup) {
return findTargetTagAndCoordinatesForTouch(
eventX, eventY, viewGroup, mEventCoords, null);
}
/**
* Find touch event target view within the provided container given the coordinates provided
* via {@link MotionEvent}.
*
* @param eventX the X screen coordinate of the touch location
* @param eventY the Y screen coordinate of the touch location
* @param viewGroup the container view to traverse
* @param nativeViewId the native react view containing this touch target
* @return the react tag ID of the child view that should handle the event
*/
public static int findTargetTagForTouch(
float eventX,
float eventY,
ViewGroup viewGroup,
@Nullable int[] nativeViewId) {
return findTargetTagAndCoordinatesForTouch(
eventX, eventY, viewGroup, mEventCoords, nativeViewId);
}
/**
* Find touch event target view within the provided container given the coordinates provided
* via {@link MotionEvent}.
*
* @param eventX the X screen coordinate of the touch location
* @param eventY the Y screen coordinate of the touch location
* @param viewGroup the container view to traverse
* @param viewCoords an out parameter that will return the X,Y value in the target view
* @param nativeViewTag an out parameter that will return the native view id
* @return the react tag ID of the child view that should handle the event
*/
public static int findTargetTagAndCoordinatesForTouch(
float eventX,
float eventY,
ViewGroup viewGroup,
float[] viewCoords,
@Nullable int[] nativeViewTag) {
UiThreadUtil.assertOnUiThread();
int targetTag = viewGroup.getId();
// Store eventCoords in array so that they are modified to be relative to the targetView found.
viewCoords[0] = eventX;
viewCoords[1] = eventY;
View nativeTargetView = findTouchTargetView(viewCoords, viewGroup);
if (nativeTargetView != null) {
View reactTargetView = findClosestReactAncestor(nativeTargetView);
if (reactTargetView != null) {
if (nativeViewTag != null) {
nativeViewTag[0] = reactTargetView.getId();
}
targetTag = getTouchTargetForView(reactTargetView, viewCoords[0], viewCoords[1]);
}
}
return targetTag;
}
private static View findClosestReactAncestor(View view) {
while (view != null && view.getId() <= 0) {
view = (View) view.getParent();
}
return view;
}
/**
* Returns the touch target View that is either viewGroup or one if its descendants.
* This is a recursive DFS since view the entire tree must be parsed until the target is found.
* If the search does not backtrack, it is possible to follow a branch that cannot be a target
* (because of pointerEvents). For example, if both C and E can be the target of an event:
* A (pointerEvents: auto) - B (pointerEvents: box-none) - C (pointerEvents: none)
* \ D (pointerEvents: auto) - E (pointerEvents: auto)
* If the search goes down the first branch, it would return A as the target, which is incorrect.
* NB: This modifies the eventCoords to always be relative to the current viewGroup. When the
* method returns, it will contain the eventCoords relative to the targetView found.
*/
private static View findTouchTargetView(float[] eventCoords, ViewGroup viewGroup) {
int childrenCount = viewGroup.getChildCount();
// Consider z-index when determining the touch target.
ReactZIndexedViewGroup zIndexedViewGroup = viewGroup instanceof ReactZIndexedViewGroup ?
(ReactZIndexedViewGroup) viewGroup :
null;
for (int i = childrenCount - 1; i >= 0; i--) {
int childIndex = zIndexedViewGroup != null ? zIndexedViewGroup.getZIndexMappedChildIndex(i) : i;
View child = viewGroup.getChildAt(childIndex);
PointF childPoint = mTempPoint;
if (isTransformedTouchPointInView(eventCoords[0], eventCoords[1], viewGroup, child, childPoint)) {
// If it is contained within the child View, the childPoint value will contain the view
// coordinates relative to the child
// We need to store the existing X,Y for the viewGroup away as it is possible this child
// will not actually be the target and so we restore them if not
float restoreX = eventCoords[0];
float restoreY = eventCoords[1];
eventCoords[0] = childPoint.x;
eventCoords[1] = childPoint.y;
View targetView = findTouchTargetViewWithPointerEvents(eventCoords, child);
if (targetView != null) {
return targetView;
}
eventCoords[0] = restoreX;
eventCoords[1] = restoreY;
}
}
return viewGroup;
}
/**
* Returns whether the touch point is within the child View
* It is transform aware and will invert the transform Matrix to find the true local points
* This code is taken from {@link ViewGroup#isTransformedTouchPointInView()}
*/
private static boolean isTransformedTouchPointInView(
float x,
float y,
ViewGroup parent,
View child,
PointF outLocalPoint) {
float localX = x + parent.getScrollX() - child.getLeft();
float localY = y + parent.getScrollY() - child.getTop();
Matrix matrix = child.getMatrix();
if (!matrix.isIdentity()) {
float[] localXY = mMatrixTransformCoords;
localXY[0] = localX;
localXY[1] = localY;
Matrix inverseMatrix = mInverseMatrix;
matrix.invert(inverseMatrix);
inverseMatrix.mapPoints(localXY);
localX = localXY[0];
localY = localXY[1];
}
if (child instanceof ReactHitSlopView && ((ReactHitSlopView) child).getHitSlopRect() != null) {
Rect hitSlopRect = ((ReactHitSlopView) child).getHitSlopRect();
if ((localX >= -hitSlopRect.left && localX < (child.getRight() - child.getLeft()) + hitSlopRect.right)
&& (localY >= -hitSlopRect.top && localY < (child.getBottom() - child.getTop()) + hitSlopRect.bottom)) {
outLocalPoint.set(localX, localY);
return true;
}
return false;
} else {
if ((localX >= 0 && localX < (child.getRight() - child.getLeft()))
&& (localY >= 0 && localY < (child.getBottom() - child.getTop()))) {
outLocalPoint.set(localX, localY);
return true;
}
return false;
}
}
/**
* Returns the touch target View of the event given, or null if neither the given View nor any of
* its descendants are the touch target.
*/
private static @Nullable View findTouchTargetViewWithPointerEvents(
float eventCoords[], View view) {
PointerEvents pointerEvents = view instanceof ReactPointerEventsView ?
((ReactPointerEventsView) view).getPointerEvents() : PointerEvents.AUTO;
// Views that are disabled should never be the target of pointer events. However, their children
// can be because some views (SwipeRefreshLayout) use enabled but still have children that can
// be valid targets.
if (!view.isEnabled()) {
if (pointerEvents == PointerEvents.AUTO) {
pointerEvents = PointerEvents.BOX_NONE;
} else if (pointerEvents == PointerEvents.BOX_ONLY) {
pointerEvents = PointerEvents.NONE;
}
}
if (pointerEvents == PointerEvents.NONE) {
// This view and its children can't be the target
return null;
} else if (pointerEvents == PointerEvents.BOX_ONLY) {
// This view is the target, its children don't matter
return view;
} else if (pointerEvents == PointerEvents.BOX_NONE) {
// This view can't be the target, but its children might.
if (view instanceof ViewGroup) {
View targetView = findTouchTargetView(eventCoords, (ViewGroup) view);
if (targetView != view) {
return targetView;
}
// PointerEvents.BOX_NONE means that this react element cannot receive pointer events.
// However, there might be virtual children that can receive pointer events, in which case
// we still want to return this View and dispatch a pointer event to the virtual element.
// Note that this currently only applies to Nodes/FlatViewGroup as it's the only class that
// is both a ViewGroup and ReactCompoundView (ReactTextView is a ReactCompoundView but not a
// ViewGroup).
if (view instanceof ReactCompoundView) {
int reactTag = ((ReactCompoundView)view).reactTagForTouch(eventCoords[0], eventCoords[1]);
if (reactTag != view.getId()) {
// make sure we exclude the View itself because of the PointerEvents.BOX_NONE
return view;
}
}
}
return null;
} else if (pointerEvents == PointerEvents.AUTO) {
// Either this view or one of its children is the target
if (view instanceof ReactCompoundViewGroup) {
if (((ReactCompoundViewGroup) view).interceptsTouchEvent(eventCoords[0], eventCoords[1])) {
return view;
}
}
if (view instanceof ViewGroup) {
return findTouchTargetView(eventCoords, (ViewGroup) view);
}
return view;
} else {
throw new JSApplicationIllegalArgumentException(
"Unknown pointer event type: " + pointerEvents.toString());
}
}
private static int getTouchTargetForView(View targetView, float eventX, float eventY) {
if (targetView instanceof ReactCompoundView) {
// Use coordinates relative to the view, which have been already computed by
// {@link #findTouchTargetView()}.
return ((ReactCompoundView) targetView).reactTagForTouch(eventX, eventY);
}
return targetView.getId();
}
}
| |
package com.jk.db.datasource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.internal.SessionImpl;
import com.jk.db.dataaccess.core.JKDbConstants;
import com.jk.util.JK;
import com.jk.util.JKConversionUtil;
import com.jk.util.annotations.AnnotationDetector;
import com.jk.util.config.JKConfig;
import com.jk.util.exceptions.JKDataAccessException;
import com.jk.util.logging.JKLogger;
import com.jk.util.logging.JKLoggerFactory;
public class HibernateDataSource implements JKDataSource {
JKLogger logger = JKLoggerFactory.getLogger(getClass());
SessionFactory sessionFactory;
EntityManagerFactory emf;
private Configuration config;
private JKConfig jkConfig;
/////////////////////////////////////////////////////////////////////////////
public HibernateDataSource(JKConfig jkConfig) {
this.jkConfig = jkConfig;
init();
}
/////////////////////////////////////////////////////////////////////////////
protected void init() {
logger.info("Hibernate: start configurations");
config = new Configuration();
config.setProperty("hibernate.hbm2ddl.auto", "update");
config.setProperty("hibernate.c3p0.preferredTestQuery", "select 1");
config.setProperty("hibernate.c3p0.testConnectionOnCheckout", "true");
config.setProperty("hibernate.c3p0.max_size", "4");
config.setProperty("hibernate.c3p0.min_size", "1");
config.setProperty("hibernate.c3p0.idle_test_period", "10");
config.setProperty("connection.autoReconnect","true");
config.setProperty("connection.autoReconnectForPools","true");
config.setProperty("connection.is-connection-validation-required","true");
config.setProperty("hibernate.connection.autocommit","true");
//we should put them first to insure
Properties properties = jkConfig.toProperties();
Set<Object> keySet = properties.keySet();
{ // load config from my proetries file
for (Object keyObject : keySet) {
String key = keyObject.toString();
if (key.startsWith("hibernate.")) {
String value = properties.getProperty(key);
logger.debug("Hibernate: Set ({}) property with value ({})", key, value);
config.setProperty(key, value);
}
}
}
{
// configure entities
String entitiesPackages = jkConfig.getProperty(JKDbConstants.PROPERTY_DB_ENTITY_PACKAGES, "com.app");
List<String> entityClassNames = AnnotationDetector.scanAsList(Entity.class, entitiesPackages.split(","));
for (String entityClassName : entityClassNames) {
logger.debug("Adding entity class ({}) to Hibernate", entityClassName);
config.addAnnotatedClass(JK.getClass(entityClassName));
}
}
{
if (logger.isDebugEnabled()) {
config.setProperty("hibernate.show_sql", "true");
config.setProperty("hibernate.format_sql", "true");
config.setProperty("hibernate.use_sql_comments", "true");
}
}
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
sessionFactory = config.buildSessionFactory(builder.build());
logger.debug("Hibernate: configured successfully");
}
/////////////////////////////////////////////////////////////////////////////
public EntityManager createEntityManager() {
return sessionFactory.createEntityManager();
}
/////////////////////////////////////////////////////////////////////////////
public void close(EntityManager manager, boolean commit) {
if (manager != null && manager.isOpen()) {
if (commit) {
manager.getTransaction().commit();
} else {
manager.getTransaction().rollback();
}
manager.close();
}
}
@Override
public String getDatabaseUrl() {
return config.getProperty(AvailableSettings.URL);
}
@Override
public String getDriverName() {
return config.getProperty(AvailableSettings.DRIVER);
}
@Override
public String getPassword() {
return config.getProperty(AvailableSettings.PASS);
}
@Override
public Properties getProperties() {
return config.getProperties();
}
@Override
public String getProperty(String property, String defaultValue) {
String value = config.getProperty(property);
if (value != null) {
return value;
}
return defaultValue;
}
@Override
public String getTestQuery() {
JK.implementMe();
return null;
}
@Override
public String getUsername() {
return config.getProperty(AvailableSettings.USER);
}
@Override
public String getDatabaseName() {
try (Connection connnectino = getConnection()) {
return getConnection().getCatalog();
} catch (Exception e) {
JK.throww(e);
return null;
}
}
@Override
public int getQueryLimit() {
return JKConversionUtil.toInteger(jkConfig.getProperty(JKDbConstants.QUERY_ROWS_COUNT, JKDbConstants.DEFAULT_QUERY_ROW_COUNT));
}
@Override
public void close() {
sessionFactory.close();
}
@Override
public void close(Connection con) {
try {
if (con == null || con.isClosed()) {
return;
}
con.close();
} catch (final SQLException e) {
}
}
@Override
public void close(Connection connection, boolean commit) {
try {
if (commit) {
this.logger.trace("commit transaction");
connection.commit();
} else {
this.logger.trace("rollback transaction");
connection.rollback();
}
} catch (final SQLException e) {
// throw new JKDataAccessException(e);
} finally {
close(connection);
}
}
@Override
public void close(ResultSet rs) {
logger.trace("close rs");
if (rs != null) {
try {
rs.close();
} catch (final Exception e) {
}
}
}
@Override
public void close(Statement stmt) {
logger.trace(stmt);
if (stmt != null) {
try {
stmt.close();
} catch (final Exception e) {
}
}
}
@Override
public Connection getConnection() throws JKDataAccessException {
Connection connection = ((SessionImpl) sessionFactory.openSession()).connection();
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
throw new JKDataAccessException(e);
}
return connection;
}
@Override
public Connection getQueryConnection() throws JKDataAccessException {
return getConnection();
}
@Override
public JKDatabase getDatabaseType() {
return JKDatabase.getDatabaseByUrl(getDatabaseUrl());
}
@Override
public void resetCache() {
}
@Override
public int getDatabasePort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getDatabaseHost() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getBaseScriptPath(JKDatabase databaseType) {
return "/scripts/" + databaseType.toString().toLowerCase() + "/base.sql";
}
// /*
// * (non-Javadoc)
// *
// * @see com.jk.db.datasource.JKDataSource#getPersisitnceUnitInfo(java.lang.
// * String, java.util.Properties, java.lang.String)
// */
// public PersistenceUnitInfo getPersisitnceUnitInfo(String persisitnceUnitName, Properties prop, String entitiesPackages) {
// logger.debug("getPersisitnceUnitInfo: ", persisitnceUnitName, " Prop: ", prop, " Entities packages : ", entitiesPackages);
// PersistenceUnitInfo info ;//getCache().get(persisitnceUnitName, PersistenceUnitInfo.class);
//// if (info == null) {
// List<String> entityClassNames = AnnotationDetector.scanAsList(Entity.class, entitiesPackages.split(","));
// logger.debug("Entities : ", entityClassNames);
// info = new JKPersistenceUnitInfoImpl(persisitnceUnitName, entityClassNames, prop);
//// getCache().cache(persisitnceUnitName, info, PersistenceUnitInfo.class);
//// }
// return info;
// }
// /*
// * (non-Javadoc)
// *
// * @see com.jk.db.datasource.JKDataSource#close(javax.persistence.EntityManager,
// * boolean)
// */
// @Override
// public void close(EntityManager em, boolean commit) {
// if (em != null) {
// if (commit && !em.getTransaction().getRollbackOnly()) {
// em.getTransaction().commit();
// } else {
// em.getTransaction().rollback();
// }
// em.close();
// }
// }
// this.entitiesPackages = this.config.getProperty(JKDbConstants.PROPERTY_DB_ENTITY_PACKAGES, JKDbConstants.DEFAULT_DB_ENTITY_PACKAGES);
// /*
// * (non-Javadoc)
// *
// * @see com.jk.db.datasource.JKDataSource#getEntitiesPackages()
// */
// @Override
// public String getEntitiesPackages() {
// return entitiesPackages;
// }
//
// @Override
// public EntityManagerFactory getEntityManagerFactory() {
// logger.debug("getEntityManagerFactory() ");
// //= getCache().get(name, EntityManagerFactory.class);
// if (emf == null) {
// logger.debug("EMF not loaded, loading now...");
// Properties prop = new Properties();
// prop.setProperty(JKPersistenceUnitProperties.JDBC_DRIVER, getDriverName());
// prop.setProperty(JKPersistenceUnitProperties.JDBC_PASSWORD, getPassword());
// prop.setProperty(JKPersistenceUnitProperties.JDBC_URL, getDatabaseUrl());
// prop.setProperty(JKPersistenceUnitProperties.JDBC_USER, getUsername());
// prop.setProperty("hibernate.hbm2ddl.auto", "update");
// // settings.put("dialect", "org.hibernate.dialect.MySQL57InnoDBDialect");
//
// PersistenceUnitInfo persisitnceUnitInfo = getPersisitnceUnitInfo(JKDbConstants.DEFAULT_PERSISINCE_UNIT_NAME, prop, getEntitiesPackages());
// emf = JKEntityManagerFactory.createEntityManagerFactory(persisitnceUnitInfo);
//// logger.debug("add to emf cache ");
//// getCache().cache(JKDbConstants.DEFAULT_PERSISINCE_UNIT_NAME, emf, EntityManagerFactory.class);
// }
// return emf;
// }
// /*
// * (non-Javadoc)
// *
// * @see com.jk.db.datasource.JKDataSource#createEntityManager()
// */
// @Override
// public EntityManager createEntityManager() {
// EntityManager em = getEntityManagerFactory().createEntityManager();
// em.getTransaction().begin();
// return em;
//
// }
}
| |
package mods.mud.gui;
import java.awt.Desktop;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.xml.bind.DatatypeConverter;
import mods.mud.ModUpdateDetector;
import mods.mud.UpdateChecker;
import mods.mud.UpdateEntry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.StatCollector;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
public class GuiChangelogDownload extends GuiScreen
{
private GuiSlotModList modList;
private int selected = -1;
private UpdateEntry selectedMod;
private ArrayList<UpdateEntry> entries;
private String[] changelog;
int lineStart = 0;
private GuiButton disable;
private GuiButton download;
private GuiButton close1;
private GuiButton ok;
private GuiButton urlButton;
private boolean isDownloading = false;
private boolean downloadComplete = false;
private boolean downloadFailed = false;
private float downloadPercent;
private String message;
private GuiScreen parent;
private char[] bullets = new char[]{0x2219, 0x25E6, 0x2023};
private int[] bulletWidth = new int[3];
private Thread getChangeLogThread;
public GuiChangelogDownload(GuiScreen parent){
this.parent = parent;
changelog = new String[]{StatCollector.translateToLocal("log.message.loading")};
if(!ModUpdateDetector.hasChecked){
new UpdateChecker(ModUpdateDetector.getAllUpdateEntries()).run();
}
this.entries=new ArrayList<UpdateEntry>(ModUpdateDetector.getAllUpdateEntries());
}
public GuiChangelogDownload(){
this(null);
}
@Override
public void initGui()
{
this.buttonList.clear();
this.modList=new GuiSlotModList(this, entries, 100);
this.modList.registerScrollButtons(this.buttonList, 1, 2);
for(int i= 0; i < bullets.length; i++){
bulletWidth[i] = fontRendererObj.getStringWidth(bullets[i]+" ");
}
disable = new GuiButton(3, 15, 10, 125, 20, StatCollector.translateToLocal("mud.disable")+": "+Boolean.toString(!ModUpdateDetector.enabled));
download = new GuiButton(4, 15, height-35, 125, 20, StatCollector.translateToLocal("button.download.latest"));
download.enabled = false;
close1 = new GuiButton(5, width-140, height-35, 125, 20, StatCollector.translateToLocal("gui.done"));
ok = new GuiButton(6, (width - 200)/2 + 5, (height - 150)/2+115, 190, 20, StatCollector.translateToLocal("button.ok"));
urlButton = new GuiButton(7, (width - 125)/2, height-35, 125, 20, StatCollector.translateToLocal("button.url"));
urlButton.enabled = false;
ok.visible = isDownloading;
ok.enabled = downloadComplete || downloadFailed;
buttonList.add(disable);
buttonList.add(download);
buttonList.add(close1);
buttonList.add(ok);
buttonList.add(urlButton);
}
@Override
protected void keyTyped(char par1, int par2)
{
if(!isDownloading){
if (par2 == 1)
{
this.mc.displayGuiScreen(parent);
this.mc.setIngameFocus();
}
}
}
@Override
protected void actionPerformed(GuiButton button) {
if (button.enabled)
{
if(!isDownloading || (downloadFailed || downloadComplete) ){
switch (button.id)
{
case 3:
isDownloading = false;
close1.enabled = true;
ModUpdateDetector.toggleState();
disable.displayString = StatCollector.translateToLocal("mud.disable")+":"+Boolean.toString(!ModUpdateDetector.enabled);
return;
case 4:
ModContainer mc = selectedMod.getMc();
String filename = String.format("[%s] %s - %s.jar",
Loader.instance().getMCVersionString().replaceAll("Minecraft", "").trim(),
mc.getName(),
selectedMod.getLatest().getVersionString());
File newFile = new File(mc.getSource().getParent(), filename);
Thread t = new Thread(new Downloader(selectedMod.getLatest().download,
newFile, mc.getSource(), selectedMod.getLatest().md5
));
t.start();
isDownloading = true;
ok.visible = true;
close1.enabled = false;
download.enabled = false;
urlButton.enabled = false;
return;
case 5:
this.mc.displayGuiScreen(parent);
return;
case 6:
isDownloading = false;
downloadComplete = false;
downloadFailed = false;
ok.visible = false;
close1.enabled = true;
urlButton.enabled=true;
return;
case 7:
if(selectedMod != null && selectedMod.getLatest() != null && selectedMod.getLatest().url != null){
try {
Desktop.getDesktop().browse(new URI(selectedMod.getLatest().url));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}catch (URISyntaxException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return;
}
}
}
super.actionPerformed(button);
}
@Override
public void drawDefaultBackground() {
super.drawBackground(0);
}
@Override
public void drawScreen(int p_571_1_, int p_571_2_, float p_571_3_)
{
if(modList != null)
this.modList.drawScreen(p_571_1_, p_571_2_, p_571_3_);
if(selectedMod != null){
int start = 32;
for(int i = lineStart; i < changelog.length && start < height-52; i++){
start = drawText(changelog[i], start);
}
}
int mouse_x = Mouse.getEventX() * this.width / this.mc.displayWidth;
int mouse_y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1;
if(mouse_x > 125 && mouse_y > 35 && mouse_y < height-50){
int scroll = Mouse.getDWheel();
if(scroll < 0 && lineStart < changelog.length-15){
lineStart++;
}
if(scroll > 0 && lineStart > 0){
lineStart--;
}
}
if(isDownloading){
ok.visible = true;
int x = (width - 200)/2;
int y = (height - 150)/2;
drawRect(x-1,y-1,x+201, y+151, 0xFFFFFFFF);
drawRect(x,y,x+200, y+150, 0xFF000000);
drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.downloading"), width/2, y + 15, 0xFFFFFF00);
drawRect(x + 24, y + 39, x+176, y+56, 0xFFFFFFFF);
drawRect(x + 25, y + 40, (x+25 + 150), y+55, 0xFF000000);
drawRect(x + 25, y + 40, (int)(x+25 + 150*downloadPercent), y+55, 0xFFc0c0c0);
drawVerticalLine((int)(x+25 + 150*downloadPercent)-1, y + 39, y+55, 0xFF808080);
drawHorizontalLine(x + 25, (int)(x+25 + 150*downloadPercent)-1, y + 54, 0xFF808080);
if(downloadComplete){
drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.download.complete"), width/2, y + 70, 0xFF44FF44);
}
if(downloadFailed){
drawCenteredString(fontRendererObj, StatCollector.translateToLocal("gui.download.failed"), width/2, y + 70, 0xFFFF0000);
}
if(message != null){
drawCenteredString(fontRendererObj, message, width/2, y + 85, 0xFFFFFFFF);
}
ok.drawButton(mc, p_571_1_, p_571_2_);
}
super.drawScreen(p_571_1_, p_571_2_, p_571_3_);
}
private int drawText(String line, int start) {
int startX = 125;
if(line == null){
return 5;
} else if(line.startsWith("==") && line.substring(2).contains("==")){
String main = line.substring(2, line.lastIndexOf("==")).trim();
float scale = 1F;
GL11.glScalef(1/scale, 1/scale, 1/scale);
this.drawString(fontRendererObj, main.replaceAll("=", "").trim(), (int)((startX)*scale), (int)(start*scale), 0xFFFFFF00);
GL11.glScalef(scale, scale, scale);
if(line.lastIndexOf("==")+2 <= line.length()){
String sub = line.substring(line.lastIndexOf("==")+2, line.length()).trim();
GL11.glScalef(1/scale, 1/scale, 1/scale);
this.drawString(fontRendererObj, sub.replaceAll("=", "").trim(), (int)((startX+fontRendererObj.getStringWidth(main+" "))*scale), (int)(start*scale), 0xFF2222FF);
GL11.glScalef(scale, scale, scale);
}
return (int)(1F/scale * 10)+start;
}else if(line.trim().startsWith("**") && line.trim().endsWith("**")){
float scale = 1.1F;
GL11.glScalef(1/scale, 1/scale, 1/scale);
this.drawString(fontRendererObj, line.replaceAll("\\*\\*", "").trim(), (int)((startX)*scale), (int)(start*scale), 0xFFFFFFFF);
GL11.glScalef(scale, scale, scale);
return (int)(1F/scale * 10)+start;
}else{
float scale = 1.2F;
GL11.glScalef(1/scale, 1/scale, 1/scale);
int bullet = -1;
while(line.startsWith("*")){
startX+=10;
line = line.substring(1).trim();
bullet++;
}
if(bullet > 3){
bullet = 3;
}
List<String> lineList = fontRendererObj.listFormattedStringToWidth(line, width - 10 - startX);
Iterator<String> it = lineList.iterator();
for(int i = 0; it.hasNext(); i++){
String subline = it.next().trim();
if(i == 0 && bullet > -1){
subline = bullets[bullet]+" "+subline;
}else if (bullet > -1){
startX+=bulletWidth[bullet];
}
this.drawString(fontRendererObj, subline, (int) ((startX) * scale), (int) (start * scale), 0xFFFFFFFF);
start += (int)(1F/scale * 10);
}
GL11.glScalef(scale, scale, scale);
return start;
}
}
Minecraft getMinecraftInstance() {
return mc;
}
FontRenderer getFontRenderer() {
return fontRendererObj;
}
/**
* @param var1
*/
public void selectModIndex(int var1)
{
if(getChangeLogThread == null || !getChangeLogThread.isAlive()){
this.selected=var1;
if (var1>=0 && var1<=entries.size()) {
this.selectedMod=entries.get(selected);
} else {
this.selectedMod=null;
}
urlButton.enabled = selectedMod!=null && selectedMod.getLatest()!=null && selectedMod.getLatest().url!=null;
if(selectedMod!=null) {
if (selectedMod.getChangelogURL() == null) {
changelog = new String[]{StatCollector.translateToLocal("log.message.none")};
} else {
getChangeLogThread = new Thread(new ChangelogLoader(selectedMod.getChangelogURL()));
getChangeLogThread.start();
changelog = new String[]{StatCollector.translateToLocal("log.message.loading")};
}
try {
if (!selectedMod.isUpToDate()) {
download.enabled = true;
download.displayString = StatCollector.translateToLocal("button.download.latest");
}
} catch (Exception e) {
}
}
}
}
public boolean modIndexSelected(int var1)
{
return var1==selected;
}
private class ChangelogLoader implements Runnable{
URL changelogURL;
private ChangelogLoader(URL changelogURL) {
this.changelogURL = changelogURL;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(changelogURL.openStream()));
String line = br.readLine();
ArrayList<String> lines = new ArrayList<String>(100);
if(line != null)
lines.add(line);
while(line != null){
line = br.readLine();
lines.add(line);
}
changelog = lines.toArray(new String[0]);
} catch (IOException e) {
e.printStackTrace();
changelog = new String[]{StatCollector.translateToLocal("log.message.fail")};
}
}
}
private class Downloader implements Runnable{
private String downloadUrl = "";
private File file = null;
private File orginial;
private byte[] expectedMd5;
public Downloader(String url, File location, File originalFile, String md5){
this.downloadUrl = url;
this.file = location;
this.orginial = originalFile;
if(md5 != null){
try{
this.expectedMd5 = DatatypeConverter.parseHexBinary(md5.toUpperCase());
}catch (Exception e){
e.printStackTrace();
this.expectedMd5 = null;
}
}
}
@Override
public void run() {
try {
isDownloading = true;
if(file.exists())
file.delete();
file.createNewFile();
URL url=new URL(downloadUrl);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
float totalDataRead=0;
java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int i;
while((i=in.read(data,0,1024))>=0)
{
totalDataRead=totalDataRead+i;
bout.write(data,0,i);
downloadPercent=(totalDataRead)/filesize;
}
bout.close();
in.close();
if(expectedMd5 != null){
DataInputStream dis = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte [] fileData = new byte[(int)file.length()];
dis = new DataInputStream((new FileInputStream(file)));
dis.readFully(fileData);
dis.close();
byte[] md5 = md.digest(fileData);
ModUpdateDetector.logger.trace("Expected MD5: "+bytArrayToHex(expectedMd5));
ModUpdateDetector.logger.trace("File MD5: "+bytArrayToHex(md5));
if(Arrays.equals(md5, expectedMd5)){
downloadComplete = true;
ok.enabled = true;
message = StatCollector.translateToLocal("gui.restart");
}else{
downloadComplete = false;
downloadFailed = true;
ok.enabled = true;
message = StatCollector.translateToLocal("gui.md5.fail");
//file.delete();
}
} catch (Exception e) {
e.printStackTrace();
if(dis != null){
try{
dis.close();
}catch (Exception ex){}
}
downloadFailed = true;
ok.enabled = true;
}
}else{
downloadComplete = true;
ok.enabled = true;
message = StatCollector.translateToLocal("gui.restart");
}
if(downloadComplete &&
orginial.exists() &&
!orginial.getName().equals(file.getName()) &&
!orginial.isDirectory()
){
ModUpdateDetector.logger.trace("Deleting: "+orginial.getAbsolutePath());
if(!orginial.delete()){
ModUpdateDetector.logger.trace("Deleting failed, spawning new process to delete");
String cmd = "java -classpath \""+file.getAbsolutePath()+"\" mods.mud.utils.FileDeleter \""+orginial.getAbsolutePath()+"\"";
Runtime.getRuntime().exec(cmd);
}
}
} catch (IOException e) {
e.printStackTrace();
message = StatCollector.translateToLocal(e.getLocalizedMessage());
downloadFailed = true;
ok.enabled = true;
}
}
}
String bytArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder();
for(byte b: a)
sb.append(String.format("%02x", b&0xff));
return sb.toString();
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.execution;
import com.facebook.presto.metadata.Node;
import com.facebook.presto.metadata.NodeManager;
import com.facebook.presto.spi.HostAddress;
import com.facebook.presto.spi.Split;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.SetMultimap;
import com.google.common.net.InetAddresses;
import org.weakref.jmx.Managed;
import javax.inject.Inject;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class NodeScheduler
{
private final NodeManager nodeManager;
private final AtomicLong scheduleLocal = new AtomicLong();
private final AtomicLong scheduleRack = new AtomicLong();
private final AtomicLong scheduleRandom = new AtomicLong();
private final int minCandidates;
@Inject
public NodeScheduler(NodeManager nodeManager, NodeSchedulerConfig config)
{
this.nodeManager = nodeManager;
this.minCandidates = config.getMinCandidates();
}
@Managed
public long getScheduleLocal()
{
return scheduleLocal.get();
}
@Managed
public long getScheduleRack()
{
return scheduleRack.get();
}
@Managed
public long getScheduleRandom()
{
return scheduleRandom.get();
}
@Managed
public void reset()
{
scheduleLocal.set(0);
scheduleRack.set(0);
scheduleRandom.set(0);
}
public NodeSelector createNodeSelector(final String dataSourceName, final Comparator<Node> nodeComparator)
{
// this supplier is thread-safe. TODO: this logic should probably move to the scheduler since the choice of which node to run in should be
// done as close to when the the split is about to be scheduled
final Supplier<NodeMap> nodeMap = Suppliers.memoizeWithExpiration(new Supplier<NodeMap>()
{
@Override
public NodeMap get()
{
ImmutableSetMultimap.Builder<HostAddress, Node> byHostAndPort = ImmutableSetMultimap.builder();
ImmutableSetMultimap.Builder<InetAddress, Node> byHost = ImmutableSetMultimap.builder();
ImmutableSetMultimap.Builder<Rack, Node> byRack = ImmutableSetMultimap.builder();
Set<Node> nodes;
if (dataSourceName != null) {
nodes = nodeManager.getActiveDatasourceNodes(dataSourceName);
}
else {
nodes = nodeManager.getAllNodes().getActiveNodes();
}
for (Node node : nodes) {
try {
byHostAndPort.put(node.getHostAndPort(), node);
InetAddress host = InetAddress.getByName(node.getHttpUri().getHost());
byHost.put(host, node);
byRack.put(Rack.of(host), node);
}
catch (UnknownHostException e) {
// ignore
}
}
return new NodeMap(byHostAndPort.build(), byHost.build(), byRack.build());
}
}, 5, TimeUnit.SECONDS);
return new NodeSelector(nodeComparator, nodeMap);
}
public class NodeSelector
{
private final Comparator<Node> nodeComparator;
private final AtomicReference<Supplier<NodeMap>> nodeMap;
public NodeSelector(Comparator<Node> nodeComparator, Supplier<NodeMap> nodeMap)
{
this.nodeComparator = nodeComparator;
this.nodeMap = new AtomicReference<>(nodeMap);
}
public void lockDownNodes()
{
nodeMap.set(Suppliers.ofInstance(nodeMap.get().get()));
}
public List<Node> allNodes()
{
return ImmutableList.copyOf(nodeMap.get().get().getNodesByHostAndPort().values());
}
public Node selectRandomNode()
{
// create a single partition on a random node for this fragment
ArrayList<Node> nodes = new ArrayList<>(nodeMap.get().get().getNodesByHostAndPort().values());
Preconditions.checkState(!nodes.isEmpty(), "Cluster does not have any active nodes");
Collections.shuffle(nodes, ThreadLocalRandom.current());
return nodes.get(0);
}
public Node selectNode(Split split)
{
// select acceptable nodes
List<Node> nodes = selectNodes(nodeMap.get().get(), split, minCandidates);
Preconditions.checkState(!nodes.isEmpty(), "No nodes available to run query");
// select the node with the smallest number of assignments
Node chosen = Ordering.from(nodeComparator).min(nodes);
return chosen;
}
private List<Node> selectNodes(NodeMap nodeMap, Split split, int minCount)
{
Set<Node> chosen = new LinkedHashSet<>(minCount);
// first look for nodes that match the hint
for (HostAddress hint : split.getAddresses()) {
for (Node node : nodeMap.getNodesByHostAndPort().get(hint)) {
if (chosen.add(node)) {
scheduleLocal.incrementAndGet();
}
}
InetAddress address;
try {
address = hint.toInetAddress();
}
catch (UnknownHostException e) {
// skip addresses that don't resolve
continue;
}
// consider a split with a host hint without a port as being accessible
// by all nodes in that host
if (!hint.hasPort() || split.isRemotelyAccessible()) {
for (Node node : nodeMap.getNodesByHost().get(address)) {
if (chosen.add(node)) {
scheduleLocal.incrementAndGet();
}
}
}
}
// add nodes in same rack, if below the minimum count
if (split.isRemotelyAccessible() && chosen.size() < minCount) {
for (HostAddress hint : split.getAddresses()) {
InetAddress address;
try {
address = hint.toInetAddress();
}
catch (UnknownHostException e) {
// skip addresses that don't resolve
continue;
}
for (Node node : nodeMap.getNodesByRack().get(Rack.of(address))) {
if (chosen.add(node)) {
scheduleRack.incrementAndGet();
}
if (chosen.size() == minCount) {
break;
}
}
if (chosen.size() == minCount) {
break;
}
}
}
// add some random nodes if below the minimum count
if (split.isRemotelyAccessible()) {
if (chosen.size() < minCount) {
for (Node node : lazyShuffle(nodeMap.getNodesByHost().values())) {
if (chosen.add(node)) {
scheduleRandom.incrementAndGet();
}
if (chosen.size() == minCount) {
break;
}
}
}
}
return ImmutableList.copyOf(chosen);
}
}
private static <T> Iterable<T> lazyShuffle(final Iterable<T> iterable)
{
return new Iterable<T>()
{
@Override
public Iterator<T> iterator()
{
return new AbstractIterator<T>()
{
List<T> list = Lists.newArrayList(iterable);
int limit = list.size();
@Override
protected T computeNext()
{
if (limit == 0) {
return endOfData();
}
int position = ThreadLocalRandom.current().nextInt(limit);
T result = list.get(position);
list.set(position, list.get(limit - 1));
limit--;
return result;
}
};
}
};
}
private static class NodeMap
{
private final SetMultimap<HostAddress, Node> nodesByHostAndPort;
private final SetMultimap<InetAddress, Node> nodesByHost;
private final SetMultimap<Rack, Node> nodesByRack;
public NodeMap(SetMultimap<HostAddress, Node> nodesByHostAndPort, SetMultimap<InetAddress, Node> nodesByHost, SetMultimap<Rack, Node> nodesByRack)
{
this.nodesByHostAndPort = nodesByHostAndPort;
this.nodesByHost = nodesByHost;
this.nodesByRack = nodesByRack;
}
private SetMultimap<HostAddress, Node> getNodesByHostAndPort()
{
return nodesByHostAndPort;
}
public SetMultimap<InetAddress, Node> getNodesByHost()
{
return nodesByHost;
}
public SetMultimap<Rack, Node> getNodesByRack()
{
return nodesByRack;
}
}
private static class Rack
{
private int id;
public static Rack of(InetAddress address)
{
// TODO: this needs to be pluggable
int id = InetAddresses.coerceToInteger(address) & 0xFF_FF_FF_00;
return new Rack(id);
}
private Rack(int id)
{
this.id = id;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Rack rack = (Rack) o;
if (id != rack.id) {
return false;
}
return true;
}
@Override
public int hashCode()
{
return id;
}
}
}
| |
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.db.record.ridbag.sbtree;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import com.orientechnologies.common.profiler.OProfilerMBean;
import com.orientechnologies.common.serialization.types.OBooleanSerializer;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.index.sbtree.OSBTreeMapEntryIterator;
import com.orientechnologies.orient.core.index.sbtree.OTreeInternal;
import com.orientechnologies.orient.core.index.sbtree.local.OSBTreeException;
import com.orientechnologies.orient.core.index.sbtreebonsai.local.OBonsaiBucketPointer;
import com.orientechnologies.orient.core.index.sbtreebonsai.local.OSBTreeBonsaiLocal;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
/**
* Persistent Set<OIdentifiable> implementation that uses the SBTree to handle entries in persistent way.
*
* @author <a href="mailto:enisher@gmail.com">Artem Orobets</a>
*/
public class OIndexRIDContainerSBTree implements Set<OIdentifiable> {
public static final String INDEX_FILE_EXTENSION = ".irs";
private OSBTreeBonsaiLocal<OIdentifiable, Boolean> tree;
protected static final OProfilerMBean PROFILER = Orient.instance().getProfiler();
public OIndexRIDContainerSBTree(long fileId, boolean durableMode) {
tree = new OSBTreeBonsaiLocal<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, durableMode);
tree.create(fileId, OLinkSerializer.INSTANCE, OBooleanSerializer.INSTANCE);
}
public OIndexRIDContainerSBTree(long fileId, OBonsaiBucketPointer rootPointer, boolean durableMode) {
tree = new OSBTreeBonsaiLocal<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, durableMode);
tree.load(fileId, rootPointer, (OAbstractPaginatedStorage) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage()
.getUnderlying());
}
public OIndexRIDContainerSBTree(String file, OBonsaiBucketPointer rootPointer, boolean durableMode) {
tree = new OSBTreeBonsaiLocal<OIdentifiable, Boolean>(INDEX_FILE_EXTENSION, durableMode);
final OAbstractPaginatedStorage storage = (OAbstractPaginatedStorage) ODatabaseRecordThreadLocal.INSTANCE.get().getStorage()
.getUnderlying();
final long fileId;
try {
fileId = storage.getDiskCache().openFile(file + INDEX_FILE_EXTENSION);
} catch (IOException e) {
throw new OSBTreeException("Exception during loading of sbtree " + file, e);
}
tree.load(fileId, rootPointer, storage);
}
public OBonsaiBucketPointer getRootPointer() {
return tree.getRootBucketPointer();
}
@Override
public int size() {
return (int) tree.size();
}
@Override
public boolean isEmpty() {
return tree.size() == 0L;
}
@Override
public boolean contains(Object o) {
return o instanceof OIdentifiable && contains((OIdentifiable) o);
}
public boolean contains(OIdentifiable o) {
return tree.get(o) != null;
}
@Override
public Iterator<OIdentifiable> iterator() {
return new TreeKeyIterator(tree, false);
}
@Override
public Object[] toArray() {
// TODO replace with more efficient implementation
final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());
for (OIdentifiable identifiable : this) {
list.add(identifiable);
}
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
// TODO replace with more efficient implementation.
final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(size());
for (OIdentifiable identifiable : this) {
list.add(identifiable);
}
return list.toArray(a);
}
@Override
public boolean add(OIdentifiable oIdentifiable) {
return this.tree.put(oIdentifiable, Boolean.TRUE);
}
@Override
public boolean remove(Object o) {
return o instanceof OIdentifiable && remove((OIdentifiable) o);
}
public boolean remove(OIdentifiable o) {
return tree.remove(o) != null;
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
@Override
public boolean addAll(Collection<? extends OIdentifiable> c) {
boolean modified = false;
for (OIdentifiable e : c)
if (add(e))
modified = true;
return modified;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = false;
Iterator<OIdentifiable> it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object o : c) {
modified |= remove(o);
}
return modified;
}
@Override
public void clear() {
tree.clear();
}
public void delete() {
tree.delete();
}
public String getName() {
return tree.getName();
}
private static class TreeKeyIterator implements Iterator<OIdentifiable> {
private final boolean autoConvertToRecord;
private OSBTreeMapEntryIterator<OIdentifiable, Boolean> entryIterator;
public TreeKeyIterator(OTreeInternal<OIdentifiable, Boolean> tree, boolean autoConvertToRecord) {
entryIterator = new OSBTreeMapEntryIterator<OIdentifiable, Boolean>(tree);
this.autoConvertToRecord = autoConvertToRecord;
}
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public OIdentifiable next() {
final OIdentifiable identifiable = entryIterator.next().getKey();
if (autoConvertToRecord)
return identifiable.getRecord();
else
return identifiable;
}
@Override
public void remove() {
entryIterator.remove();
}
}
}
| |
/**
* Copyright (C) 2016 Bruno Candido Volpato da Cunha (brunocvcunha@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.brunocvcunha.instagram4j.requests;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.util.EntityUtils;
import org.brunocvcunha.instagram4j.InstagramConstants;
import org.brunocvcunha.instagram4j.requests.payload.StatusResult;
import org.brunocvcunha.instagram4j.util.InstagramGenericUtil;
import lombok.Builder;
import lombok.NonNull;
import lombok.extern.log4j.Log4j;
/**
* Direct-share request.
*
* @author Evgeny Bondarenko (evgbondarenko@gmail.com)
*
*/
@Log4j
@Builder
public class InstagramDirectShareRequest extends InstagramRequest<StatusResult> {
@NonNull
private ShareType shareType;
/**
* List of recipients IDs (i.e. "1234567890")
*/
private List<String> recipients;
/**
* The thread ID to share to
*/
private String threadId;
/**
* The media ID in instagram's internal format (ie "223322332233_22332").
*/
private String mediaId;
private String message;
private String link;
@Override
public String getUrl() throws IllegalArgumentException {
String result;
switch (shareType) {
case MESSAGE:
result = "direct_v2/threads/broadcast/text/";
break;
case MEDIA:
result = "direct_v2/threads/broadcast/media_share/?media_type=photo";
break;
case LINK:
result = "direct_v2/threads/broadcast/link/";
default:
throw new IllegalArgumentException("Invalid shareType parameter value: " + shareType);
}
return result;
}
@Override
public String getMethod() {
return "POST";
}
@Override
public StatusResult execute() throws ClientProtocolException, IOException {
String recipients = "";
if (this.recipients != null) {
recipients = "\"" + String.join("\",\"", this.recipients.toArray(new String[0])) + "\"";
}
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
if (shareType == ShareType.MEDIA) {
map.put("type", "form-data");
map.put("name", "media_id");
map.put("data", mediaId);
data.add(map);
}
if (shareType == ShareType.LINK) {
map = new HashMap();
map.put("type", "form-data");
map.put("name", "link_text");
map.put("data", this.link == null ? "" : this.link);
data.add(map);
map = new HashMap();
map.put("type", "form-data");
map.put("name", "link_urls");
map.put("data", "[\"" + this.link + "\"]");
data.add(map);
}
if (shareType == ShareType.MESSAGE) {
map = new HashMap<String, String>();
map.put("type", "form-data");
map.put("name", "text");
map.put("data", message == null ? "" : message);
data.add(map);
}
map = map.size() > 0 ? new HashMap<String, String>() : map;
map.put("type", "form-data");
map.put("name", "recipient_users");
map.put("data", "[[" + recipients + "]]");
data.add(map);
map = new HashMap<String, String>();
map.put("type", "form-data");
map.put("name", "client_context");
map.put("data", InstagramGenericUtil.generateUuid(true));
data.add(map);
map = new HashMap<String, String>();
map.put("type", "form-data");
map.put("name", "thread_ids");
map.put("data", "[" + (threadId != null ? threadId : "") + "]");
data.add(map);
HttpPost post = createHttpRequest();
post.setEntity(new ByteArrayEntity(buildBody(data, api.getUuid()).getBytes(StandardCharsets.UTF_8)));
HttpResponse response = api.executeHttpRequest(post);
int resultCode = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity());
log.info("Direct-share request result: " + resultCode + ", " + content);
post.releaseConnection();
StatusResult result = parseResult(resultCode, content);
return result;
}
@Override
public StatusResult parseResult(int resultCode, String content) {
return parseJson(resultCode, content, StatusResult.class);
}
protected HttpPost createHttpRequest() {
String url = InstagramConstants.API_URL + getUrl();
log.info("Direct-share URL: " + url);
HttpPost post = new HttpPost(url);
post.addHeader("User-Agent", InstagramConstants.USER_AGENT);
post.addHeader("Connection", "keep-alive");
post.addHeader("Proxy-Connection", "keep-alive");
post.addHeader("Accept", "*/*");
post.addHeader("Content-Type", "multipart/form-data; boundary=" + api.getUuid());
post.addHeader("Accept-Language", "en-US");
return post;
}
protected String buildBody(List<Map<String, String>> bodies, String boundary) {
StringBuilder sb = new StringBuilder();
String newLine = "\r\n";
for (Map<String, String> b : bodies) {
sb.append("--").append(boundary).append(newLine).append("Content-Disposition: ").append(b.get("type"))
.append("; name=\"").append(b.get("name")).append("\"").append(newLine).append(newLine)
.append(b.get("data")).append(newLine);
}
sb.append("--").append(boundary).append("--");
String body = sb.toString();
log.debug("Direct-share message body: " + body);
return body;
}
protected void init() {
switch (shareType) {
case MEDIA:
if (mediaId == null || mediaId.isEmpty()) {
throw new IllegalArgumentException("mediaId cannot be null or empty.");
}
break;
case MESSAGE:
if (message == null || message.isEmpty()) {
throw new IllegalArgumentException("message cannot be null or empty.");
}
break;
case LINK:
if (link == null || link.isEmpty()) {
throw new IllegalArgumentException("link cannot be null or empty.");
}
break;
default:
break;
}
}
public enum ShareType {
MESSAGE, MEDIA, LINK
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.optimizer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import org.apache.hadoop.hive.ql.exec.JoinOperator;
import org.apache.hadoop.hive.ql.exec.Operator;
import org.apache.hadoop.hive.ql.exec.OperatorFactory;
import org.apache.hadoop.hive.ql.exec.ReduceSinkOperator;
import org.apache.hadoop.hive.ql.exec.RowSchema;
import org.apache.hadoop.hive.ql.exec.SelectOperator;
import org.apache.hadoop.hive.ql.exec.TableScanOperator;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.GraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.lib.Rule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ParseContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc.ExprNodeDescEqualityWrapper;
import org.apache.hadoop.hive.ql.plan.ExprNodeDescUtils;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.FilterDesc;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.ReduceSinkDesc;
import org.apache.hadoop.hive.ql.plan.SelectDesc;
import org.apache.hadoop.hive.ql.plan.UnionDesc;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPAnd;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNot;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* SkewJoinOptimizer.
*
*/
public class SkewJoinOptimizer extends Transform {
private static final Logger LOG = LoggerFactory.getLogger(SkewJoinOptimizer.class.getName());
public static class SkewJoinProc implements NodeProcessor {
private ParseContext parseContext;
public SkewJoinProc(ParseContext parseContext) {
super();
this.parseContext = parseContext;
}
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
// We should be having a tree which looks like this
// TS -> * -> RS -
// \
// -> JOIN -> ..
// /
// TS -> * -> RS -
//
// We are in the join operator now.
SkewJoinOptProcCtx ctx = (SkewJoinOptProcCtx) procCtx;
parseContext = ctx.getpGraphContext();
JoinOperator joinOp = (JoinOperator)nd;
// This join has already been processed
if (ctx.getDoneJoins().contains(joinOp)) {
return null;
}
ctx.getDoneJoins().add(joinOp);
Operator<? extends OperatorDesc> currOp = joinOp;
boolean processSelect = false;
// Is there a select following
// Clone the select also. It is useful for a follow-on optimization where the union
// followed by a select star is completely removed.
if ((joinOp.getChildOperators().size() == 1) &&
(joinOp.getChildOperators().get(0) instanceof SelectOperator)) {
currOp = joinOp.getChildOperators().get(0);
processSelect = true;
}
List<TableScanOperator> tableScanOpsForJoin = new ArrayList<TableScanOperator>();
if (!getTableScanOpsForJoin(joinOp, tableScanOpsForJoin)) {
return null;
}
if ((tableScanOpsForJoin == null) || (tableScanOpsForJoin.isEmpty())) {
return null;
}
// Get the skewed values in all the tables
Map<List<ExprNodeDesc>, List<List<String>>> skewedValues =
getSkewedValues(joinOp, tableScanOpsForJoin);
// If there are no skewed values, nothing needs to be done
if (skewedValues == null || skewedValues.size() == 0) {
return null;
}
// After this optimization, the tree should be like:
// TS -> (FIL "skewed rows") * -> RS -
// \
// -> JOIN
// / \
// TS -> (FIL "skewed rows") * -> RS - \
// \
// -> UNION -> ..
// /
// TS -> (FIL "no skewed rows") * -> RS - /
// \ /
// -> JOIN
// /
// TS -> (FIL "no skewed rows") * -> RS -
//
// Create a clone of the operator
Operator<? extends OperatorDesc> currOpClone;
try {
currOpClone = currOp.clone();
insertRowResolvers(currOp, currOpClone, ctx);
} catch (CloneNotSupportedException e) {
LOG.debug("Operator tree could not be cloned");
return null;
}
JoinOperator joinOpClone;
if (processSelect) {
joinOpClone = (JoinOperator)(currOpClone.getParentOperators().get(0));
} else {
joinOpClone = (JoinOperator)currOpClone;
}
joinOpClone.getConf().cloneQBJoinTreeProps(joinOp.getConf());
parseContext.getJoinOps().add(joinOpClone);
List<TableScanOperator> tableScanCloneOpsForJoin =
new ArrayList<TableScanOperator>();
if (!getTableScanOpsForJoin(joinOpClone, tableScanCloneOpsForJoin)) {
LOG.debug("Operator tree not properly cloned!");
return null;
}
// Put the filter "skewed column = skewed keys" in op
// and "skewed columns != skewed keys" in selectOpClone
insertSkewFilter(tableScanOpsForJoin, skewedValues, true);
insertSkewFilter(tableScanCloneOpsForJoin, skewedValues, false);
// Update the topOps appropriately
Map<String, Operator<? extends OperatorDesc>> topOps = getTopOps(joinOpClone);
Map<String, TableScanOperator> origTopOps = parseContext.getTopOps();
for (Entry<String, Operator<? extends OperatorDesc>> topOp : topOps.entrySet()) {
TableScanOperator tso = (TableScanOperator) topOp.getValue();
String tabAlias = tso.getConf().getAlias();
int initCnt = 1;
String newAlias = "subquery" + initCnt + ":" + tabAlias;
while (origTopOps.containsKey(newAlias)) {
initCnt++;
newAlias = "subquery" + initCnt + ":" + tabAlias;
}
parseContext.getTopOps().put(newAlias, tso);
setUpAlias(joinOp, joinOpClone, tabAlias, newAlias, tso);
}
// Now do a union of the select operators: selectOp and selectOpClone
// Store the operator that follows the select after the join, we will be
// adding this as a child to the Union later
List<Operator<? extends OperatorDesc>> finalOps = currOp.getChildOperators();
currOp.setChildOperators(null);
currOpClone.setChildOperators(null);
// Make the union operator
List<Operator<? extends OperatorDesc>> oplist =
new ArrayList<Operator<? extends OperatorDesc>>();
oplist.add(currOp);
oplist.add(currOpClone);
Operator<? extends OperatorDesc> unionOp =
OperatorFactory.getAndMakeChild(currOp.getCompilationOpContext(),
new UnionDesc(), new RowSchema(currOp.getSchema().getSignature()), oplist);
// Introduce a select after the union
List<Operator<? extends OperatorDesc>> unionList =
new ArrayList<Operator<? extends OperatorDesc>>();
unionList.add(unionOp);
Operator<? extends OperatorDesc> selectUnionOp =
OperatorFactory.getAndMakeChild(currOp.getCompilationOpContext(), new SelectDesc(true),
new RowSchema(unionOp.getSchema().getSignature()), unionList);
// add the finalOp after the union
selectUnionOp.setChildOperators(finalOps);
// replace the original selectOp in the parents with selectUnionOp
for (Operator<? extends OperatorDesc> finalOp : finalOps) {
finalOp.replaceParent(currOp, selectUnionOp);
}
return null;
}
/*
* Get the list of table scan operators for this join. A interface supportSkewJoinOptimization
* has been provided. Currently, it is only enabled for simple filters and selects.
*/
private boolean getTableScanOpsForJoin(
JoinOperator op,
List<TableScanOperator> tsOps) {
for (Operator<? extends OperatorDesc> parent : op.getParentOperators()) {
if (!getTableScanOps(parent, tsOps)) {
return false;
}
}
return true;
}
private boolean getTableScanOps(
Operator<? extends OperatorDesc> op,
List<TableScanOperator> tsOps) {
for (Operator<? extends OperatorDesc> parent : op.getParentOperators()) {
if (!parent.supportSkewJoinOptimization()) {
return false;
}
if (parent instanceof TableScanOperator) {
tsOps.add((TableScanOperator)parent);
} else if (!getTableScanOps(parent, tsOps)) {
return false;
}
}
return true;
}
/**
* Returns the skewed values in all the tables which are going to be scanned.
* If the join is on columns c1, c2 and c3 on tables T1 and T2,
* T1 is skewed on c1 and c4 with the skew values ((1,2),(3,4)),
* whereas T2 is skewed on c1, c2 with skew values ((5,6),(7,8)), the resulting
* map would be: <(c1) -> ((1), (3)), (c1,c2) -> ((5,6),(7,8))>
* @param op The join operator being optimized
* @param tableScanOpsForJoin table scan operators which are parents of the join operator
* @return map<join keys intersection skewedkeys, list of skewed values>.
* @throws SemanticException
*/
private Map<List<ExprNodeDesc>, List<List<String>>>
getSkewedValues(
Operator<? extends OperatorDesc> op, List<TableScanOperator> tableScanOpsForJoin) throws SemanticException {
Map <List<ExprNodeDesc>, List<List<String>>> skewDataReturn =
new HashMap<List<ExprNodeDesc>, List<List<String>>>();
Map <List<ExprNodeDescEqualityWrapper>, List<List<String>>> skewData =
new HashMap<List<ExprNodeDescEqualityWrapper>, List<List<String>>>();
// The join keys are available in the reduceSinkOperators before join
for (Operator<? extends OperatorDesc> reduceSinkOp : op.getParentOperators()) {
ReduceSinkDesc rsDesc = ((ReduceSinkOperator) reduceSinkOp).getConf();
if (rsDesc.getKeyCols() != null) {
TableScanOperator tableScanOp = null;
Table table = null;
// Find the skew information corresponding to the table
List<String> skewedColumns = null;
List<List<String>> skewedValueList = null;
// The join columns which are also skewed
List<ExprNodeDescEqualityWrapper> joinKeysSkewedCols =
new ArrayList<ExprNodeDescEqualityWrapper>();
// skewed Keys which intersect with join keys
List<Integer> positionSkewedKeys = new ArrayList<Integer>();
// Update the joinKeys appropriately.
for (ExprNodeDesc keyColDesc : rsDesc.getKeyCols()) {
ExprNodeColumnDesc keyCol = null;
// If the key column is not a column, then dont apply this optimization.
// This will be fixed as part of https://issues.apache.org/jira/browse/HIVE-3445
// for type conversion UDFs.
if (keyColDesc instanceof ExprNodeColumnDesc) {
keyCol = (ExprNodeColumnDesc) keyColDesc;
if (table == null) {
tableScanOp = getTableScanOperator(parseContext, reduceSinkOp, tableScanOpsForJoin);
table =
tableScanOp == null ? null : tableScanOp.getConf().getTableMetadata();
skewedColumns =
table == null ? null : table.getSkewedColNames();
// No skew on the table to take care of
if ((skewedColumns == null) || (skewedColumns.isEmpty())) {
continue;
}
skewedValueList =
table == null ? null : table.getSkewedColValues();
}
ExprNodeDesc keyColOrigin = ExprNodeDescUtils.backtrack(keyCol,
reduceSinkOp, tableScanOp);
int pos = keyColOrigin == null || !(keyColOrigin instanceof ExprNodeColumnDesc) ?
-1 : skewedColumns.indexOf(((ExprNodeColumnDesc)keyColOrigin).getColumn());
if ((pos >= 0) && (!positionSkewedKeys.contains(pos))) {
positionSkewedKeys.add(pos);
ExprNodeColumnDesc keyColClone = (ExprNodeColumnDesc) keyColOrigin.clone();
keyColClone.setTabAlias(null);
joinKeysSkewedCols.add(new ExprNodeDescEqualityWrapper(keyColClone));
}
}
}
// If the skew keys match the join keys, then add it to the list
if ((skewedColumns != null) && (!skewedColumns.isEmpty())) {
if (!joinKeysSkewedCols.isEmpty()) {
// If the join keys matches the skewed keys, use the table skewed keys
List<List<String>> skewedJoinValues;
if (skewedColumns.size() == positionSkewedKeys.size()) {
skewedJoinValues = skewedValueList;
}
else {
skewedJoinValues =
getSkewedJoinValues(skewedValueList, positionSkewedKeys);
}
List<List<String>> oldSkewedJoinValues =
skewData.get(joinKeysSkewedCols);
if (oldSkewedJoinValues == null) {
oldSkewedJoinValues = new ArrayList<List<String>>();
}
for (List<String> skewValue : skewedJoinValues) {
if (!oldSkewedJoinValues.contains(skewValue)) {
oldSkewedJoinValues.add(skewValue);
}
}
skewData.put(joinKeysSkewedCols, oldSkewedJoinValues);
}
}
}
}
// convert skewData to contain ExprNodeDesc in the keys
for (Map.Entry<List<ExprNodeDescEqualityWrapper>, List<List<String>>> mapEntry :
skewData.entrySet()) {
List<ExprNodeDesc> skewedKeyJoinCols = new ArrayList<ExprNodeDesc>();
for (ExprNodeDescEqualityWrapper key : mapEntry.getKey()) {
skewedKeyJoinCols.add(key.getExprNodeDesc());
}
skewDataReturn.put(skewedKeyJoinCols, mapEntry.getValue());
}
return skewDataReturn;
}
/**
* Get the table scan.
*/
private TableScanOperator getTableScanOperator(
ParseContext parseContext,
Operator<? extends OperatorDesc> op,
List<TableScanOperator> tableScanOpsForJoin) {
while (true) {
if (op instanceof TableScanOperator) {
TableScanOperator tsOp = (TableScanOperator)op;
if (tableScanOpsForJoin.contains(tsOp)) {
return tsOp;
}
}
if ((op.getParentOperators() == null) || (op.getParentOperators().isEmpty()) ||
(op.getParentOperators().size() > 1)) {
return null;
}
op = op.getParentOperators().get(0);
}
}
/*
* If the skewedValues contains ((1,2,3),(4,5,6)), and the user is looking for
* positions (0,2), the result would be ((1,3),(4,6))
* Get the skewed key values that are part of the join key.
* @param skewedValuesList List of all the skewed values
* @param positionSkewedKeys the requested positions
* @return sub-list of skewed values with the positions present
*/
private List<List<String>> getSkewedJoinValues(
List<List<String>> skewedValueList, List<Integer> positionSkewedKeys) {
List<List<String>> skewedJoinValues = new ArrayList<List<String>>();
for (List<String> skewedValuesAllColumns : skewedValueList) {
List<String> skewedValuesSpecifiedColumns = new ArrayList<String>();
for (int pos : positionSkewedKeys) {
skewedValuesSpecifiedColumns.add(skewedValuesAllColumns.get(pos));
}
skewedJoinValues.add(skewedValuesSpecifiedColumns);
}
return skewedJoinValues;
}
/**
* Inserts a filter comparing the join keys with the skewed keys. If the table
* is skewed with values (k1, v1) and (k2, v2) on columns (key, value), then
* filter ((key=k1 AND value=v1) OR (key=k2 AND value=v2)) is inserted. If @skewed
* is false, a NOT is inserted before it.
* @param tableScanOpsForJoin table scans for which the filter will be inserted
* @param skewedValuesList the map of <expressions, list of skewed values>
* @param skewed True if we want skewedCol = skewedValue, false if we want
* not (skewedCol = skewedValue)
*/
private void insertSkewFilter(
List<TableScanOperator> tableScanOpsForJoin,
Map<List<ExprNodeDesc>, List<List<String>>> skewedValuesList,
boolean skewed) {
ExprNodeDesc filterExpr = constructFilterExpr(skewedValuesList, skewed);
for (TableScanOperator tableScanOp : tableScanOpsForJoin) {
insertFilterOnTop(tableScanOp, filterExpr);
}
}
/**
* Inserts a filter below the table scan operator. Construct the filter
* from the filter expression provided.
* @param tableScanOp the table scan operators
* @param filterExpr the filter expression
*/
private void insertFilterOnTop(
TableScanOperator tableScanOp,
ExprNodeDesc filterExpr) {
// Get the top operator and it's child, all operators have a single parent
Operator<? extends OperatorDesc> currChild = tableScanOp.getChildOperators().get(0);
// Create the filter Operator and update the parents and children appropriately
tableScanOp.setChildOperators(null);
currChild.setParentOperators(null);
Operator<FilterDesc> filter = OperatorFactory.getAndMakeChild(
new FilterDesc(filterExpr, false),
new RowSchema(tableScanOp.getSchema().getSignature()), tableScanOp);
OperatorFactory.makeChild(filter, currChild);
}
/**
* Construct the filter expression from the skewed keys and skewed values.
* If the skewed join keys are (k1), and (k1,k3) with the skewed values
* (1,2) and ((2,3),(4,5)) respectively, the filter expression would be:
* (k1=1) or (k1=2) or ((k1=2) and (k3=3)) or ((k1=4) and (k3=5)).
*/
private ExprNodeDesc constructFilterExpr(
Map<List<ExprNodeDesc>, List<List<String>>> skewedValuesMap,
boolean skewed) {
ExprNodeDesc finalExprNodeDesc = null;
try {
for (Map.Entry<List<ExprNodeDesc>, List<List<String>>> mapEntry :
skewedValuesMap.entrySet()) {
List<ExprNodeDesc> keyCols = mapEntry.getKey();
List<List<String>> skewedValuesList = mapEntry.getValue();
for (List<String> skewedValues : skewedValuesList) {
int keyPos = 0;
ExprNodeDesc currExprNodeDesc = null;
// Make the following condition: all the values match for all the columns
for (String skewedValue : skewedValues) {
List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>();
// We have ensured that the keys are columns
ExprNodeColumnDesc keyCol = (ExprNodeColumnDesc) keyCols.get(keyPos).clone();
keyPos++;
children.add(keyCol);
// Convert the constants available as strings to the corresponding objects
children.add(createConstDesc(skewedValue, keyCol));
ExprNodeGenericFuncDesc expr = null;
// Create the equality condition
expr = ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPEqual(), children);
if (currExprNodeDesc == null) {
currExprNodeDesc = expr;
} else {
// If there are previous nodes, then AND the current node with the previous one
List<ExprNodeDesc> childrenAND = new ArrayList<ExprNodeDesc>();
childrenAND.add(currExprNodeDesc);
childrenAND.add(expr);
currExprNodeDesc =
ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPAnd(), childrenAND);
}
}
// If there are more than one skewed values,
// then OR the current node with the previous one
if (finalExprNodeDesc == null) {
finalExprNodeDesc = currExprNodeDesc;
} else {
List<ExprNodeDesc> childrenOR = new ArrayList<ExprNodeDesc>();
childrenOR.add(finalExprNodeDesc);
childrenOR.add(currExprNodeDesc);
finalExprNodeDesc =
ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPOr(), childrenOR);
}
}
}
// Add a NOT operator in the beginning (this is for the cloned operator because we
// want the values which are not skewed
if (skewed == false) {
List<ExprNodeDesc> childrenNOT = new ArrayList<ExprNodeDesc>();
childrenNOT.add(finalExprNodeDesc);
finalExprNodeDesc =
ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPNot(), childrenNOT);
}
} catch (UDFArgumentException e) {
// Ignore the exception because we are not comparing Long vs. String here.
// There should never be an exception
assert false;
}
return finalExprNodeDesc;
}
/**
* Converts the skewedValue available as a string in the metadata to the appropriate object
* by using the type of the column from the join key.
* @param skewedValue
* @param keyCol
* @return an expression node descriptor of the appropriate constant
*/
private ExprNodeConstantDesc createConstDesc(
String skewedValue, ExprNodeColumnDesc keyCol) {
ObjectInspector inputOI = TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(
TypeInfoFactory.stringTypeInfo);
ObjectInspector outputOI = TypeInfoUtils.getStandardJavaObjectInspectorFromTypeInfo(
keyCol.getTypeInfo());
Converter converter = ObjectInspectorConverters.getConverter(inputOI, outputOI);
Object skewedValueObject = converter.convert(skewedValue);
return new ExprNodeConstantDesc(keyCol.getTypeInfo(), skewedValueObject);
}
private Map<String, Operator<? extends OperatorDesc>> getTopOps(
Operator<? extends OperatorDesc> op) {
// Must be deterministic order map for consistent q-test output across
// Java versions
Map<String, Operator<? extends OperatorDesc>> topOps =
new LinkedHashMap<String, Operator<? extends OperatorDesc>>();
if (op.getParentOperators() == null || op.getParentOperators().size() == 0) {
topOps.put(((TableScanOperator)op).getConf().getAlias(), op);
} else {
for (Operator<? extends OperatorDesc> parent : op.getParentOperators()) {
if (parent != null) {
topOps.putAll(getTopOps(parent));
}
}
}
return topOps;
}
private void insertRowResolvers(
Operator<? extends OperatorDesc> op,
Operator<? extends OperatorDesc> opClone,
SkewJoinOptProcCtx ctx) {
if (op instanceof TableScanOperator) {
ctx.getCloneTSOpMap().put((TableScanOperator)opClone, (TableScanOperator)op);
}
List<Operator<? extends OperatorDesc>> parents = op.getParentOperators();
List<Operator<? extends OperatorDesc>> parentClones = opClone.getParentOperators();
if ((parents != null) && (!parents.isEmpty()) &&
(parentClones != null) && (!parentClones.isEmpty())) {
for (int pos = 0; pos < parents.size(); pos++) {
insertRowResolvers(parents.get(pos), parentClones.get(pos), ctx);
}
}
}
/**
* Set alias in the cloned join tree
*/
private static void setUpAlias(JoinOperator origin, JoinOperator cloned, String origAlias,
String newAlias, Operator<? extends OperatorDesc> topOp) {
cloned.getConf().getAliasToOpInfo().remove(origAlias);
cloned.getConf().getAliasToOpInfo().put(newAlias, topOp);
if (origin.getConf().getLeftAlias().equals(origAlias)) {
cloned.getConf().setLeftAlias(null);
cloned.getConf().setLeftAlias(newAlias);
}
replaceAlias(origin.getConf().getLeftAliases(), cloned.getConf().getLeftAliases(), origAlias, newAlias);
replaceAlias(origin.getConf().getRightAliases(), cloned.getConf().getRightAliases(), origAlias, newAlias);
replaceAlias(origin.getConf().getBaseSrc(), cloned.getConf().getBaseSrc(), origAlias, newAlias);
replaceAlias(origin.getConf().getMapAliases(), cloned.getConf().getMapAliases(), origAlias, newAlias);
replaceAlias(origin.getConf().getStreamAliases(), cloned.getConf().getStreamAliases(), origAlias, newAlias);
}
private static void replaceAlias(String[] origin, String[] cloned,
String alias, String newAlias) {
if (origin == null || cloned == null || origin.length != cloned.length) {
return;
}
for (int i = 0; i < origin.length; i++) {
if (origin[i].equals(alias)) {
cloned[i] = newAlias;
}
}
}
private static void replaceAlias(List<String> origin, List<String> cloned,
String alias, String newAlias) {
if (origin == null || cloned == null || origin.size() != cloned.size()) {
return;
}
for (int i = 0; i < origin.size(); i++) {
if (origin.get(i).equals(alias)) {
cloned.set(i, newAlias);
}
}
}
}
/* (non-Javadoc)
* @see org.apache.hadoop.hive.ql.optimizer.Transform#transform
* (org.apache.hadoop.hive.ql.parse.ParseContext)
*/
@Override
public ParseContext transform(ParseContext pctx) throws SemanticException {
Map<Rule, NodeProcessor> opRules = new LinkedHashMap<Rule, NodeProcessor>();
opRules.put(new RuleRegExp("R1", "TS%.*RS%JOIN%"), getSkewJoinProc(pctx));
SkewJoinOptProcCtx skewJoinOptProcCtx = new SkewJoinOptProcCtx(pctx);
// The dispatcher fires the processor corresponding to the closest matching
// rule and passes the context along
Dispatcher disp = new DefaultRuleDispatcher(
null, opRules, skewJoinOptProcCtx);
GraphWalker ogw = new DefaultGraphWalker(disp);
// Create a list of topop nodes
List<Node> topNodes = new ArrayList<Node>();
topNodes.addAll(pctx.getTopOps().values());
ogw.startWalking(topNodes, null);
return pctx;
}
private NodeProcessor getSkewJoinProc(ParseContext parseContext) {
return new SkewJoinProc(parseContext);
}
/**
* SkewJoinOptProcCtx.
*
*/
public static class SkewJoinOptProcCtx implements NodeProcessorCtx {
private ParseContext pGraphContext;
// set of joins already processed
private Set<JoinOperator> doneJoins;
private Map<TableScanOperator, TableScanOperator> cloneTSOpMap;
public SkewJoinOptProcCtx(ParseContext pctx) {
this.pGraphContext = pctx;
doneJoins = new HashSet<JoinOperator>();
cloneTSOpMap = new HashMap<TableScanOperator, TableScanOperator>();
}
public ParseContext getpGraphContext() {
return pGraphContext;
}
public void setPGraphContext(ParseContext graphContext) {
pGraphContext = graphContext;
}
public Set<JoinOperator> getDoneJoins() {
return doneJoins;
}
public void setDoneJoins(Set<JoinOperator> doneJoins) {
this.doneJoins = doneJoins;
}
public Map<TableScanOperator, TableScanOperator> getCloneTSOpMap() {
return cloneTSOpMap;
}
public void setCloneTSOpMap(Map<TableScanOperator, TableScanOperator> cloneTSOpMap) {
this.cloneTSOpMap = cloneTSOpMap;
}
}
}
| |
package game;
import java.util.Vector;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Graphics;
public class Game {
public static final int HUMAN = 0;
public static final int COMPUTER_A = 1;
public static final int COMPUTER_B = 2;
public static final int NUM_PLAYERS = 3;
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int SELECT_HAND = 0;
public static final int SELECT_SET = 1;
private Graphics doubleBufferGraphics = null;
private int screenWidth = 0;
private int screenHeight = 0;
private CardGraphics cardGraphics = null;
private Hand deck = new Hand(); // not rendered
private Hand newCardPile = new Hand();
private Hand dumpPile = new Hand();
private Player[] players;
private Sets[] sets;
private int winner = Game.HUMAN;
private int activePlayer = Game.HUMAN;
private int selectionMode = Game.SELECT_HAND;
// if the game's state changes set dirty to true
private boolean dirty = false;
private boolean gameHasEnded = false;
private TongIts theMidlet;
private int playerAreaHeight;
public Game(Image doubleBuffer, TongIts midlet) {
Player[] p = { new Player("You", this)
, new ComputerPlayer("Rey", this), new ComputerPlayer("Ian", this) };
players = p;
Sets[] s = { new Sets(players[HUMAN])
, new Sets(players[COMPUTER_A])
, new Sets(players[COMPUTER_B])};
sets = s;
theMidlet = midlet;
doubleBufferGraphics = doubleBuffer.getGraphics();
doubleBufferGraphics.setClip(0, 0, screenWidth, screenHeight);
cardGraphics = new CardGraphics(doubleBuffer);
screenWidth = doubleBuffer.getWidth();
screenHeight = doubleBuffer.getHeight();
playerAreaHeight = (screenHeight - Config.TOOLBAR_HEIGHT) / 3;
// create the permanent deck
deck.createStandardDeck();
// set the positions of all the hands
initPositions();
}
public void newGame() {
selectionMode = Game.SELECT_HAND;
// initialize the deck
deck.unmark();
deck.deselect();
deck.faceUp();
// empty all hands
newCardPile.clear();
dumpPile.clear();
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
sets[i].clear();
players[i].hand.clear();
players[i].didReveal = players[i].didChow = players[i].didGetNewCard = false;
}
// clear the computer players' hidden sets
ComputerPlayer computer = (ComputerPlayer) players[Game.COMPUTER_A];
computer.sets.clear();
computer = (ComputerPlayer) players[Game.COMPUTER_B];
computer.sets.clear();
// create the new card pile
for (int i = 0; i < deck.getSize(); i++) {
Card card = (Card) deck.cards.elementAt(i);
newCardPile.addCard(card);
}
newCardPile.shuffle();
newCardPile.move();
// the winner in the previous round becomes the mano
players[winner].makeMano();
// deal the cards
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
// deal extra card to the mano
// note that there should ONLY be ONE mano
if (players[i].mano) {
Card card = newCardPile.removeTopCard();
players[i].hand.addCard(card);
players[i].mano = false;
}
// deal 12 cards each
for (int j = 0; j < 12; j++) {
Card card = newCardPile.removeTopCard();
players[i].hand.addCard(card);
}
}
// refresh the positions of the players' hands and sets
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
sets[i].move();
players[i].hand.move();
}
// set the hands that are faced down
newCardPile.faceDown();
players[Game.COMPUTER_A].hand.faceDown();
players[Game.COMPUTER_B].hand.faceDown();
players[Game.HUMAN].hand.sort();
players[Game.COMPUTER_A].hand.sort();
players[Game.COMPUTER_B].hand.sort();
players[winner].activate();
activePlayer = winner;
dirty = true;
gameHasEnded = false;
}
public void renderGame() {
if (!dirty) return;
// if dirty
dirty = false;
// draw the background
doubleBufferGraphics.setClip(0, 0, screenWidth, screenHeight);
doubleBufferGraphics.setClip(0, 0, screenWidth, screenHeight);
doubleBufferGraphics.setColor(0, 128, 128);
doubleBufferGraphics.fillRect(0, 0, screenWidth, playerAreaHeight*2);
doubleBufferGraphics.setColor(0, 128, 0);
doubleBufferGraphics.fillRect(0, playerAreaHeight*2, screenWidth, playerAreaHeight+Config.TOOLBAR_HEIGHT);
doubleBufferGraphics.setColor(255, 255, 255);
doubleBufferGraphics.fillRect(0, playerAreaHeight-1, screenWidth, 1);
doubleBufferGraphics.fillRect(0, playerAreaHeight*2-1, screenWidth, 1);
doubleBufferGraphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_SMALL));
doubleBufferGraphics.setColor(255, 255, 255);
doubleBufferGraphics.drawString("("+players[Game.COMPUTER_B].name+")", screenWidth-1, 2, Graphics.RIGHT | Graphics.TOP);
doubleBufferGraphics.drawString("("+players[Game.COMPUTER_A].name+")", screenWidth-1, playerAreaHeight+2, Graphics.RIGHT | Graphics.TOP);
cardGraphics.drawHand(newCardPile);
cardGraphics.drawHand(dumpPile);
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
for (int j = 0; j < sets[i].hands.size(); j++) {
Hand hand = (Hand) sets[i].hands.elementAt(j);
cardGraphics.drawHand(hand);
}
cardGraphics.drawHand(players[i].hand);
}
// draw the computer players' hidden sets (tago)
ComputerPlayer computer = (ComputerPlayer) players[Game.COMPUTER_A];
cardGraphics.drawSets(computer.sets);
computer = (ComputerPlayer) players[Game.COMPUTER_B];
cardGraphics.drawSets(computer.sets);
// doubleBufferGraphics.setClip(0, 0, screenWidth, screenHeight);
// writeToolbarMsg("test");
if (gameHasEnded) renderWinInfo();
}
public void writeToolbarMsg(String msg) {
// dirty = true;
// doubleBufferGraphics.setColor(0x00666666);
// doubleBufferGraphics.fillRect(0, screenHeight-Config.TOOLBAR_HEIGHT, screenWidth, Config.TOOLBAR_HEIGHT);
// doubleBufferGraphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_SMALL));
// doubleBufferGraphics.setColor(0x00ffffff);
// doubleBufferGraphics.drawString(msg, 1, (screenHeight-Config.TOOLBAR_HEIGHT) + 1, Graphics.LEFT | Graphics.TOP);
}
public void playGame() {
startComputer();
}
public void markNext(int direction) {
if (gameHasEnded) return;
if (players[Game.HUMAN].active) {
if (selectionMode == Game.SELECT_HAND) {
players[Game.HUMAN].markNext(direction == Game.RIGHT);
} else {
players[Game.HUMAN].markNextSet(sets, direction == Game.RIGHT);
}
dirty = true;
}
}
public void select() {
if (gameHasEnded) return;
if (players[Game.HUMAN].active) {
players[Game.HUMAN].selectMarkedCards();
dirty = true;
}
}
public void bunot() {
if (gameHasEnded) return;
if (players[Game.HUMAN].active) {
if (players[Game.HUMAN].didGetNewCard || players[Game.HUMAN].didChow) {
theMidlet.showAlert("You already got a new card or performed a chow.");
return;
}
if (players[Game.HUMAN].bunot(newCardPile)) {
dirty = true;
}
}
}
public void reveal() {
if (gameHasEnded) return;
if (players[Game.HUMAN].active && selectionMode == Game.SELECT_HAND) {
int numCards = players[Game.HUMAN].hand.getNumSelectedCards();
if (numCards < 3) {
return;
}
if (!players[Game.HUMAN].didGetNewCard && !players[Game.HUMAN].didChow) {
theMidlet.showAlert("You must get a new card first or perform a chow.");
return;
}
if (players[Game.HUMAN].reveal(sets[Game.HUMAN])) {
dirty = true;
} else {
theMidlet.showAlert("Not a valid set to reveal.");
}
}
}
public void chow() {
if (gameHasEnded) return;
if (players[Game.HUMAN].active) {
if (players[Game.HUMAN].hand.getNumSelectedCards() == 0) return;
if (players[Game.HUMAN].didGetNewCard || players[Game.HUMAN].didChow) {
theMidlet.showAlert("You already got a new card or performed a chow.");
return;
}
if (players[Game.HUMAN].chow(dumpPile, sets[Game.HUMAN])) {
dirty = true;
} else {
theMidlet.showAlert("Wrong card for chow.");
}
}
}
public void dump() {
if (gameHasEnded) return;
if (players[Game.HUMAN].active && selectionMode == Game.SELECT_HAND) {
int numCards = players[Game.HUMAN].hand.getNumSelectedCards();
if (numCards < 1 || numCards > 1) {
return;
}
if (!players[Game.HUMAN].didGetNewCard && !players[Game.HUMAN].didChow) {
theMidlet.showAlert("You must get a new card first or perform a chow.");
return;
}
if (players[Game.HUMAN].dump(dumpPile)) {
dirty = true;
switchPlayer();
}
}
}
public void sapaw() {
if (gameHasEnded) return;
if (!players[Game.HUMAN].active) return;
if (players[Game.HUMAN].hand.getNumSelectedCards() == 0) return;
if (!players[Game.HUMAN].didChow && !players[Game.HUMAN].didGetNewCard) return;
boolean hasSets = false;
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
if (sets[i].hands.size() > 0) hasSets = true;
}
if (!hasSets) {
theMidlet.showAlert("There are no valid sets available.");
return;
}
if (selectionMode == Game.SELECT_SET) {
selectionMode = Game.SELECT_HAND;
players[Game.HUMAN].hand.move();
players[Game.HUMAN].activate();
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
sets[i].unmark();
}
} else if (selectionMode == Game.SELECT_HAND) {
theMidlet.showAlert("Select the set then press \"Sapaw on Set\" from the menu.");
selectionMode = Game.SELECT_SET;
players[Game.HUMAN].hand.unmark();
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
if (sets[i].hands.size() > 0) {
Hand hand = (Hand) sets[i].hands.firstElement();
hand.mark();
break;
}
}
}
dirty = true;
}
public void doSapaw() {
if (gameHasEnded) return;
if (selectionMode == Game.SELECT_HAND) return;
Vector allSets = new Vector();
for (int i = 0; i < sets.length; i++) {
for (int j = 0; j < sets[i].hands.size(); j++) {
allSets.addElement(sets[i].hands.elementAt(j));
}
}
for (int i = 0; i < allSets.size(); i++) {
Hand hand = (Hand) allSets.elementAt(i);
if (hand.marked) {
if (players[Game.HUMAN].sapaw(hand) == false) {
Debug.out("Sapaw failed :(");
theMidlet.showAlert("Wrong card for sapaw.");
} else {
Debug.out("Sapaw success! :)");
for (int j = 0; j < sets.length; j++) {
sets[j].move();
}
}
break;
}
}
// cancel the sapaw attempt
endSapaw();
dirty = true;
}
private void endSapaw() {
if (selectionMode == Game.SELECT_SET) {
selectionMode = Game.SELECT_HAND;
players[Game.HUMAN].hand.move();
players[Game.HUMAN].activate();
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
sets[i].unmark();
}
}
}
private void startComputer() {
if (gameHasEnded) return;
if (activePlayer == Game.HUMAN) return;
// Debug.out("Computer " + activePlayer);
((ComputerPlayer)players[activePlayer]).playTurn(dumpPile, newCardPile, sets[activePlayer], sets);
if (players[activePlayer].done) switchPlayer();
dirty = true;
}
private void switchPlayer() {
// determine if there is a winner
if (testWinner()) return;
players[activePlayer].deactivate();
if (activePlayer == Game.NUM_PLAYERS - 1) {
activePlayer = Game.HUMAN;
} else {
activePlayer++;
}
players[activePlayer].activate();
}
private boolean testWinner() {
Debug.out("in testWinner()");
if (players[activePlayer].hand.getSize() == 0) {
for (int i = 0; i < NUM_PLAYERS; i++) {
players[i].hand.faceUp();
}
gameHasEnded = true;
} else if(newCardPile.getSize() == 0) {
for (int i = 0; i < NUM_PLAYERS; i++) {
players[i].hand.faceUp();
}
gameHasEnded = true;
}
dirty = gameHasEnded;
return gameHasEnded;
}
private void renderWinInfo() {
if (players[activePlayer].hand.getSize() == 0) {
Debug.out("A player discarded all his cards.");
gameHasEnded = true;
winner = activePlayer;
String msg = players[winner].name
+ " have no cards left. "
+ players[winner].name
+ " won the game! You can start a new game from the menu.";
theMidlet.showAlert(msg);
} else if(newCardPile.getSize() == 0) {
Debug.out("New card pile ran out of cards.");
gameHasEnded = true;
// determine the player with the lowest valued card
winner = getLowestPlayer();
String msg = "No more cards left in the pile. "
+ players[winner].name
+ " won the game! You can start a new game from the menu.";
theMidlet.showAlert(msg);
}
}
private int getLowestPlayer() {
// remove the "tago" cards from the human player
// while (players[Game.HUMAN].prepareToReveal()) {
// players[Game.HUMAN].reveal(sets[Game.HUMAN]);
// }
int loval = 1000;
int val = 0;
int lowestPlayer = 0;
for (int i = 0; i < Game.NUM_PLAYERS; i++) {
if (!players[i].didReveal) continue;
val = players[i].hand.getRankTotal();
if (val < loval) {
loval = val;
lowestPlayer = i;
}
}
return lowestPlayer;
}
private void initPositions() {
// the new card pile
newCardPile.orient(Hand.PILE); // 3D stacked look
newCardPile.move(screenWidth - Config.CARD_WIDTH - 7, playerAreaHeight*2 + 1);
// the dump pile
dumpPile.orient(Hand.PILE);
dumpPile.move(screenWidth - (Config.CARD_WIDTH*2) - 14, playerAreaHeight*2 + 1);
// position and orientation of human player's hand and sets
players[Game.HUMAN].orient(Hand.HORIZONTAL);
players[Game.HUMAN].hand.move(1, playerAreaHeight*2 + 2);
sets[Game.HUMAN].orient(Hand.HORIZONTAL);
sets[Game.HUMAN].move(1, (playerAreaHeight*2) + Config.CARD_HEIGHT + 4);
// position and orientation of computer players' hands and sets
players[Game.COMPUTER_B].orient(Hand.HORIZONTAL);
sets[Game.COMPUTER_B].orient(Hand.HORIZONTAL);
players[Game.COMPUTER_B].hand.move(1, 2);
sets[Game.COMPUTER_B].move(1, Config.CARD_HEIGHT +4);
players[Game.COMPUTER_A].orient(Hand.HORIZONTAL);
sets[Game.COMPUTER_A].orient(Hand.HORIZONTAL);
players[Game.COMPUTER_A].hand.move(1, playerAreaHeight + 2);
sets[Game.COMPUTER_A].move(1, playerAreaHeight + Config.CARD_HEIGHT + 4);
}
}
| |
/*
* Sun Public License Notice
*
* The contents of this file are subject to the Sun Public License
* Version 1.0 (the "License"). You may not use this file except in
* compliance with the License. A copy of the License is available at
* http://www.sun.com/
*
* The Original Code is NetBeans. The Initial Developer of the Original
* Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun
* Microsystems, Inc. All Rights Reserved.
*/
package org.netbeans.lib.cvsclient.command.log;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.text.SyncDateFormat;
import org.jetbrains.annotations.NonNls;
import org.netbeans.lib.cvsclient.JavaCvsSrcBundle;
import org.netbeans.lib.cvsclient.command.AbstractMessageParser;
import org.netbeans.lib.cvsclient.command.KeywordSubstitution;
import org.netbeans.lib.cvsclient.event.IEventSender;
import org.netbeans.lib.cvsclient.file.ICvsFileSystem;
import org.netbeans.lib.cvsclient.util.BugLog;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* @author Thomas Singer
*/
final public class LogMessageParser extends AbstractMessageParser {
// Constants ==============================================================
@NonNls private static final String RCS_FILE = "RCS file: ";
@NonNls private static final String WORKING_FILE = "Working file: ";
@NonNls private static final String HEAD = "head: ";
@NonNls private static final String BRANCH = "branch:";
@NonNls private static final String LOCKS = "locks: ";
@NonNls private static final String ACCESS_LIST = "access list:";
@NonNls private static final String SYMBOLIC_NAMES = "symbolic names:";
@NonNls private static final String KEYWORD_SUBST = "keyword substitution: ";
@NonNls private static final String TOTAL_REVISIONS = "total revisions: ";
@NonNls private static final String SELECTED_REVISIONS = ";\tselected revisions: ";
@NonNls private static final String DESCRIPTION = "description:";
@NonNls private static final String REVISION = "revision ";
@NonNls private static final String DATE = "date: ";
@NonNls private static final String BRANCHES = "branches: ";
@NonNls private static final String AUTHOR = " author: ";
@NonNls private static final String STATE = " state: ";
@NonNls private static final String LINES = " lines: ";
@NonNls private static final String SPLITTER = "----------------------------";
@NonNls private static final String FINAL_SPLIT = "=============";
@NonNls private static final String FINAL_SPLIT_WITH_TAB = "\t=============";
private static final SyncDateFormat[] EXPECTED_DATE_FORMATS = new SyncDateFormat[2];
@NonNls private static final String NO_FILE_MESSAGE = "no file";
static {
initDateFormats();
}
@SuppressWarnings({"HardCodedStringLiteral"})
private static void initDateFormats() {
SimpleDateFormat delegate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
delegate.setTimeZone(TimeZone.getTimeZone("GMT"));
EXPECTED_DATE_FORMATS[0] = new SyncDateFormat(delegate);
delegate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
delegate.setTimeZone(TimeZone.getTimeZone("GMT"));
EXPECTED_DATE_FORMATS[1] = new SyncDateFormat(delegate);
}
// Fields =================================================================
private final IEventSender eventSender;
private final ICvsFileSystem cvsFileSystem;
private LogInformation logInfo;
private Revision revision;
private boolean addingSymNames;
private boolean addingDescription;
private boolean processingRevision;
private List<String> logMessageBuffer;
private final Pattern myRevisionPattern;
// Setup ==================================================================
public LogMessageParser(IEventSender eventSender, ICvsFileSystem cvsFileSystem) {
BugLog.getInstance().assertNotNull(eventSender);
BugLog.getInstance().assertNotNull(cvsFileSystem);
this.cvsFileSystem = cvsFileSystem;
this.eventSender = eventSender;
myRevisionPattern = Pattern.compile("revision \\d+(\\.\\d+){1,3}.*");
}
// Implemented ============================================================
@Override
protected void outputDone() {
if (addingDescription) {
addingDescription = false;
}
if (processingRevision) {
revision.setMessage(getMessageFromBuffer());
logInfo.addRevision(revision);
revision = null;
processingRevision = false;
}
if (logInfo != null) {
eventSender.notifyFileInfoListeners(logInfo);
logInfo = null;
}
logMessageBuffer = null;
}
private String getMessageFromBuffer() {
if (logMessageBuffer.size() > 0 && lastLogMessageIsFinalSeparator(logMessageBuffer.get(logMessageBuffer.size()-1))) {
logMessageBuffer.remove(logMessageBuffer.size()-1);
}
else if (logMessageBuffer.size() > 1 &&
lastLogMessageIsFinalSeparator(logMessageBuffer.get(logMessageBuffer.size()-2)) &&
logMessageBuffer.get(logMessageBuffer.size()-1).length() == 0) {
logMessageBuffer.remove(logMessageBuffer.size()-2);
logMessageBuffer.remove(logMessageBuffer.size()-1);
}
if (logMessageBuffer.size() > 0) {
return StringUtil.join(logMessageBuffer, "\n") + "\n";
}
return "";
}
private static boolean lastLogMessageIsFinalSeparator(String logMessageString) {
return logMessageString.startsWith(FINAL_SPLIT) || logMessageString.startsWith(FINAL_SPLIT_WITH_TAB);
}
@Override
public void parseLine(String line, boolean isErrorMessage) {
if (isErrorMessage) return;
if (processingRevision) {
if (line.startsWith(RCS_FILE)) {
processRcsFile(line.substring(RCS_FILE.length()));
return;
}
if (myRevisionPattern.matcher(line).matches()) {
processRevisionStart(line);
return;
}
if (line.startsWith(DATE)) {
processRevisionDate(line);
return;
}
// first check for the branches tag
if (line.startsWith(BRANCHES)) {
processBranches(line.substring(BRANCHES.length()));
}
else {
logMessageBuffer.add(line);
}
return;
}
if (addingSymNames) {
if (line.startsWith("\t")) {
processSymbolicNames(line.substring(1));
return;
}
}
// revision stuff first -> will be the most common to parse
if (line.startsWith(REVISION)) {
processRevisionStart(line);
return;
}
if (line.startsWith(KEYWORD_SUBST)) {
final String keywordSubstitution = line.substring(KEYWORD_SUBST.length()).trim();
logInfo.setKeywordSubstitution(KeywordSubstitution.getValue(keywordSubstitution));
addingSymNames = false;
return;
}
if (line.startsWith(RCS_FILE)) {
processRcsFile(line.substring(RCS_FILE.length()));
return;
}
if (line.startsWith(WORKING_FILE)) {
processWorkingFile(line.substring(WORKING_FILE.length()));
return;
}
if (line.startsWith(HEAD)) {
logInfo.setHeadRevision(line.substring(HEAD.length()).trim());
return;
}
if (line.startsWith(BRANCH)) {
logInfo.setBranch(line.substring(BRANCH.length()).trim());
return;
}
if (line.startsWith(LOCKS)) {
logInfo.setLocks(line.substring(LOCKS.length()).trim());
return;
}
if (line.startsWith(ACCESS_LIST)) {
logInfo.setAccessList(line.substring(ACCESS_LIST.length()).trim());
return;
}
if (line.startsWith(SYMBOLIC_NAMES)) {
addingSymNames = true;
return;
}
if (line.startsWith(TOTAL_REVISIONS)) {
final int semicolonIndex = line.indexOf(SELECTED_REVISIONS);
if (semicolonIndex < 0) {
// no selected revisions here..
logInfo.setTotalRevisions(line.substring(TOTAL_REVISIONS.length()).trim());
logInfo.setSelectedRevisions("0");
}
else {
final String totalRevisions = line.substring(0, semicolonIndex);
final String selectedRevisions = line.substring(semicolonIndex);
logInfo.setTotalRevisions(totalRevisions.substring(TOTAL_REVISIONS.length()).trim());
logInfo.setSelectedRevisions(selectedRevisions.substring(SELECTED_REVISIONS.length()).trim());
}
return;
}
if (addingDescription) {
if (!processingRevision && line.startsWith(SPLITTER)) {
return;
}
logMessageBuffer.add(line);
return;
}
if (line.startsWith(DESCRIPTION)) {
logMessageBuffer = new ArrayList<>();
logMessageBuffer.add(line.substring(DESCRIPTION.length()));
addingDescription = true;
}
}
// Utils ==================================================================
private void processRcsFile(String line) {
if (logInfo != null) {
outputDone();
}
logInfo = new LogInformation();
logInfo.setRcsFileName(line.trim());
}
private void processWorkingFile(String line) {
String fileName = line.trim();
if (fileName.startsWith(NO_FILE_MESSAGE)) {
fileName = fileName.substring(8);
}
logInfo.setFile(createFile(fileName));
}
private void processBranches(String line) {
final int ind = line.lastIndexOf(';');
if (ind > 0) {
line = line.substring(0, ind);
}
revision.setBranches(line.trim());
}
private void processSymbolicNames(String line) {
final int index = line.lastIndexOf(':');
if (index < 0) {
return;
}
final String symName = line.substring(0, index).trim();
final String revName = line.substring(index + 1).trim();
logInfo.addSymbolicName(symName, revName);
}
private void processRevisionStart(String line) {
revisionProcessingFinished();
int tabIndex = line.indexOf('\t', REVISION.length());
if (tabIndex < 0) {
tabIndex = line.length();
}
final String revisionNumber = line.substring(REVISION.length(), tabIndex);
revision = new Revision(revisionNumber);
processingRevision = true;
}
private void revisionProcessingFinished() {
if (revision != null) {
if (logMessageBuffer.size() > 0 && logMessageBuffer.get(logMessageBuffer.size()-1).startsWith(SPLITTER)) {
logMessageBuffer.remove(logMessageBuffer.size()-1);
}
processingRevision = false;
revision.setMessage(getMessageFromBuffer());
logInfo.addRevision(revision);
}
}
private void processRevisionDate(String line) {
// a line may looks like:
// date: 2003/02/20 14:52:06; author: tom; state: Exp; lines: +1 -1; kopt: o; commitid: 3803e54eb96167d;
// or:
// date: 2003/01/11 17:56:27; author: tom; state: Exp;
final StringTokenizer token = new StringTokenizer(line, ";", false);
if (token.hasMoreTokens()) {
final String date = token.nextToken();
final String dateString = date.substring(DATE.length());
Date parsedDate = null;
for (SyncDateFormat expectedDateFormat : EXPECTED_DATE_FORMATS) {
try {
parsedDate = expectedDateFormat.parse(dateString);
}
catch (ParseException e) {
//ignore
}
if (parsedDate != null) break;
}
if (parsedDate != null) {
revision.setDate(parsedDate);
}
else {
BugLog.getInstance().showException(new Exception(JavaCvsSrcBundle.message("line.could.not.be.parsed.error.message", line)));
}
}
if (token.hasMoreTokens()) {
final String author = token.nextToken();
if (author.startsWith(AUTHOR)) {
revision.setAuthor(author.substring(AUTHOR.length()));
}
}
if (token.hasMoreTokens()) {
final String state = token.nextToken();
if (state.startsWith(STATE)) {
revision.setState(state.substring(STATE.length()));
}
}
if (token.hasMoreTokens()) {
final String linesModified = token.nextToken();
if (linesModified.startsWith(LINES)) {
revision.setLines(linesModified.substring(LINES.length()));
}
}
processingRevision = true;
logMessageBuffer = new ArrayList<>();
}
private File createFile(String fileName) {
return cvsFileSystem.getLocalFileSystem().getFile(fileName);
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* CmsMetadataKey.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v202111;
/**
* Key associated with a piece of content from a publisher's CMS.
*/
public class CmsMetadataKey implements java.io.Serializable {
/* The ID of this CMS metadata key. This field is read-only and
* provided by Google. */
private java.lang.Long id;
/* The key of a key-value pair. */
private java.lang.String name;
/* The status of this CMS metadata key.
* This attribute is read-only. */
private com.google.api.ads.admanager.axis.v202111.CmsMetadataKeyStatus status;
public CmsMetadataKey() {
}
public CmsMetadataKey(
java.lang.Long id,
java.lang.String name,
com.google.api.ads.admanager.axis.v202111.CmsMetadataKeyStatus status) {
this.id = id;
this.name = name;
this.status = status;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("id", getId())
.add("name", getName())
.add("status", getStatus())
.toString();
}
/**
* Gets the id value for this CmsMetadataKey.
*
* @return id * The ID of this CMS metadata key. This field is read-only and
* provided by Google.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this CmsMetadataKey.
*
* @param id * The ID of this CMS metadata key. This field is read-only and
* provided by Google.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this CmsMetadataKey.
*
* @return name * The key of a key-value pair.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this CmsMetadataKey.
*
* @param name * The key of a key-value pair.
*/
public void setName(java.lang.String name) {
this.name = name;
}
/**
* Gets the status value for this CmsMetadataKey.
*
* @return status * The status of this CMS metadata key.
* This attribute is read-only.
*/
public com.google.api.ads.admanager.axis.v202111.CmsMetadataKeyStatus getStatus() {
return status;
}
/**
* Sets the status value for this CmsMetadataKey.
*
* @param status * The status of this CMS metadata key.
* This attribute is read-only.
*/
public void setStatus(com.google.api.ads.admanager.axis.v202111.CmsMetadataKeyStatus status) {
this.status = status;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CmsMetadataKey)) return false;
CmsMetadataKey other = (CmsMetadataKey) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.name==null && other.getName()==null) ||
(this.name!=null &&
this.name.equals(other.getName()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CmsMetadataKey.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "CmsMetadataKey"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202111", "CmsMetadataKeyStatus"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| |
import java.util.*;
import java.io.*;
public class poj_2430 {
/************************ SOLUTION STARTS HERE ************************/
static final int INF = (int) 1e9;
static void prettyPrint(int a[][]) {
int n = a.length;
int m = a[0].length;
int temp[][] = new int[n + 1][m + 1];
temp[0][0] = -1;
for(int i = 1; i <= n; i++) {
temp[i][0] = i - 1;
System.arraycopy(a[i - 1], 0, temp[i], 1, m);
}
for(int j = 1; j <= m; j++)
temp[0][j] = j - 1;
for(int t[] : temp) {
for(int tt : t)
print(String.format("%3d ", tt));
print('\n');
}
print('\n');
}
private static void solve() {
int N = nextInt();
int K = nextInt();
int B = nextInt();
int arr[][] = new int[N][];
for(int i = 0; i < N; i++)
arr[i] = nextIntArray(2);
// long st = System.nanoTime();
Arrays.sort(arr , new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[1] != o2[1])
return o1[1] - o2[1];
else
return o1[0] - o2[0];
}
});
int sz = 1;
for(int i = 1; i < N; i++)
sz += arr[i][1] != arr[i - 1][1] ? 1 : 0;
int compress[][] = new int[sz][2]; // 0 - up , 1 - down , 2 - both
int ptr = 0;
for(int i = 0; i < N; ) {
compress[ptr][0] = arr[i][1];
if(i + 1 < N && arr[i][1] == arr[i + 1][1]) {
compress[ptr++][1] = 2;
i += 2;
} else {
compress[ptr++][1] = arr[i][0] - 1;
i++;
}
}
int[][] costH1 = new int[sz][sz];
int[][] costH2 = new int[sz][sz];
int[][] costV = new int[sz][sz];
/*
for(int i = 0; i < sz; i++)
print(String.format("%5d ", compress[i][0]));
print('\n');
for(int i = 0; i < sz; i++)
print(String.format("%5d ", compress[i][1]));
print('\n');
*/
for(int i = 0; i < sz; i++) {
int firstUp = 0 , firstDown = 0;
int lastUp = -1 , lastDown = -1;
costH1[i][i] = compress[i][1] == 2 ? INF : 1;
costH2[i][i] = compress[i][1] == 2 ? 2 : INF;
costV[i][i] = 2;
int first = compress[i][1];
boolean flag = compress[i][1] != 2;
if(compress[i][1] != 1)
firstUp = lastUp = compress[i][0];
if(compress[i][1] != 0)
firstDown = lastDown = compress[i][0];
for(int j = i + 1; j < sz; j++) {
costV[i][j] = 2 * (compress[j][0] - compress[i][0] + 1);
flag &= compress[j][1] == first;
costH1[i][j] = flag ? compress[j][0] - compress[i][0] + 1 : INF;
if(firstUp == 0 && compress[j][1] != 1)
firstUp = lastUp = compress[j][0];
if(firstDown == 0 && compress[j][1] != 0)
firstDown = lastDown = compress[j][0];
lastUp = compress[j][1] != 1 ? compress[j][0] : lastUp;
lastDown = compress[j][1] != 0 ? compress[j][0] : lastDown;
costH2[i][j] = flag ? INF : (lastUp - firstUp + 1) + (lastDown - firstDown + 1);
}
}
/*
println("Vertical");
prettyPrint(costV);
println("Hori 1");
prettyPrint(costH1);
println("Hori 2");
prettyPrint(costH2);
*/
int DP[][] = new int[K + 1][sz];
Arrays.fill(DP[0], INF);
for(int i = 0; i < sz; i++)
DP[1][i] = Math.min(costV[0][i] , costH1[0][i]);
for(int i = 2; i <= K; i++) {
for(int j = 0; j < sz; j++) {
DP[i][j] = INF;
for(int k = -1; k < j; k++) {
int dp1 = k == -1 ? 0 : DP[i - 1][k];
int dp2 = k == -1 ? 0 : DP[i - 2][k];
DP[i][j] = Math.min(DP[i][j] , dp1 + Math.min(costV[k + 1][j] , costH1[k + 1][j]));
DP[i][j] = Math.min(DP[i][j] , dp2 + costH2[k + 1][j]);
}
}
}
//prettyPrint(DP);
println(DP[K][sz - 1]);
// println("Time : " + (System.nanoTime() - st) / 1e9);
}
static int compress[][];
static int sz;
static int memo[][][];
/*
* Thanks http://codeforces.com/blog/entry/53438?#comment-375091
*/
static int rec(int idx , int rem , int hUp , int hDown , int v) {
int mask = (hUp << 2) | (hDown << 1) | v;
if(rem < 0)
return INF;
else if(idx == sz - 1)
return 0;
else if(memo[idx][rem][mask] != -1)
return memo[idx][rem][mask];
else {
int min = INF;
// Create new rectangle
if(compress[idx + 1][1] == 0)
min = Math.min(min , 1 + rec(idx + 1, rem - 1, 1, 0, 0));
if(compress[idx + 1][1] == 1)
min = Math.min(min , 1 + rec(idx + 1, rem - 1, 0, 1, 0));
if(compress[idx + 1][1] == 2)
min = Math.min(min , 2 + rec(idx + 1, rem - 2, 1, 1, 0));
min = Math.min(min , 2 + rec(idx + 1, rem - 1, 0, 0, 1));
// Extend
if(v == 1)
min = Math.min(min , 2 * (compress[idx + 1][0] - compress[idx][0]) +
rec(idx + 1, rem, 0, 0, 1));
else if(hUp == 1 && hDown == 0) {
if(compress[idx + 1][1] == 0)
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0])
+ rec(idx + 1, rem, 1, 0, 0));
else
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0]) + 1
+ rec(idx + 1, rem - 1, 1, 1, 0));
}
else if(hUp == 0 && hDown == 1) {
if(compress[idx + 1][1] == 1)
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0])
+ rec(idx + 1, rem, 0, 1, 0));
else
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0]) + 1
+ rec(idx + 1, rem - 1, 1, 1, 0));
}
else {
if(compress[idx + 1][1] == 0)
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0])
+ rec(idx + 1, rem, 1, 0, 0));
else if(compress[idx + 1][1] == 1)
min = Math.min(min , (compress[idx + 1][0] - compress[idx][0])
+ rec(idx + 1, rem, 0, 1, 0));
min = Math.min(min , 2 * (compress[idx + 1][0] - compress[idx][0])
+ rec(idx + 1, rem, 1, 1, 0));
}
return memo[idx][rem][mask] = min;
}
}
private static void solve2() {
int N = nextInt();
int K = nextInt();
int B = nextInt();
int arr[][] = new int[N][];
for(int i = 0; i < N; i++)
arr[i] = nextIntArray(2);
// long st = System.nanoTime();
Arrays.sort(arr , new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[1] != o2[1])
return o1[1] - o2[1];
else
return o1[0] - o2[0];
}
});
sz = 1;
for(int i = 1; i < N; i++)
sz += arr[i][1] != arr[i - 1][1] ? 1 : 0;
compress = new int[sz][2]; // 0 - up , 1 - down , 2 - both
int ptr = 0;
for(int i = 0; i < N; ) {
compress[ptr][0] = arr[i][1];
if(i + 1 < N && arr[i][1] == arr[i + 1][1]) {
compress[ptr++][1] = 2;
i += 2;
} else {
compress[ptr++][1] = arr[i][0] - 1;
i++;
}
}
memo = new int[sz][K][8];
for(int a[][] : memo)
for(int b[] : a)
Arrays.fill(b, -1);
int min = INF;
if(compress[0][1] == 0)
min = Math.min(min , 1 + rec(0, K - 1, 1, 0, 0));
else if(compress[0][1] == 1)
min = Math.min(min , 1 + rec(0, K - 1, 0, 1, 0));
else
min = Math.min(min , 2 + rec(0, K - 2, 1, 1, 0));
min = Math.min(min , 2 + rec(0, K - 1, 0, 0, 1));
println(min);
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE **********************/
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
st = null;
solve2();
reader.close();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer st;
static String next()
{while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
static int nextInt() {return Integer.parseInt(next());}
static long nextLong() {return Long.parseLong(next());}
static double nextDouble(){return Double.parseDouble(next());}
static char nextChar() {return next().charAt(0);}
static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;}
static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;}
static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
static void print(Object o) { writer.print(o); }
static void println(Object o){ writer.println(o);}
/************************ TEMPLATE ENDS HERE ************************/
}
| |
/*
* Autopsy Forensic Browser
*
* Copyright 2020 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obt ain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.communications.relationships;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JPanel;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoAccount;
import org.sleuthkit.autopsy.centralrepository.datamodel.CentralRepoException;
import org.sleuthkit.autopsy.centralrepository.datamodel.Persona;
import org.sleuthkit.autopsy.centralrepository.datamodel.PersonaAccount;
import org.sleuthkit.autopsy.centralrepository.persona.PersonaDetailsDialog;
import org.sleuthkit.autopsy.centralrepository.persona.PersonaDetailsDialogCallback;
import org.sleuthkit.autopsy.centralrepository.persona.PersonaDetailsMode;
import org.sleuthkit.autopsy.centralrepository.persona.PersonaDetailsPanel;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.datamodel.Account;
/**
* Panel to show the Personas for a given account. That is apart SummaryViewer.
*/
public final class SummaryPersonaPane extends javax.swing.JPanel {
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(SummaryPersonaPane.class.getName());
private final Map<Component, Persona> personaMap;
private final ViewButtonHandler viewButtonHandler = new ViewButtonHandler();
private CentralRepoAccount currentCRAccount = null;
private Account currentAccount = null;
/**
* Creates new form SummaryPersonaPane
*/
SummaryPersonaPane() {
initComponents();
personaScrollPane.setViewportView(new JPanel());
personaMap = new HashMap<>();
}
/**
* Clear the persona list.
*/
void clearList() {
personaScrollPane.setViewportView(new JPanel());
personaMap.clear();
}
/**
* Show the message panel.
*/
void showMessagePanel() {
CardLayout layout = (CardLayout) getLayout();
layout.show(this, "message");
}
/**
* Set the message that appears when the message panel is visible.
*
* @param message Message to show.
*/
void setMessage(String message) {
messageLabel.setText(message);
}
/**
* Update the list of personas to the new given list.
*
* @param personaList New list of personas to show
*/
void updatePersonaList(Account account, CentralRepoAccount crAccount, List<Persona> personaList) {
JPanel panel = new JPanel();
currentCRAccount = crAccount;
currentAccount = account;
CardLayout layout = (CardLayout) getLayout();
if (personaList.isEmpty()) {
layout.show(this, "create");
} else {
panel.setLayout(new GridLayout(personaList.size() + 1, 1));
int maxWidth = 0;
List<PersonaPanel> panelList = new ArrayList<>();
for (Persona persona : personaList) {
PersonaPanel personaPanel = new PersonaPanel(persona);
JButton viewButton = personaPanel.getViewButton();
panel.add(personaPanel);
personaMap.put(viewButton, persona);
viewButton.addActionListener(viewButtonHandler);
panelList.add(personaPanel);
maxWidth = Math.max(personaPanel.getPersonaLabelPreferedWidth(), maxWidth);
}
//Set the preferred width of the labeles to the buttons line up.
if (panelList.size() > 1) {
for (PersonaPanel ppanel : panelList) {
ppanel.setPersonalLabelPreferredWidth(maxWidth);
}
}
panel.add(Box.createVerticalGlue());
personaScrollPane.setViewportView(panel);
layout.show(this, "persona");
}
}
/**
* ActionListener to handle the launching of the view dialog for the given
* persona.
*/
final private class ViewButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Persona persona = personaMap.get((Component) e.getSource());
new PersonaDetailsDialog(SummaryPersonaPane.this,
PersonaDetailsMode.VIEW, persona, new PersonaViewCallbackImpl());
}
}
/**
* Callback method for the view mode of the PersonaDetailsDialog
*/
private final class PersonaViewCallbackImpl implements PersonaDetailsDialogCallback {
@Override
public void callback(Persona persona) {
// nothing to do
}
}
/**
* Callback class to handle the creation of a new person for the given
* account
*/
private final class PersonaCreateCallbackImpl implements PersonaDetailsDialogCallback {
@Override
public void callback(Persona persona) {
if (persona != null) {
List<Persona> list = new ArrayList<>();
list.add(persona);
CentralRepoAccount crAccount = null;
Collection<PersonaAccount> personaAccounts = null;
try {
personaAccounts = persona.getPersonaAccounts();
} catch (CentralRepoException ex) {
logger.log(Level.WARNING, String.format("Failed to get cr account from person %s (%d)", persona.getName(), persona.getId()), ex);
}
if (personaAccounts != null) {
Iterator<PersonaAccount> iterator = personaAccounts.iterator();
if (iterator.hasNext()) {
crAccount = iterator.next().getAccount();
}
}
updatePersonaList(currentAccount, crAccount, list);
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
personaScrollPane = new javax.swing.JScrollPane();
messagePane = new javax.swing.JPanel();
messageLabel = new javax.swing.JLabel();
createPersonaPanel = new javax.swing.JPanel();
noPersonaLabel = new javax.swing.JLabel();
createButton = new javax.swing.JButton();
setLayout(new java.awt.CardLayout());
personaScrollPane.setBorder(null);
add(personaScrollPane, "persona");
messagePane.setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(messageLabel, org.openide.util.NbBundle.getMessage(SummaryPersonaPane.class, "SummaryPersonaPane.messageLabel.text")); // NOI18N
messageLabel.setEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weighty = 1.0;
messagePane.add(messageLabel, gridBagConstraints);
add(messagePane, "message");
createPersonaPanel.setPreferredSize(new java.awt.Dimension(200, 100));
createPersonaPanel.setLayout(new java.awt.GridBagLayout());
org.openide.awt.Mnemonics.setLocalizedText(noPersonaLabel, org.openide.util.NbBundle.getMessage(SummaryPersonaPane.class, "SummaryPersonaPane.noPersonaLabel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 5, 0, 0);
createPersonaPanel.add(noPersonaLabel, gridBagConstraints);
org.openide.awt.Mnemonics.setLocalizedText(createButton, org.openide.util.NbBundle.getMessage(SummaryPersonaPane.class, "SummaryPersonaPane.createButton.text")); // NOI18N
createButton.setMargin(new java.awt.Insets(0, 5, 0, 5));
createButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 0);
createPersonaPanel.add(createButton, gridBagConstraints);
add(createPersonaPanel, "create");
}// </editor-fold>//GEN-END:initComponents
@NbBundle.Messages({
"# {0} - accountIdentifer",
"SummaryPersonaPane_not_account_in_cr=Unable to find an account with identifier {0} in the Central Repository."
})
private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
PersonaDetailsDialog createPersonaDialog = new PersonaDetailsDialog(SummaryPersonaPane.this,
PersonaDetailsMode.CREATE, null, new PersonaCreateCallbackImpl(), false);
// Pre populate the persona name and accounts if we have them.
PersonaDetailsPanel personaPanel = createPersonaDialog.getDetailsPanel();
if (currentCRAccount != null) {
personaPanel.addAccount(currentCRAccount, "", Persona.Confidence.HIGH);
} else {
createPersonaDialog.setStartupPopupMessage(Bundle.SummaryPersonaPane_not_account_in_cr(currentAccount.getTypeSpecificID()));
}
personaPanel.setPersonaName(currentAccount.getTypeSpecificID());
// display the dialog now
createPersonaDialog.display();
}//GEN-LAST:event_createButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton createButton;
private javax.swing.JPanel createPersonaPanel;
private javax.swing.JLabel messageLabel;
private javax.swing.JPanel messagePane;
private javax.swing.JLabel noPersonaLabel;
private javax.swing.JScrollPane personaScrollPane;
// End of variables declaration//GEN-END:variables
}
| |
/*
* TopStack (c) Copyright 2012-2013 Transcend Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.msi.tough.model.monitor;
import java.math.BigInteger;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.Session;
import com.msi.tough.utils.Constants;
@Entity
@Table(name = "alarm")
public class AlarmBean implements Constants {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// alarm enabled
private Boolean enabled;
// action names
private String actionNames;
private String description;
// alarm name
private String alarmName;
// comparison operator
// GreaterThanOrEqualToThreshold, GreaterThanThreshold,
// LessThanThreshold and LessThanOrEqualToThreshold
private String comparator;
// dimensions
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "alarm_dimension", joinColumns = { @JoinColumn(name = "alarm_id") }, inverseJoinColumns = { @JoinColumn(name = "dimension_id") })
private Set<DimensionBean> dimensions;
private BigInteger evaluationPeriods;
// insufficient data actions
private String insufficientDataActions;
// metric name
private String metricName;
// namespace
private String namespace;
// ok Actions
private String okActions;
// period
private BigInteger period;
// statistic
private String statistic;
// threshold
private double threshold;
// unit
private String unit;
// alarm state : Possible values are OK, ALARM, or INSUFFICIENT_DATA
private String state;
// reason for the alarm state being set
private String stateReason;
// reason for the alarm state to be set in JSON
private String stateReasonData;
// // Same as Amazon Resource Name
// private String resourceName;
// account Id of the user who set the alarm.
private long userId;
private Date lastUpdate;
private Date periodStart;
public String getActionNames() {
return actionNames;
}
public String getAlarmName() {
return alarmName;
}
public String getComparator() {
return comparator;
}
public String getDescription() {
return description;
}
public Set<DimensionBean> getDimensions() {
return dimensions;
}
public Boolean getEnabled() {
return enabled;
}
public BigInteger getEvaluationPeriods() {
return evaluationPeriods;
}
public Long getId() {
return id;
}
public String getInsufficientDataActions() {
return insufficientDataActions;
}
public Date getLastUpdate() {
return lastUpdate;
}
public String getMetricName() {
return metricName;
}
public String getNamespace() {
return namespace;
}
public String getOkActions() {
return okActions;
}
public BigInteger getPeriod() {
return period;
}
public Date getPeriodStart() {
return periodStart;
}
public String getState() {
return state;
}
public String getStateReason() {
return stateReason;
}
public String getStateReasonData() {
return stateReasonData;
}
public String getStatistic() {
return statistic;
}
public double getThreshold() {
return threshold;
}
public String getUnit() {
return unit;
}
public long getUserId() {
return userId;
}
public boolean isEnabled() {
return enabled;
}
public void save(final Session session) {
session.saveOrUpdate(this);
}
public void setActionNames(final String actionNames) {
this.actionNames = actionNames;
}
public void setAlarmName(final String alarmName) {
this.alarmName = alarmName;
}
public void setComparator(final String comparator) {
this.comparator = comparator;
}
public void setDescription(final String description) {
this.description = description;
}
public void setDimensions(final Set<DimensionBean> dimensions) {
this.dimensions = dimensions;
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
public void setEnabled(final Boolean enabled) {
this.enabled = enabled;
}
public void setEvaluationPeriods(final BigInteger evaluationPeriods) {
this.evaluationPeriods = evaluationPeriods;
}
public void setId(final Long id) {
this.id = id;
}
public void setInsufficientDataActions(final String insufficientDataActions) {
this.insufficientDataActions = insufficientDataActions;
}
public void setLastUpdate(final Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public void setMetricName(final String metricName) {
this.metricName = metricName;
}
public void setNamespace(final String namespace) {
this.namespace = namespace;
}
public void setOkActions(final String okActions) {
this.okActions = okActions;
}
public void setPeriod(final BigInteger period) {
this.period = period;
}
public void setPeriodStart(final Date periodStart) {
this.periodStart = periodStart;
}
public void setState(final String state) {
this.state = state;
}
public void setStateReason(final String stateReason) {
this.stateReason = stateReason;
}
public void setStateReasonData(final String stateReasonData) {
this.stateReasonData = stateReasonData;
}
public void setStatistic(final String statistic) {
this.statistic = statistic;
}
public void setThreshold(final double threshold) {
this.threshold = threshold;
}
public void setUnit(final String unit) {
this.unit = unit;
}
public void setUserId(final long userId) {
this.userId = userId;
}
}
| |
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mutabilitydetector.asm.tree.analysis;
import org.mutabilitydetector.asm.typehierarchy.TypeHierarchy;
import org.mutabilitydetector.asm.typehierarchy.TypeHierarchyReader;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.SimpleVerifier;
import java.util.List;
/**
* An extended {@link SimpleVerifier} that guarantees not to load classes.
*
* Delegates to an underlying {@link TypeHierarchyReader} to perform the
* necessary visiting of class files to find the information required for
* verification.
*
* The default implementation of {@link TypeHierarchyReader} will attempt to
* read classes using a {@link ClassReader} which reads class files using
* {@link ClassLoader#getSystemResourceAsStream(String)}. Unlike with native
* classloading, there is no caching used in this verifier, which will almost
* certainly degrade performance. To maintain performance, supply an alternative
* {@link TypeHierarchyReader} which can using a caching strategy best suited to
* your environment.
*
* @see ClassReader#ClassReader(String)
* @see SimpleVerifier
* @see Type
* @see TypeHierarchyReader
*
* @author Graham Allan
*
*/
public class NonClassloadingSimpleVerifier extends SimpleVerifier {
private final Type currentClass;
private final Type currentSuperClass;
private final List<Type> currentClassInterfaces;
private final boolean isInterface;
/**
* Used to obtain hierarchy information used in verification.
*/
protected final TypeHierarchyReader typeHierarchyReader;
/**
* Default constructor which chooses a naive {@link TypeHierarchyReader}.
*/
public NonClassloadingSimpleVerifier() {
this(new TypeHierarchyReader());
}
public NonClassloadingSimpleVerifier(final Type currentClass, final Type currentSuperClass, boolean isInterface) {
this(currentClass, currentSuperClass, null, isInterface, new TypeHierarchyReader());
}
/**
* Constructor which uses the given {@link TypeHierarchyReader} to obtain
* hierarchy information for given {@link Type}s.
*/
public NonClassloadingSimpleVerifier(TypeHierarchyReader reader) {
this(null, null, null, false, reader);
}
public NonClassloadingSimpleVerifier(Type currentClass,
Type currentSuperClass,
List<Type> currentClassInterfaces,
boolean isInterface,
TypeHierarchyReader reader) {
super(ASM7, currentClass, currentSuperClass, currentClassInterfaces, isInterface);
this.currentClass = currentClass;
this.currentSuperClass = currentSuperClass;
this.currentClassInterfaces = currentClassInterfaces;
this.isInterface = isInterface;
this.typeHierarchyReader = reader;
}
/**
* Unconditionally throws an {@link Error}. This method should never be
* called.
*/
@Override
protected Class< ? > getClass(Type t) {
throw new Error("Programming error: this verifier should "
+ "not be attempting to load classes.");
}
/**
* Immediately delegates and returns the result of the equivalent method of
* the underlying {@link TypeHierarchyReader}.
*
* @see TypeHierarchyReader#isInterface(Type)
*/
@Override
protected boolean isInterface(final Type t) {
if (currentClass != null && t.equals(currentClass)) {
return isInterface;
}
return typeHierarchyReader.isInterface(t);
}
/**
* Immediately delegates and returns the result of the equivalent method of
* the underlying {@link TypeHierarchyReader}.
*
* @see TypeHierarchyReader#getSuperClass(Type)
*/
@Override
protected Type getSuperClass(final Type t) {
if (currentClass != null && t.equals(currentClass)) {
return currentSuperClass;
}
return typeHierarchyReader.getSuperClass(t);
}
/**
* Immediately delegates and returns the result of the equivalent method of
* the underlying {@link TypeHierarchyReader}.
*
* @see TypeHierarchyReader#isAssignableFrom(Type, Type)
*/
@Override
public boolean isAssignableFrom(Type toType, Type fromType) {
if (toType.equals(fromType)) {
return true;
}
if (currentClass != null && toType.equals(currentClass)) {
if (getSuperClass(fromType) == null) {
return false;
} else {
if (isInterface) {
return fromType.getSort() == Type.OBJECT
|| fromType.getSort() == Type.ARRAY;
}
return isAssignableFrom(toType, getSuperClass(fromType));
}
}
if (currentClass != null && fromType.equals(currentClass)) {
if (isAssignableFrom(toType, currentSuperClass)) {
return true;
}
if (currentClassInterfaces != null) {
for (Type currentClassInterface : currentClassInterfaces) {
if (isAssignableFrom(toType, currentClassInterface)) {
return true;
}
}
}
return false;
}
TypeHierarchy tc = typeHierarchyReader.hierarchyOf(toType);
return tc.isAssignableFrom(fromType, typeHierarchyReader);
}
@Override
protected boolean isSubTypeOf(final BasicValue value, final BasicValue expected) {
Type expectedType = expected.getType();
Type type = value.getType();
switch (expectedType.getSort()) {
case Type.INT:
case Type.FLOAT:
case Type.LONG:
case Type.DOUBLE:
return type.equals(expectedType);
case Type.ARRAY:
case Type.OBJECT:
if (type.equals(NULL_TYPE)) {
return true;
} else if (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY) {
if (isAssignableFrom(expectedType, type)) {
return true;
} else if (isInterface(expectedType)) {
// The merge of class or interface types can only yield class types (because it is not
// possible in general to find an unambiguous common super interface, due to multiple
// inheritance). Because of this limitation, we need to relax the subtyping check here
// if 'value' is an interface.
return isAssignableFrom(TypeHierarchy.JAVA_LANG_OBJECT.type(), type);
} else {
return false;
}
} else {
return false;
}
default:
throw new AssertionError();
}
}
}
| |
/*******************************************************************************
* Copyright Duke Comprehensive Cancer Center and SemanticBits
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/c3pr/LICENSE.txt for details.
******************************************************************************/
package edu.duke.cabig.c3pr.webservice.converters;
import java.util.Arrays;
import java.util.List;
import org.springframework.test.AssertThrows;
import com.semanticbits.querybuilder.AdvancedSearchCriteriaParameter;
import edu.duke.cabig.c3pr.domain.Identifier;
import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier;
import edu.duke.cabig.c3pr.domain.StudySubject;
import edu.duke.cabig.c3pr.domain.StudySubjectDemographics;
import edu.duke.cabig.c3pr.domain.StudySubjectRegistryStatus;
import edu.duke.cabig.c3pr.exception.ConversionException;
import edu.duke.cabig.c3pr.webservice.common.AdvanceSearchCriterionParameter;
import edu.duke.cabig.c3pr.webservice.common.BiologicEntityIdentifier;
import edu.duke.cabig.c3pr.webservice.common.DocumentIdentifier;
import edu.duke.cabig.c3pr.webservice.common.Organization;
import edu.duke.cabig.c3pr.webservice.common.PerformedStudySubjectMilestone;
import edu.duke.cabig.c3pr.webservice.common.Person;
import edu.duke.cabig.c3pr.webservice.common.StudySubjectConsentVersion;
import edu.duke.cabig.c3pr.webservice.common.Subject;
import edu.duke.cabig.c3pr.webservice.common.SubjectIdentifier;
import edu.duke.cabig.c3pr.webservice.helpers.SubjectRegistryRelatedTestCase;
public class SubjectRegistryJAXBToDomainObjectConverterImplTest extends SubjectRegistryRelatedTestCase {
/**
* Test method for
* {@link edu.duke.cabig.c3pr.webservice.subjectmanagement.converters.JAXBToDomainObjectConverterImpl#convert(edu.duke.cabig.c3pr.webservice.subjectmanagement.BiologicEntityIdentifier)}
* .
*/
public void testConvertBiologicEntityIdentifier() {
BiologicEntityIdentifier bioId = createBioEntityId();
Identifier oaId = converter.convertBiologicIdentifiers(Arrays.asList(new BiologicEntityIdentifier[]{bioId})).get(0);
assertOrgAssId((OrganizationAssignedIdentifier)oaId);
final BiologicEntityIdentifier badBioId = createBioEntityId();
badBioId.setIdentifier(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertBiologicIdentifiers(Arrays.asList(new BiologicEntityIdentifier[]{badBioId}));
}
}.runTest();
final BiologicEntityIdentifier badBioId2 = createBioEntityId();
badBioId2.setTypeCode(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertBiologicIdentifiers(Arrays.asList(new BiologicEntityIdentifier[]{badBioId2}));
}
}.runTest();
final BiologicEntityIdentifier badBioId3 = createBioEntityId();
badBioId3.setAssigningOrganization(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertBiologicIdentifiers(Arrays.asList(new BiologicEntityIdentifier[]{badBioId3}));
}
}.runTest();
}
/**
* Test method for
* {@link edu.duke.cabig.c3pr.webservice.subjectmanagement.converters.JAXBToDomainObjectConverterImpl#convert(edu.duke.cabig.c3pr.webservice.subjectmanagement.BiologicEntityIdentifier)}
* .
*/
public void testConvertDocumentIdentifier() {
DocumentIdentifier docId = createDocumentId();
Identifier oaId = converter.convert(Arrays.asList(new DocumentIdentifier[]{docId})).get(0);
assertOrgAssIdDoc((OrganizationAssignedIdentifier)oaId);
final DocumentIdentifier badBioId = createDocumentId();
badBioId.setIdentifier(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convert(Arrays.asList(new DocumentIdentifier[]{badBioId}));
}
}.runTest();
final DocumentIdentifier badBioId2 = createDocumentId();
badBioId2.setTypeCode(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convert(Arrays.asList(new DocumentIdentifier[]{badBioId2}));
}
}.runTest();
final DocumentIdentifier badBioId3 = createDocumentId();
badBioId3.setAssigningOrganization(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convert(Arrays.asList(new DocumentIdentifier[]{badBioId3}));
}
}.runTest();
}
public void testConvertHealthcareSitePrimaryIdentifier(){
Organization organization = createOrganization();
assertEquals(TEST_ORG_ID , converter.convertHealthcareSitePrimaryIdentifier(organization));
final Organization badOrg1 = createOrganization();
badOrg1.getOrganizationIdentifier().clear();
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertHealthcareSitePrimaryIdentifier(badOrg1);
}
}.runTest();
final Organization badOrg2 = createOrganization();
badOrg2.getOrganizationIdentifier().get(0).setIdentifier(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertHealthcareSitePrimaryIdentifier(badOrg2);
}
}.runTest();
final Organization badOrg3 = createOrganization();
badOrg3.getOrganizationIdentifier().get(0).getIdentifier().setExtension("");
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertHealthcareSitePrimaryIdentifier(badOrg3);
}
}.runTest();
}
public void testConvertSubjectConsent(){
List<StudySubjectConsentVersion> subjectConsents = null;
subjectConsents = getSubjectConsents();
assertSubjectConsent(converter.convertSubjectConsent(subjectConsents));
final List<StudySubjectConsentVersion> bad1 = getSubjectConsents();
bad1.get(0).getSubjectConsentAnswer().get(0).getConsentQuestion().getOfficialTitle().setValue("");
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad1);
}
}.runTest();
final List<StudySubjectConsentVersion> bad2 = getSubjectConsents();
bad2.get(0).getSubjectConsentAnswer().get(0).getConsentQuestion().setOfficialTitle(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad2);
}
}.runTest();
final List<StudySubjectConsentVersion> bad3 = getSubjectConsents();
bad3.get(0).getSubjectConsentAnswer().get(0).setConsentQuestion(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad3);
}
}.runTest();
final List<StudySubjectConsentVersion> bad4 = getSubjectConsents();
bad4.get(0).getSubjectConsentAnswer().get(0).getMissedIndicator().setValue(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad4);
}
}.runTest();
final List<StudySubjectConsentVersion> bad5 = getSubjectConsents();
bad5.get(0).getSubjectConsentAnswer().get(0).setMissedIndicator(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad5);
}
}.runTest();
final List<StudySubjectConsentVersion> bad6 = getSubjectConsents();
bad6.get(0).getConsent().getOfficialTitle().setValue("");
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad6);
}
}.runTest();
final List<StudySubjectConsentVersion> bad7 = getSubjectConsents();
bad7.get(0).getConsent().setOfficialTitle(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad7);
}
}.runTest();
final List<StudySubjectConsentVersion> bad8 = getSubjectConsents();
bad8.get(0).setConsent(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectConsent(bad8);
}
}.runTest();
}
/**
* Test method for
* {@link edu.duke.cabig.c3pr.webservice.subjectmanagement.converters.JAXBToDomainObjectConverterImpl#convert(edu.duke.cabig.c3pr.webservice.subjectmanagement.BiologicEntityIdentifier)}
* .
*/
public void testConvertSubjectIdentifier() {
SubjectIdentifier docId = createSubjectId();
Identifier oaId = converter.convertSubjectIdentifiers(Arrays.asList(new SubjectIdentifier[]{docId})).get(0);
assertOrgAssIdSub((OrganizationAssignedIdentifier)oaId);
final SubjectIdentifier badSubId = createSubjectId();
badSubId.setIdentifier(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectIdentifiers(Arrays.asList(new SubjectIdentifier[]{badSubId}));
}
}.runTest();
final SubjectIdentifier badSubId2 = createSubjectId();
badSubId2.setTypeCode(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectIdentifiers(Arrays.asList(new SubjectIdentifier[]{badSubId2}));
}
}.runTest();
final SubjectIdentifier badSubId3 = createSubjectId();
badSubId3.setAssigningOrganization(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertSubjectIdentifiers(Arrays.asList(new SubjectIdentifier[]{badSubId3}));
}
}.runTest();
}
/**
* Test for
* {@link edu.duke.cabig.c3pr.webservice.converters.JAXBToDomainObjectConverterImpl#convert(AdvanceSearchCriterionParameter)}
*/
public void testConvertAdvanceSearchCriterionParameter() {
AdvanceSearchCriterionParameter param = createAdvaceSearchParam();
AdvancedSearchCriteriaParameter convParam = converter.convert(param);
assertEquals(TEST_ATTRIBUTE_NAME, convParam.getAttributeName());
assertEquals(TEST_OBJ_CTX_NAME, convParam.getContextObjectName());
assertEquals(TEST_OBJ_NAME, convParam.getObjectName());
assertEquals(TEST_PREDICATE, convParam.getPredicate());
assertEquals(Arrays.asList(new String[] { TEST_VALUE1, TEST_VALUE2 }),
convParam.getValues());
}
public void testConvertRegistryStatus(){
PerformedStudySubjectMilestone status = createStatus();
StudySubjectRegistryStatus actual = converter.convertRegistryStatus(status);
assertEquals(TEST_REGISTRYSTATUS_CODE1, actual.getPermissibleStudySubjectRegistryStatus().getRegistryStatus().getCode());
assertEquals(parseISODate(TEST_REGISTRYSTATUS_DATE1), actual.getEffectiveDate());
assertEquals(TEST_REGISTRYSTATUS_REASON11 , actual.getReasons().get(0).getCode());
assertEquals(TEST_REGISTRYSTATUS_REASON12 , actual.getReasons().get(1).getCode());
final PerformedStudySubjectMilestone bad = createStatus();
bad.setStatusDate(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertRegistryStatus(bad);
}
}.runTest();
bad.getStatusCode().setCode("");
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertRegistryStatus(bad);
}
}.runTest();
bad.setStatusCode(null);
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertRegistryStatus(bad);
}
}.runTest();
}
public void testConvertSubjectDemographics(){
StudySubjectDemographics studySubjectDemographics = createSubjectDemographics();
Person actual = converter.convertSubjectDemographics(studySubjectDemographics);
assertPerson(actual);
}
public void testConvertToSubjectDemographics(){
Subject subject = new Subject();
Person person = createPerson();
subject.setEntity(person);
final StudySubjectDemographics actual = new StudySubjectDemographics();
converter.convertToSubjectDemographics(actual, subject);
assertSubjectDemographics(actual);
// test exceptions
final Person badDataPerson1 = createPerson();
final Subject badDataSubj1 = new Subject();
badDataSubj1.setEntity(badDataPerson1);
badDataPerson1.setBirthDate(iso.TSDateTime(BAD_ISO_DATE));
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertToSubjectDemographics(actual, badDataSubj1);
}
}.runTest();
final Person badDataPerson2 = createPerson();
final Subject badDataSubj2 = new Subject();
badDataSubj2.setEntity(badDataPerson2);
badDataPerson2.setRaceCode(iso.DSETCD(iso.CD(RACE_WHITE), iso.CD(
BAD_RACE_CODE)));
new AssertThrows(ConversionException.class) {
public void test() {
converter.convertToSubjectDemographics(actual, badDataSubj2);
}
}.runTest();
}
public void testConvert(){
StudySubject studySubject = createStudySubjectDomainObject();
edu.duke.cabig.c3pr.webservice.subjectregistry.StudySubject actual = converter.convert(studySubject);
assertPerson((Person)actual.getEntity());
assertEquals(TEST_PAYMENT_METHOD, actual.getPaymentMethodCode().getCode());
assertEquals(TEST_DATA_ENTRY_STATUS, actual.getStatusCode().getCode());
assertEquals(TEST_STUDYSUBJECT_ID, actual.getSubjectIdentifier().get(0).getIdentifier().getExtension());
assertEquals(TEST_CONSENT_DELIVERY_DATE1, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getConsentDeliveryDate().getValue());
assertEquals(TEST_CONSENT_SIGNED_DATE1, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getInformedConsentDate().getValue());
assertEquals(TEST_CONSENT_PRESENTER1, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getConsentPresenter().getValue());
assertEquals(TEST_CONSENTING_METHOD1, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getConsentingMethod().getCode());
assertEquals(TEST_CONSENT_ANS11, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getSubjectConsentAnswer().get(0).getMissedIndicator().isValue());
assertEquals(TEST_CONSENT_QUES11, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getSubjectConsentAnswer().get(0).getConsentQuestion().getOfficialTitle().getValue());
assertEquals(TEST_CONSENT_ANS12, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getSubjectConsentAnswer().get(1).getMissedIndicator().isValue());
assertEquals(TEST_CONSENT_QUES12, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(0).getSubjectConsentAnswer().get(1).getConsentQuestion().getOfficialTitle().getValue());
assertEquals(TEST_CONSENT_DELIVERY_DATE2, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getConsentDeliveryDate().getValue());
assertEquals(TEST_CONSENT_SIGNED_DATE2, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getInformedConsentDate().getValue());
assertEquals(TEST_CONSENT_PRESENTER2, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getConsentPresenter().getValue());
assertEquals(TEST_CONSENTING_METHOD2, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getConsentingMethod().getCode());
assertEquals(TEST_CONSENT_ANS21, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getSubjectConsentAnswer().get(0).getMissedIndicator().isValue());
assertEquals(TEST_CONSENT_QUES21, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getSubjectConsentAnswer().get(0).getConsentQuestion().getOfficialTitle().getValue());
assertEquals(TEST_CONSENT_ANS22, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getSubjectConsentAnswer().get(1).getMissedIndicator().isValue());
assertEquals(TEST_CONSENT_QUES22, actual.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().get(1).getSubjectConsentAnswer().get(1).getConsentQuestion().getOfficialTitle().getValue());
assertEquals(TEST_STUDY_ID, actual.getStudySubjectProtocolVersion().getStudySiteProtocolVersion().getStudyProtocolVersion().getStudyProtocolDocument().getDocument().getDocumentIdentifier().get(0).getIdentifier().getExtension());
assertEquals(TEST_SHORTTITLE, actual.getStudySubjectProtocolVersion().getStudySiteProtocolVersion().getStudyProtocolVersion().getStudyProtocolDocument().getOfficialTitle().getValue());
assertEquals(TEST_LONGTITLE, actual.getStudySubjectProtocolVersion().getStudySiteProtocolVersion().getStudyProtocolVersion().getStudyProtocolDocument().getPublicTitle().getValue());
assertEquals(TEST_DESC, actual.getStudySubjectProtocolVersion().getStudySiteProtocolVersion().getStudyProtocolVersion().getStudyProtocolDocument().getPublicDescription().getValue());
assertEquals(TEST_HEALTHCARESITE_ID, actual.getStudySubjectProtocolVersion().getStudySiteProtocolVersion().getStudySite().getOrganization().getOrganizationIdentifier().get(0).getIdentifier().getExtension());
assertEquals(TEST_REGISTRYSTATUS_CODE1, actual.getStudySubjectStatus().get(0).getStatusCode().getCode());
assertEquals(TEST_REGISTRYSTATUS_DATE1, actual.getStudySubjectStatus().get(0).getStatusDate().getValue());
assertEquals(TEST_REGISTRYSTATUS_REASON11, actual.getStudySubjectStatus().get(0).getReasonCode().getItem().get(0).getCode());
assertEquals(TEST_REGISTRYSTATUS_REASON12, actual.getStudySubjectStatus().get(0).getReasonCode().getItem().get(1).getCode());
assertEquals(TEST_REGISTRYSTATUS_CODE2, actual.getStudySubjectStatus().get(1).getStatusCode().getCode());
assertEquals(TEST_REGISTRYSTATUS_DATE2, actual.getStudySubjectStatus().get(1).getStatusDate().getValue());
assertEquals(TEST_REGISTRYSTATUS_REASON21, actual.getStudySubjectStatus().get(1).getReasonCode().getItem().get(0).getCode());
assertEquals(TEST_REGISTRYSTATUS_REASON22, actual.getStudySubjectStatus().get(1).getReasonCode().getItem().get(1).getCode());
}
}
| |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.trace.v1.stub;
import static com.google.cloud.trace.v1.PagedResponseWrappers.ListTracesPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.devtools.cloudtrace.v1.GetTraceRequest;
import com.google.devtools.cloudtrace.v1.ListTracesRequest;
import com.google.devtools.cloudtrace.v1.ListTracesResponse;
import com.google.devtools.cloudtrace.v1.PatchTracesRequest;
import com.google.devtools.cloudtrace.v1.Trace;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
* Settings class to configure an instance of {@link TraceServiceStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (cloudtrace.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object. For
* example, to set the total timeout of patchTraces to 30 seconds:
*
* <pre>
* <code>
* TraceServiceStubSettings.Builder traceServiceSettingsBuilder =
* TraceServiceStubSettings.newBuilder();
* traceServiceSettingsBuilder.patchTracesSettings().getRetrySettingsBuilder()
* .setTotalTimeout(Duration.ofSeconds(30));
* TraceServiceStubSettings traceServiceSettings = traceServiceSettingsBuilder.build();
* </code>
* </pre>
*/
@Generated("by GAPIC v0.0.5")
@BetaApi
public class TraceServiceStubSettings extends StubSettings<TraceServiceStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/cloud-platform")
.add("https://www.googleapis.com/auth/trace.append")
.add("https://www.googleapis.com/auth/trace.readonly")
.build();
private final UnaryCallSettings<PatchTracesRequest, Empty> patchTracesSettings;
private final UnaryCallSettings<GetTraceRequest, Trace> getTraceSettings;
private final PagedCallSettings<ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>
listTracesSettings;
/** Returns the object with the settings used for calls to patchTraces. */
public UnaryCallSettings<PatchTracesRequest, Empty> patchTracesSettings() {
return patchTracesSettings;
}
/** Returns the object with the settings used for calls to getTrace. */
public UnaryCallSettings<GetTraceRequest, Trace> getTraceSettings() {
return getTraceSettings;
}
/** Returns the object with the settings used for calls to listTraces. */
public PagedCallSettings<ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>
listTracesSettings() {
return listTracesSettings;
}
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public TraceServiceStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcTraceServiceStub.create(this);
} else {
throw new UnsupportedOperationException(
"Transport not supported: " + getTransportChannelProvider().getTransportName());
}
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "cloudtrace.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken(
"gapic", GaxProperties.getLibraryVersion(TraceServiceStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected TraceServiceStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
patchTracesSettings = settingsBuilder.patchTracesSettings().build();
getTraceSettings = settingsBuilder.getTraceSettings().build();
listTracesSettings = settingsBuilder.listTracesSettings().build();
}
private static final PagedListDescriptor<ListTracesRequest, ListTracesResponse, Trace>
LIST_TRACES_PAGE_STR_DESC =
new PagedListDescriptor<ListTracesRequest, ListTracesResponse, Trace>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListTracesRequest injectToken(ListTracesRequest payload, String token) {
return ListTracesRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListTracesRequest injectPageSize(ListTracesRequest payload, int pageSize) {
throw new UnsupportedOperationException(
"page size is not supported by this API method");
}
@Override
public Integer extractPageSize(ListTracesRequest payload) {
throw new UnsupportedOperationException(
"page size is not supported by this API method");
}
@Override
public String extractNextToken(ListTracesResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<Trace> extractResources(ListTracesResponse payload) {
return payload.getTracesList();
}
};
private static final PagedListResponseFactory<
ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>
LIST_TRACES_PAGE_STR_FACT =
new PagedListResponseFactory<
ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>() {
@Override
public ApiFuture<ListTracesPagedResponse> getFuturePagedResponse(
UnaryCallable<ListTracesRequest, ListTracesResponse> callable,
ListTracesRequest request,
ApiCallContext context,
ApiFuture<ListTracesResponse> futureResponse) {
PageContext<ListTracesRequest, ListTracesResponse, Trace> pageContext =
PageContext.create(callable, LIST_TRACES_PAGE_STR_DESC, request, context);
return ListTracesPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Builder for TraceServiceStubSettings. */
public static class Builder extends StubSettings.Builder<TraceServiceStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final UnaryCallSettings.Builder<PatchTracesRequest, Empty> patchTracesSettings;
private final UnaryCallSettings.Builder<GetTraceRequest, Trace> getTraceSettings;
private final PagedCallSettings.Builder<
ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>
listTracesSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"idempotent",
ImmutableSet.copyOf(
Lists.<StatusCode.Code>newArrayList(
StatusCode.Code.DEADLINE_EXCEEDED, StatusCode.Code.UNAVAILABLE)));
definitions.put("non_idempotent", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.2)
.setMaxRetryDelay(Duration.ofMillis(1000L))
.setInitialRpcTimeout(Duration.ofMillis(20000L))
.setRpcTimeoutMultiplier(1.5)
.setMaxRpcTimeout(Duration.ofMillis(30000L))
.setTotalTimeout(Duration.ofMillis(45000L))
.build();
definitions.put("default", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this((ClientContext) null);
}
protected Builder(ClientContext clientContext) {
super(clientContext);
patchTracesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getTraceSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
listTracesSettings = PagedCallSettings.newBuilder(LIST_TRACES_PAGE_STR_FACT);
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
patchTracesSettings, getTraceSettings, listTracesSettings);
initDefaults(this);
}
private static Builder createDefault() {
Builder builder = new Builder((ClientContext) null);
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setEndpoint(getDefaultEndpoint());
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.patchTracesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));
builder
.getTraceSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));
builder
.listTracesSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("default"));
return builder;
}
protected Builder(TraceServiceStubSettings settings) {
super(settings);
patchTracesSettings = settings.patchTracesSettings.toBuilder();
getTraceSettings = settings.getTraceSettings.toBuilder();
listTracesSettings = settings.listTracesSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
patchTracesSettings, getTraceSettings, listTracesSettings);
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to patchTraces. */
public UnaryCallSettings.Builder<PatchTracesRequest, Empty> patchTracesSettings() {
return patchTracesSettings;
}
/** Returns the builder for the settings used for calls to getTrace. */
public UnaryCallSettings.Builder<GetTraceRequest, Trace> getTraceSettings() {
return getTraceSettings;
}
/** Returns the builder for the settings used for calls to listTraces. */
public PagedCallSettings.Builder<ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>
listTracesSettings() {
return listTracesSettings;
}
@Override
public TraceServiceStubSettings build() throws IOException {
return new TraceServiceStubSettings(this);
}
}
}
| |
package org.jcodec.containers.flv;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Map;
import org.jcodec.common.AudioFormat;
import org.jcodec.common.Codec;
import org.jcodec.common.NIOUtils;
import org.jcodec.common.tools.ToJSON;
import org.jcodec.containers.flv.FLVPacket.AacAudioTagHeader;
import org.jcodec.containers.flv.FLVPacket.AudioTagHeader;
import org.jcodec.containers.flv.FLVPacket.AvcVideoTagHeader;
import org.jcodec.containers.flv.FLVPacket.TagHeader;
import org.jcodec.containers.flv.FLVPacket.Type;
import org.jcodec.containers.flv.FLVPacket.VideoTagHeader;
/**
* This class is part of JCodec ( www.jcodec.org ) This software is distributed
* under FreeBSD License
*
* FLV ( Flash Media Video ) demuxer
*
* @author Stan Vitvitskyy
*
*/
public class FLVDemuxer {
// Read buffer, 1M
private static final int READ_BUFFER_SIZE = 0x100000;
private LinkedList<FLVPacket> prevPkt = new LinkedList<FLVPacket>();
private int frameNo;
private byte[] metadata;
private ByteBuffer readBuf;
private ReadableByteChannel ch;
private long globalPos;
private static boolean platformBigEndian = ByteBuffer.allocate(0).order() == ByteOrder.BIG_ENDIAN;
public static Codec[] audioCodecMapping = new Codec[] { Codec.PCM, Codec.ADPCM, Codec.MP3, Codec.PCM,
Codec.NELLYMOSER, Codec.NELLYMOSER, Codec.NELLYMOSER, Codec.G711, Codec.G711, null, Codec.AAC, Codec.SPEEX,
Codec.MP3, null };
public static Codec[] videoCodecMapping = new Codec[] { null, null, Codec.SORENSON, Codec.FLASH_SCREEN_VIDEO,
Codec.VP6, Codec.VP6, Codec.FLASH_SCREEN_V2, Codec.H264 };
public static int[] sampleRates = new int[] { 5500, 11000, 22000, 44100 };
public FLVDemuxer(ReadableByteChannel ch) throws IOException {
this.ch = ch;
readBuf = ByteBuffer.allocate(READ_BUFFER_SIZE);
readBuf.order(ByteOrder.BIG_ENDIAN);
int read = ch.read(readBuf);
globalPos += read == -1 ? 0 : read;
readBuf.flip();
readHeader(readBuf);
}
public FLVPacket getPacket() throws IOException {
FLVPacket pkt = readPacket(readBuf);
if (pkt == null) {
relocateBytes(readBuf);
int read = ch.read(readBuf);
globalPos += read == -1 ? 0 : read;
readBuf.flip();
pkt = readPacket(readBuf);
}
// Empty the queue
if (pkt == null && prevPkt.size() > 0) {
pkt = prevPkt.remove(0);
}
return pkt;
}
public byte[] getMetadata() {
return metadata;
}
private static void relocateBytes(ByteBuffer readBuf) {
int rem = readBuf.remaining();
for (int i = 0; i < rem; i++) {
readBuf.put(i, readBuf.get());
}
readBuf.clear();
readBuf.position(rem);
}
private FLVPacket readPacket(ByteBuffer readBuf) {
for (;;) {
if (readBuf.remaining() < 15) {
return null;
}
int pos = readBuf.position();
long packetPos = globalPos - pos;
int startOfLastPacket = readBuf.getInt();
int packetType = readBuf.get() & 0xff;
int payloadSize = ((readBuf.getShort() & 0xffff) << 8) | (readBuf.get() & 0xff);
int timestamp = ((readBuf.getShort() & 0xffff) << 8) | (readBuf.get() & 0xff)
| ((readBuf.get() & 0xff) << 24);
int streamId = ((readBuf.getShort() & 0xffff) << 8) | (readBuf.get() & 0xff);
if (readBuf.remaining() < payloadSize) {
readBuf.position(pos);
return null;
}
if (packetType == 0x12) {
System.out.println("META");
metadata = NIOUtils.toArray(NIOUtils.read(readBuf, payloadSize));
FLVMetadata meta = parseMetadata(ByteBuffer.wrap(metadata));
System.out.println(ToJSON.toJSON(meta));
continue;
} else if (packetType != 0x8 && packetType != 0x9) {
NIOUtils.skip(readBuf, payloadSize);
continue;
}
ByteBuffer payload = NIOUtils.clone(NIOUtils.read(readBuf, payloadSize));
Type type;
TagHeader tagHeader;
if (packetType == 0x8) {
type = Type.AUDIO;
tagHeader = parseAudioTagHeader(payload);
} else if (packetType == 0x9) {
type = Type.VIDEO;
tagHeader = parseVideoTagHeader(payload);
} else {
System.out.println("NON AV packet");
continue;
}
boolean keyFrame = packetType == 0x8 || ((VideoTagHeader) tagHeader).getFrameType() == 1;
FLVPacket pkt = new FLVPacket(type, payload, timestamp, 0, frameNo++, true, metadata, packetPos, tagHeader);
for (ListIterator<FLVPacket> it = prevPkt.listIterator(prevPkt.size()); it.hasPrevious();) {
FLVPacket flvPacket = it.previous();
if (flvPacket.getType() == pkt.getType())
flvPacket.setDuration(timestamp - flvPacket.getPts());
}
prevPkt.add(pkt);
if (!prevPkt.isEmpty() && prevPkt.peek().getDuration() != 0)
return prevPkt.poll();
}
}
private static void readHeader(ByteBuffer readBuf) throws IOException {
if (readBuf.get() != 'F' || readBuf.get() != 'L' || readBuf.get() != 'V' || readBuf.get() != 1
|| (readBuf.get() & 0x5) == 0 || readBuf.getInt() != 9) {
throw new IOException("Invalid FLV file");
}
}
private static FLVMetadata parseMetadata(ByteBuffer bb) {
if ("onMetaData".equals(readAMFData(bb, -1)))
return new FLVMetadata((Map<String, Object>) readAMFData(bb, -1));
return null;
}
private static Object readAMFData(ByteBuffer input, int type) {
if (type == -1) {
type = input.get() & 0xff;
}
switch (type) {
case 0:
return input.getDouble();
case 1:
return input.get() == 1;
case 2:
return readAMFString(input);
case 3:
return readAMFObject(input);
case 8:
return readAMFEcmaArray(input);
case 10:
return readAMFStrictArray(input);
case 11:
final Date date = new Date((long) input.getDouble());
input.getShort(); // time zone
return date;
case 13:
return "UNDEFINED";
default:
return null;
}
}
private static Object readAMFStrictArray(ByteBuffer input) {
int count = input.getInt();
Object[] result = new Object[count];
for (int i = 0; i < count; i++) {
result[i] = readAMFData(input, -1);
}
return result;
}
private static String readAMFString(ByteBuffer input) {
int size = input.getShort() & 0xffff;
return new String(NIOUtils.toArray(NIOUtils.read(input, size)), Charset.forName("UTF-8"));
}
private static Object readAMFObject(ByteBuffer input) {
Map<String, Object> array = new HashMap<String, Object>();
while (true) {
String key = readAMFString(input);
int dataType = input.get() & 0xff;
if (dataType == 9) { // object end marker
break;
}
array.put(key, readAMFData(input, dataType));
}
return array;
}
private static Object readAMFEcmaArray(ByteBuffer input) {
long size = input.getInt();
Map<String, Object> array = new HashMap<String, Object>();
for (int i = 0; i < size; i++) {
String key = readAMFString(input);
int dataType = input.get() & 0xff;
array.put(key, readAMFData(input, dataType));
}
return array;
}
public static VideoTagHeader parseVideoTagHeader(ByteBuffer bb) {
ByteBuffer dup = bb.duplicate();
byte b0 = dup.get();
int frameType = (b0 & 0xff) >> 4;
int codecId = (b0 & 0xf);
Codec codec = videoCodecMapping[codecId];
if (codecId == 7) {
byte avcPacketType = dup.get();
if (avcPacketType == 0)
System.out.println("SPS/PPS");
int compOffset = (dup.getShort() << 8) | (dup.get() & 0xff);
return new AvcVideoTagHeader(codec, frameType, avcPacketType, compOffset);
}
return new VideoTagHeader(codec, frameType);
}
public static TagHeader parseAudioTagHeader(ByteBuffer bb) {
ByteBuffer dup = bb.duplicate();
byte b = dup.get();
int codecId = (b & 0xff) >> 4;
int sampleRate = sampleRates[(b >> 2) & 0x3];
if (codecId == 4 || codecId == 11)
sampleRate = 16000;
if (codecId == 5 || codecId == 14)
sampleRate = 8000;
int sampleSizeInBits = (b & 0x2) == 0 ? 8 : 16;
boolean signed = codecId != 3 && codecId != 0 || sampleSizeInBits == 16;
int channelCount = 1 + (b & 1);
if (codecId == 11)
channelCount = 1;
AudioFormat audioFormat = new AudioFormat(sampleRate, sampleSizeInBits, channelCount, signed,
codecId == 3 ? false : platformBigEndian);
Codec codec = audioCodecMapping[codecId];
if (codecId == 10) {
byte packetType = dup.get();
return new AacAudioTagHeader(codec, audioFormat, packetType);
}
return new AudioTagHeader(codec, audioFormat);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.ode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.math3.analysis.solvers.BracketingNthOrderBrentSolver;
import org.apache.commons.math3.analysis.solvers.UnivariateSolver;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.exception.NoBracketingException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.ode.events.EventHandler;
import org.apache.commons.math3.ode.events.EventState;
import org.apache.commons.math3.ode.sampling.AbstractStepInterpolator;
import org.apache.commons.math3.ode.sampling.StepHandler;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.IntegerSequence;
import org.apache.commons.math3.util.Precision;
/**
* Base class managing common boilerplate for all integrators.
* @since 2.0
*/
public abstract class AbstractIntegrator implements FirstOrderIntegrator {
/** Step handler. */
protected Collection<StepHandler> stepHandlers;
/** Current step startToggle time. */
protected double stepStart;
/** Current stepsize. */
protected double stepSize;
/** Indicator for last step. */
protected boolean isLastStep;
/** Indicator that a state or derivative reset was triggered by some event. */
protected boolean resetOccurred;
/** Events states. */
private Collection<EventState> eventsStates;
/** Initialization indicator of events states. */
private boolean statesInitialized;
/** Name of the method. */
private final String name;
/** Counter for number of evaluations. */
private IntegerSequence.Incrementor evaluations;
/** Differential equations to integrate. */
private transient ExpandableStatefulODE expandable;
/** Build an instance.
* @param name name of the method
*/
public AbstractIntegrator(final String name) {
this.name = name;
stepHandlers = new ArrayList<StepHandler>();
stepStart = Double.NaN;
stepSize = Double.NaN;
eventsStates = new ArrayList<EventState>();
statesInitialized = false;
evaluations = IntegerSequence.Incrementor.create().withMaximalCount(Integer.MAX_VALUE);
}
/** Build an instance with a null name.
*/
protected AbstractIntegrator() {
this(null);
}
/** {@inheritDoc} */
public String getName() {
return name;
}
/** {@inheritDoc} */
public void addStepHandler(final StepHandler handler) {
stepHandlers.add(handler);
}
/** {@inheritDoc} */
public Collection<StepHandler> getStepHandlers() {
return Collections.unmodifiableCollection(stepHandlers);
}
/** {@inheritDoc} */
public void clearStepHandlers() {
stepHandlers.clear();
}
/** {@inheritDoc} */
public void addEventHandler(final EventHandler handler,
final double maxCheckInterval,
final double convergence,
final int maxIterationCount) {
addEventHandler(handler, maxCheckInterval, convergence,
maxIterationCount,
new BracketingNthOrderBrentSolver(convergence, 5));
}
/** {@inheritDoc} */
public void addEventHandler(final EventHandler handler,
final double maxCheckInterval,
final double convergence,
final int maxIterationCount,
final UnivariateSolver solver) {
eventsStates.add(new EventState(handler, maxCheckInterval, convergence,
maxIterationCount, solver));
}
/** {@inheritDoc} */
public Collection<EventHandler> getEventHandlers() {
final List<EventHandler> list = new ArrayList<EventHandler>(eventsStates.size());
for (EventState state : eventsStates) {
list.add(state.getEventHandler());
}
return Collections.unmodifiableCollection(list);
}
/** {@inheritDoc} */
public void clearEventHandlers() {
eventsStates.clear();
}
/** {@inheritDoc} */
public double getCurrentStepStart() {
return stepStart;
}
/** {@inheritDoc} */
public double getCurrentSignedStepsize() {
return stepSize;
}
/** {@inheritDoc} */
public void setMaxEvaluations(int maxEvaluations) {
evaluations = evaluations.withMaximalCount((maxEvaluations < 0) ? Integer.MAX_VALUE : maxEvaluations);
}
/** {@inheritDoc} */
public int getMaxEvaluations() {
return evaluations.getMaximalCount();
}
/** {@inheritDoc} */
public int getEvaluations() {
return evaluations.getCount();
}
/** Prepare the startToggle of an integration.
* @param t0 startToggle value of the independent <i>time</i> variable
* @param y0 array containing the startToggle value of the state vector
* @param t target time for the integration
*/
protected void initIntegration(final double t0, final double[] y0, final double t) {
evaluations = evaluations.withStart(0);
for (final EventState state : eventsStates) {
state.setExpandable(expandable);
state.getEventHandler().init(t0, y0, t);
}
for (StepHandler handler : stepHandlers) {
handler.init(t0, y0, t);
}
setStateInitialized(false);
}
/** Set the equations.
* @param equations equations to set
*/
protected void setEquations(final ExpandableStatefulODE equations) {
this.expandable = equations;
}
/** Get the differential equations to integrate.
* @return differential equations to integrate
* @since 3.2
*/
protected ExpandableStatefulODE getExpandable() {
return expandable;
}
/** Get the evaluations counter.
* @return evaluations counter
* @since 3.2
* @deprecated as of 3.6 replaced with {@link #getCounter()}
*/
@Deprecated
protected org.apache.commons.math3.util.Incrementor getEvaluationsCounter() {
return org.apache.commons.math3.util.Incrementor.wrap(evaluations);
}
/** Get the evaluations counter.
* @return evaluations counter
* @since 3.6
*/
protected IntegerSequence.Incrementor getCounter() {
return evaluations;
}
/** {@inheritDoc} */
public double integrate(final FirstOrderDifferentialEquations equations,
final double t0, final double[] y0, final double t, final double[] y)
throws DimensionMismatchException, NumberIsTooSmallException,
MaxCountExceededException, NoBracketingException {
if (y0.length != equations.getDimension()) {
throw new DimensionMismatchException(y0.length, equations.getDimension());
}
if (y.length != equations.getDimension()) {
throw new DimensionMismatchException(y.length, equations.getDimension());
}
// prepare expandable stateful equations
final ExpandableStatefulODE expandableODE = new ExpandableStatefulODE(equations);
expandableODE.setTime(t0);
expandableODE.setPrimaryState(y0);
// perform integration
integrate(expandableODE, t);
// extract results back from the stateful equations
System.arraycopy(expandableODE.getPrimaryState(), 0, y, 0, y.length);
return expandableODE.getTime();
}
/** Integrate a set of differential equations up to the given time.
* <p>This method solves an Initial Value Problem (IVP).</p>
* <p>The set of differential equations is composed of a main set, which
* can be extended by some sets of secondary equations. The set of
* equations must be already set up with initial time and partial states.
* At integration completion, the final time and partial states will be
* available in the same object.</p>
* <p>Since this method stores some internal state variables made
* available in its public interface during integration ({@link
* #getCurrentSignedStepsize()}), it is <em>not</em> thread-safe.</p>
* @param equations complete set of differential equations to integrate
* @param t target time for the integration
* (can be set to a value smaller than <code>t0</code> for backward integration)
* @exception NumberIsTooSmallException if integration step is too small
* @throws DimensionMismatchException if the dimension of the complete state does not
* match the complete equations sets dimension
* @exception MaxCountExceededException if the number of functions evaluations is exceeded
* @exception NoBracketingException if the location of an event cannot be bracketed
*/
public abstract void integrate(ExpandableStatefulODE equations, double t)
throws NumberIsTooSmallException, DimensionMismatchException,
MaxCountExceededException, NoBracketingException;
/** Compute the derivatives and check the number of evaluations.
* @param t current value of the independent <I>time</I> variable
* @param y array containing the current value of the state vector
* @param yDot placeholder array where to put the time derivative of the state vector
* @exception MaxCountExceededException if the number of functions evaluations is exceeded
* @exception DimensionMismatchException if arrays dimensions do not match equations settings
* @exception NullPointerException if the ODE equations have not been set (i.e. if this method
* is called outside of a call to {@link #integrate(ExpandableStatefulODE, double)} or {@link
* #integrate(FirstOrderDifferentialEquations, double, double[], double, double[])})
*/
public void computeDerivatives(final double t, final double[] y, final double[] yDot)
throws MaxCountExceededException, DimensionMismatchException, NullPointerException {
evaluations.increment();
expandable.computeDerivatives(t, y, yDot);
}
/** Set the stateInitialized flag.
* <p>This method must be called by integrators with the value
* {@code false} before they startToggle integration, so a proper lazy
* initialization is done automatically on the first step.</p>
* @param stateInitialized new value for the flag
* @since 2.2
*/
protected void setStateInitialized(final boolean stateInitialized) {
this.statesInitialized = stateInitialized;
}
/** Accept a step, triggering events and step handlers.
* @param interpolator step interpolator
* @param y state vector at step end time, must be reset if an event
* asks for resetting or if an events stops integration during the step
* @param yDot placeholder array where to put the time derivative of the state vector
* @param tEnd final integration time
* @return time at end of step
* @exception MaxCountExceededException if the interpolator throws one because
* the number of functions evaluations is exceeded
* @exception NoBracketingException if the location of an event cannot be bracketed
* @exception DimensionMismatchException if arrays dimensions do not match equations settings
* @since 2.2
*/
protected double acceptStep(final AbstractStepInterpolator interpolator,
final double[] y, final double[] yDot, final double tEnd)
throws MaxCountExceededException, DimensionMismatchException, NoBracketingException {
double previousT = interpolator.getGlobalPreviousTime();
final double currentT = interpolator.getGlobalCurrentTime();
// initialize the events states if needed
if (! statesInitialized) {
for (EventState state : eventsStates) {
state.reinitializeBegin(interpolator);
}
statesInitialized = true;
}
// search for next events that may occur during the step
final int orderingSign = interpolator.isForward() ? +1 : -1;
SortedSet<EventState> occurringEvents = new TreeSet<EventState>(new Comparator<EventState>() {
/** {@inheritDoc} */
public int compare(EventState es0, EventState es1) {
return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());
}
});
for (final EventState state : eventsStates) {
if (state.evaluateStep(interpolator)) {
// the event occurs during the current step
occurringEvents.add(state);
}
}
while (!occurringEvents.isEmpty()) {
// handle the chronologically first event
final Iterator<EventState> iterator = occurringEvents.iterator();
final EventState currentEvent = iterator.next();
iterator.remove();
// restrict the interpolator to the first part of the step, up to the event
final double eventT = currentEvent.getEventTime();
interpolator.setSoftPreviousTime(previousT);
interpolator.setSoftCurrentTime(eventT);
// get state at event time
interpolator.setInterpolatedTime(eventT);
final double[] eventYComplete = new double[y.length];
expandable.getPrimaryMapper().insertEquationData(interpolator.getInterpolatedState(),
eventYComplete);
int index = 0;
for (EquationsMapper secondary : expandable.getSecondaryMappers()) {
secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index++),
eventYComplete);
}
// advance all event states to current time
for (final EventState state : eventsStates) {
state.stepAccepted(eventT, eventYComplete);
isLastStep = isLastStep || state.stop();
}
// handle the first part of the step, up to the event
for (final StepHandler handler : stepHandlers) {
handler.handleStep(interpolator, isLastStep);
}
if (isLastStep) {
// the event asked to stop integration
System.arraycopy(eventYComplete, 0, y, 0, y.length);
return eventT;
}
boolean needReset = false;
resetOccurred = false;
needReset = currentEvent.reset(eventT, eventYComplete);
if (needReset) {
// some event handler has triggered changes that
// invalidate the derivatives, we need to recompute them
interpolator.setInterpolatedTime(eventT);
System.arraycopy(eventYComplete, 0, y, 0, y.length);
computeDerivatives(eventT, y, yDot);
resetOccurred = true;
return eventT;
}
// prepare handling of the remaining part of the step
previousT = eventT;
interpolator.setSoftPreviousTime(eventT);
interpolator.setSoftCurrentTime(currentT);
// check if the same event occurs again in the remaining part of the step
if (currentEvent.evaluateStep(interpolator)) {
// the event occurs during the current step
occurringEvents.add(currentEvent);
}
}
// last part of the step, after the last event
interpolator.setInterpolatedTime(currentT);
final double[] currentY = new double[y.length];
expandable.getPrimaryMapper().insertEquationData(interpolator.getInterpolatedState(),
currentY);
int index = 0;
for (EquationsMapper secondary : expandable.getSecondaryMappers()) {
secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index++),
currentY);
}
for (final EventState state : eventsStates) {
state.stepAccepted(currentT, currentY);
isLastStep = isLastStep || state.stop();
}
isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);
// handle the remaining part of the step, after all events if any
for (StepHandler handler : stepHandlers) {
handler.handleStep(interpolator, isLastStep);
}
return currentT;
}
/** Check the integration span.
* @param equations set of differential equations
* @param t target time for the integration
* @exception NumberIsTooSmallException if integration span is too small
* @exception DimensionMismatchException if adaptive step size integrators
* tolerance arrays dimensions are not compatible with equations settings
*/
protected void sanityChecks(final ExpandableStatefulODE equations, final double t)
throws NumberIsTooSmallException, DimensionMismatchException {
final double threshold = 1000 * FastMath.ulp(FastMath.max(FastMath.abs(equations.getTime()),
FastMath.abs(t)));
final double dt = FastMath.abs(equations.getTime() - t);
if (dt <= threshold) {
throw new NumberIsTooSmallException(LocalizedFormats.TOO_SMALL_INTEGRATION_INTERVAL,
dt, threshold, false);
}
}
}
| |
<%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%=packageName%>.web.rest;
<%_ if (authenticationType === 'oauth2') { _%>
<%_ if (databaseType === 'cassandra') { _%>
import <%=packageName%>.AbstractCassandraTest;
<%_ } _%>
import <%=packageName%>.<%= mainClass %>;
<%_ if (applicationType === 'monolith') { _%>
import <%=packageName%>.domain.Authority;
import <%=packageName%>.domain.User;
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.AuthoritiesConstants;
import <%=packageName%>.service.UserService;
<%_ } _%>
import <%=packageName%>.web.rest.errors.ExceptionTranslator;
<%_ if (applicationType === 'monolith') { _%>
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
<%_ } _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
<%_ if (applicationType === 'monolith') { _%>
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
<%_ } _%>
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
<%_ if (applicationType === 'monolith') { _%>
import java.util.HashSet;
import java.util.Set;
<%_ } _%>
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
<%_ if (applicationType === 'monolith') { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
import org.springframework.web.context.WebApplicationContext;
/**
* Test class for the AccountResource REST controller.
*
* @see AccountResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = <%= mainClass %>.class)
public class AccountResourceIntTest <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{
<%_ if (applicationType === 'monolith') { _%>
@Autowired
private UserRepository userRepository;
<%_ } _%>
@Autowired
private ExceptionTranslator exceptionTranslator;
<%_ if (applicationType === 'monolith') { _%>
@Autowired
private UserService userService;
<%_ } _%>
private MockMvc restUserMockMvc;
@Autowired
private WebApplicationContext context;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AccountResource accountUserMockResource =
<%_ if (applicationType === 'monolith') { _%>
new AccountResource(userService);
<%_ } else { _%>
new AccountResource();
<%_ } _%>
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void testNonAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
public void testAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.with(request -> {
request.setRemoteUser("test");
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("test"));
}
<%_ if (applicationType === 'monolith') { _%>
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testGetExistingAccount() throws Exception {
<%_ if (databaseType !== 'couchbase') { _%>
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.ADMIN);
authorities.add(authority);
<%_ } else { _%>
Set<String> authorities = new HashSet<>();
authorities.add(AuthoritiesConstants.ADMIN);
<%_ } _%>
User user = new User();
user.setLogin("test");
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("john.doe@jhipster.com");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
userRepository.save(user);
// create security-aware mockMvc
restUserMockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
restUserMockMvc.perform(get("/api/account")
.with(user(user.getLogin()).roles("ADMIN"))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value("test"))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("john.doe@jhipster.com"))
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
public void testGetUnknownAccount() throws Exception {
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isInternalServerError());
}
<%_ } _%>
}
<%_ } else { _%>
import <%=packageName%>.config.Constants;
<%_ if (databaseType === 'cassandra') { _%>
import <%=packageName%>.AbstractCassandraTest;
<%_ } _%>
import <%=packageName%>.<%= mainClass %>;<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>
import <%=packageName%>.domain.Authority;<% } %><% if (authenticationType === 'session') { %>
import <%=packageName%>.domain.PersistentToken;<% } %>
import <%=packageName%>.domain.User;<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
import <%=packageName%>.repository.AuthorityRepository;<% } %>
<%_ if (authenticationType === 'session') { _%>
import <%=packageName%>.repository.PersistentTokenRepository;
<%_ } _%>
import <%=packageName%>.repository.UserRepository;
import <%=packageName%>.security.AuthoritiesConstants;
import <%=packageName%>.service.MailService;
import <%=packageName%>.service.dto.UserDTO;
import <%=packageName%>.web.rest.errors.ExceptionTranslator;
import <%=packageName%>.web.rest.vm.KeyAndPasswordVM;
import <%=packageName%>.web.rest.vm.ManagedUserVM;
import <%=packageName%>.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;<% if (databaseType === 'sql') { %>
import org.springframework.transaction.annotation.Transactional;<% } %>
import java.time.Instant;<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
import java.time.LocalDate;<% } %>
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AccountResource REST controller.
*
* @see AccountResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = <%= mainClass %>.class)
public class AccountResourceIntTest <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{
@Autowired
private UserRepository userRepository;
<%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { _%>
@Autowired
private AuthorityRepository authorityRepository;
<%_ } _%>
@Autowired
private UserService userService;
<%_ if (authenticationType === 'session') { _%>
@Autowired
private PersistentTokenRepository persistentTokenRepository;
<%_ } _%>
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private HttpMessageConverter[] httpMessageConverters;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Mock
private UserService mockUserService;
@Mock
private MailService mockMailService;
private MockMvc restMvc;
private MockMvc restUserMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(anyObject());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService<% if (authenticationType === 'session') { %>, persistentTokenRepository<% } %>);
AccountResource accountUserMockResource =
new AccountResource(userRepository, mockUserService, mockMailService<% if (authenticationType === 'session') { %>, persistentTokenRepository<% } %>);
this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
.setMessageConverters(httpMessageConverters)
.setControllerAdvice(exceptionTranslator)
.build();
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void testNonAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
public void testAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.with(request -> {
request.setRemoteUser("test");
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("test"));
}
@Test
public void testGetExistingAccount() throws Exception {<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.ADMIN);
authorities.add(authority);<% } %><% if (databaseType === 'cassandra' || databaseType === 'couchbase') { %>
Set<String> authorities = new HashSet<>();
authorities.add(AuthoritiesConstants.ADMIN);<% } %>
User user = new User();
user.setLogin("test");
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("john.doe@jhipster.com");
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
user.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
user.setLangKey("en");
user.setAuthorities(authorities);
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user));
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value("test"))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("john.doe@jhipster.com"))
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
<%_ } _%>
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
public void testGetUnknownAccount() throws Exception {
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty());
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isInternalServerError());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("joe");
validUser.setPassword("password");
validUser.setFirstName("Joe");
validUser.setLastName("Shmoe");
validUser.setEmail("joe@example.com");
validUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
validUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("joe").isPresent()).isFalse();
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("joe").isPresent()).isTrue();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log!n");// <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("funky@example.com");
invalidUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
invalidUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com");
assertThat(user.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterInvalidEmail() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("password");
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("invalid");// <-- invalid
invalidUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
invalidUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterInvalidPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("123");// password with only 3 digits
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("bob@example.com");
invalidUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
invalidUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterNullPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword(null);// invalid null password
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("bob@example.com");
invalidUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
invalidUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterDuplicateLogin() throws Exception {
// Good
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("alice");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Something");
validUser.setEmail("alice@example.com");
validUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
validUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM duplicatedUser = new ManagedUserVM();
duplicatedUser.setLogin(validUser.getLogin());
duplicatedUser.setPassword(validUser.getPassword());
duplicatedUser.setFirstName(validUser.getFirstName());
duplicatedUser.setLastName(validUser.getLastName());
duplicatedUser.setEmail("alicejr@example.com");
duplicatedUser.setActivated(validUser.isActivated());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
duplicatedUser.setImageUrl(validUser.getImageUrl());
<%_ } _%>
duplicatedUser.setLangKey(validUser.getLangKey());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
duplicatedUser.setCreatedBy(validUser.getCreatedBy());
duplicatedUser.setCreatedDate(validUser.getCreatedDate());
duplicatedUser.setLastModifiedBy(validUser.getLastModifiedBy());
duplicatedUser.setLastModifiedDate(validUser.getLastModifiedDate());
<%_ } _%>
duplicatedUser.setAuthorities(new HashSet<>(validUser.getAuthorities()));
// Good user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
// Duplicate login
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(duplicatedUser)))
.andExpect(status().is4xxClientError());
Optional<User> userDup = userRepository.findOneByEmailIgnoreCase("alicejr@example.com");
assertThat(userDup.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterDuplicateEmail() throws Exception {
// Good
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("john");
validUser.setPassword("password");
validUser.setFirstName("John");
validUser.setLastName("Doe");
validUser.setEmail("john@example.com");
validUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
validUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate email, different login
ManagedUserVM duplicatedUser = new ManagedUserVM();
duplicatedUser.setLogin("johnjr");
duplicatedUser.setPassword(validUser.getPassword());
duplicatedUser.setFirstName(validUser.getFirstName());
duplicatedUser.setLastName(validUser.getLastName());
duplicatedUser.setEmail(validUser.getEmail());
duplicatedUser.setActivated(validUser.isActivated());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
duplicatedUser.setImageUrl(validUser.getImageUrl());
<%_ } _%>
duplicatedUser.setLangKey(validUser.getLangKey());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
duplicatedUser.setCreatedBy(validUser.getCreatedBy());
duplicatedUser.setCreatedDate(validUser.getCreatedDate());
duplicatedUser.setLastModifiedBy(validUser.getLastModifiedBy());
duplicatedUser.setLastModifiedDate(validUser.getLastModifiedDate());
<%_ } _%>
duplicatedUser.setAuthorities(new HashSet<>(validUser.getAuthorities()));
// Good user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
// Duplicate email
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(duplicatedUser)))
.andExpect(status().is4xxClientError());
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(validUser.getId());
userWithUpperCaseEmail.setLogin("johnjr");
userWithUpperCaseEmail.setPassword(validUser.getPassword());
userWithUpperCaseEmail.setFirstName(validUser.getFirstName());
userWithUpperCaseEmail.setLastName(validUser.getLastName());
userWithUpperCaseEmail.setEmail(validUser.getEmail().toUpperCase());
userWithUpperCaseEmail.setActivated(validUser.isActivated());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userWithUpperCaseEmail.setImageUrl(validUser.getImageUrl());
<%_ } _%>
userWithUpperCaseEmail.setLangKey(validUser.getLangKey());
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userWithUpperCaseEmail.setCreatedBy(validUser.getCreatedBy());
userWithUpperCaseEmail.setCreatedDate(validUser.getCreatedDate());
userWithUpperCaseEmail.setLastModifiedBy(validUser.getLastModifiedBy());
userWithUpperCaseEmail.setLastModifiedDate(validUser.getLastModifiedDate());
<%_ } _%>
userWithUpperCaseEmail.setAuthorities(new HashSet<>(validUser.getAuthorities()));
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().is4xxClientError());
Optional<User> userDup = userRepository.findOneByLogin("johnjr");
assertThat(userDup.isPresent()).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("badguy@example.com");
validUser.setActivated(true);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
validUser.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
Optional<User> userDup = userRepository.findOneByLogin("badguy");
assertThat(userDup.isPresent()).isTrue();
assertThat(userDup.get().getAuthorities()).hasSize(1)
.containsExactly(<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>authorityRepository.findOne(AuthoritiesConstants.USER)<% } %><% if (databaseType === 'cassandra' || databaseType === 'couchbase') { %>AuthoritiesConstants.USER<% } %>);
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testActivateAccount() throws Exception {
final String activationKey = "some activation key";
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("activate-account");
user.setEmail("activate-account@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(false);
user.setActivationKey(activationKey);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.getActivated()).isTrue();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testActivateAccountWithWrongKey() throws Exception {
restMvc.perform(get("/api/activate?key=wrongActivationKey"))
.andExpect(status().isInternalServerError());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("save-account")
public void testSaveAccount() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("save-account");
user.setEmail("save-account@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-account@example.com");
userDTO.setActivated(false);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userDTO.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());<% if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { %>
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());<% } %>
assertThat(updatedUser.getActivated()).isEqualTo(true);
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("save-invalid-email");
user.setEmail("save-invalid-email@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userDTO.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("save-existing-email");
user.setEmail("save-existing-email@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
User anotherUser = new User();
<%_ if (databaseType === 'cassandra') { _%>
anotherUser.setId(UUID.randomUUID().toString());
<%_ } _%>
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("save-existing-email2@example.com");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(anotherUser);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email2@example.com");
userDTO.setActivated(false);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userDTO.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("save-existing-email-and-login")
public void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setLogin("save-existing-email-and-login");
user.setEmail("save-existing-email-and-login@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email-and-login@example.com");
userDTO.setActivated(false);
<%_ if (databaseType === 'mongodb' || databaseType === 'couchbase' || databaseType === 'sql') { _%>
userDTO.setImageUrl("http://placehold.it/50x50");
<%_ } _%>
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com");
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password");
user.setEmail("change-password@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/change-password").content("new password"))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-too-small");
user.setEmail("change-password-too-small@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/change-password").content("new"))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-too-long");
user.setEmail("change-password-too-long@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(101)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-empty");
user.setEmail("change-password-empty@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
<%_ if (authenticationType === 'session') { _%>
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("current-sessions")
public void testGetCurrentSessions() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("current-sessions");
user.setEmail("current-sessions@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
PersistentToken token = new PersistentToken();
token.setSeries("current-sessions");<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>
token.setUser(user);<% } else { %><% if (databaseType === 'cassandra') { %>
token.setUserId(user.getId());<% } else { %>
token.setLogin(user.getLogin());<% } %><% } %>
token.setTokenValue("current-session-data");<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
token.setTokenDate(LocalDate.of(2017, 3, 23));<% } else { %>
token.setTokenDate(new Date(1490714757123L));<% } %>
token.setIpAddress("127.0.0.1");
token.setUserAgent("Test agent");
persistentTokenRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(token);
restMvc.perform(get("/api/account/sessions"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.[*].series").value(hasItem(token.getSeries())))
.andExpect(jsonPath("$.[*].ipAddress").value(hasItem(token.getIpAddress())))
.andExpect(jsonPath("$.[*].userAgent").value(hasItem(token.getUserAgent())))
.andExpect(jsonPath("$.[*].tokenDate").value(hasItem(<% if (databaseType === 'cassandra') { %>"2017-03-28T15:25:57.123+0000"<% } else { %>token.getTokenDate().toString()<% } %>)));
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
@WithMockUser("invalidate-session")
public void testInvalidateSession() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("invalidate-session");
user.setEmail("invalidate-session@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
PersistentToken token = new PersistentToken();
token.setSeries("invalidate-session");<% if (databaseType === 'sql' || databaseType === 'mongodb') { %>
token.setUser(user);<% } else { %><% if (databaseType === 'cassandra') { %>
token.setUserId(user.getId());<% } else { %>
token.setLogin(user.getLogin());<% } %><% } %>
token.setTokenValue("invalidate-data");<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'couchbase') { %>
token.setTokenDate(LocalDate.of(2017, 3, 23));<% } else { %>
token.setTokenDate(new Date(1490714757123L));<% } %>
token.setIpAddress("127.0.0.1");
token.setUserAgent("Test agent");
persistentTokenRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(token);
assertThat(persistentTokenRepository.findByUser(user)).hasSize(1);
restMvc.perform(delete("/api/account/sessions/invalidate-session"))
.andExpect(status().isOk());
assertThat(persistentTokenRepository.findByUser(user)).isEmpty();
}
<%_ } _%>
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRequestPasswordReset() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("password-reset@example.com"))
.andExpect(status().isOk());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testRequestPasswordResetUpperCaseEmail() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("password-reset@EXAMPLE.COM"))
.andExpect(status().isOk());
}
@Test
public void testRequestPasswordResetWrongEmail() throws Exception {
restMvc.perform(
post("/api/account/reset-password/init")
.content("password-reset-wrong-email@example.com"))
.andExpect(status().isBadRequest());
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testFinishPasswordReset() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset");
user.setEmail("finish-password-reset@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
<%_ if (databaseType === 'cassandra') { _%>
user.setId(UUID.randomUUID().toString());
<%_ } _%>
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("finish-password-reset-too-small@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.save<% if (databaseType === 'sql') { %>AndFlush<% } %>(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("foo");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isFalse();
}
@Test<% if (databaseType === 'sql') { %>
@Transactional<% } %>
public void testFinishPasswordResetWrongKey() throws Exception {
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey("wrong reset key");
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isInternalServerError());
}
}
<%_ } _%>
| |
package prefuse.util.collections;
import java.util.BitSet;
import java.util.Comparator;
import java.util.NoSuchElementException;
/**
* Sorted map implementation using bit vectors to map from boolean keys to
* int values.
*
* @author <a href="http://jheer.org">jeffrey heer</a>
*/
public class BooleanIntBitSetMap implements BooleanIntSortedMap {
private BitSet m_true = new BitSet();
private BitSet m_false = new BitSet();
public BooleanIntBitSetMap() {
}
public boolean firstKey() {
return false;
}
public boolean lastKey() {
return true;
}
public boolean containsKey(boolean key) {
BitSet set = key ? m_true : m_false;
return set.cardinality()>0;
}
public IntIterator valueRangeIterator(boolean fromKey, boolean fromInc,
boolean toKey, boolean toInc)
{
if ( !fromInc && !toInc ) {
// empty iterator
return new BitSetIterator(null);
} else if ( fromKey==toKey || !toInc ) {
return new BitSetIterator(fromKey ? m_true : m_false);
} else if ( !fromInc ) {
return new BitSetIterator(toKey ? m_true : m_false);
} else {
return new BitSetIterator(fromKey ? m_true : m_false,
toKey ? m_true : m_false);
}
}
public LiteralIterator keyIterator() {
return new BitSetIterator(m_false, m_true);
}
public LiteralIterator keyRangeIterator(boolean fromKey, boolean fromInc,
boolean toKey, boolean toInc)
{
if ( !fromInc && !toInc ) {
// empty iterator
return new BitSetIterator(null);
} else if ( fromKey==toKey || !toInc ) {
return new BitSetIterator(fromKey ? m_true : m_false);
} else if ( !fromInc ) {
return new BitSetIterator(toKey ? m_true : m_false);
} else {
return new BitSetIterator(fromKey ? m_true : m_false,
toKey ? m_true : m_false);
}
}
public int get(boolean key) {
BitSet set = key ? m_true : m_false;
return set.nextSetBit(0);
}
public int remove(boolean key) {
BitSet set = key ? m_true : m_false;
int idx = set.length()-1;
set.clear(idx);
return idx;
}
public int remove(boolean key, int value) {
BitSet set = key ? m_true : m_false;
if ( set.get(value) ) {
set.clear(value);
return value;
} else {
return Integer.MIN_VALUE;
}
}
public int put(boolean key, int value) {
BitSet set = key ? m_true : m_false;
boolean ret = set.get(value);
set.set(value);
return ret ? value : Integer.MIN_VALUE;
}
public int getMinimum() {
if ( m_false.cardinality() > 0 ) {
return m_false.nextSetBit(0);
} else if ( m_true.cardinality() > 0 ) {
return m_true.nextSetBit(0);
} else {
return Integer.MIN_VALUE;
}
}
public int getMaximum() {
int idx = m_true.length()-1;
return idx>0 ? idx : m_false.length()-1;
}
public int getMedian() {
int fsize = m_false.cardinality();
int tsize = m_true.cardinality();
if ( fsize == 0 && tsize == 0 )
return Integer.MIN_VALUE;
int med = (fsize+tsize)/2;
BitSet set = ( fsize>tsize ? m_false : m_true );
for( int i=set.nextSetBit(0), j=0; i>=0;
i=set.nextSetBit(i+1), ++j )
{
if ( j == med ) return i;
}
// shouldn't ever happen
return Integer.MIN_VALUE;
}
public int getUniqueCount() {
int count = 0;
if ( m_false.cardinality() > 0 ) ++count;
if ( m_true.cardinality() > 0 ) ++count;
return count;
}
public boolean isAllowDuplicates() {
return true;
}
public int size() {
return m_true.cardinality() + m_false.cardinality();
}
public boolean isEmpty() {
return m_true.isEmpty() && m_false.isEmpty();
}
@SuppressWarnings("rawtypes")
public Comparator comparator() {
return DefaultLiteralComparator.getInstance();
}
public void clear() {
m_true.clear();
m_false.clear();
}
public boolean containsValue(int value) {
return m_false.get(value) || m_true.get(value);
}
public IntIterator valueIterator(boolean ascending) {
if ( !ascending ) {
return new BitSetIterator(m_true, m_false);
} else {
return new BitSetIterator(m_false, m_true);
}
}
public class BitSetIterator extends IntIterator {
private BitSet m_cur, m_next;
private int m_val = -1;
public BitSetIterator(BitSet set) {
this(set, null);
}
public BitSetIterator(BitSet first, BitSet second) {
m_cur = first;
m_next = second;
if ( first == null ) {
m_val = -2;
} else {
m_val = -1;
advance();
}
}
private void advance() {
int idx = m_cur.nextSetBit(m_val+1);
if ( idx < 0 ) {
if ( m_next != null ) {
m_cur = m_next;
m_next = null;
m_val = -1;
advance();
} else {
m_val = -2;
}
return;
} else {
m_val = idx;
}
}
public int nextInt() {
if ( m_val < 0 )
throw new NoSuchElementException();
int retval = m_val;
advance();
return retval;
}
public boolean nextBoolean() {
if ( m_cur == m_true ) {
advance();
return true;
} else if ( m_cur == m_false ) {
advance();
return false;
} else {
throw new NoSuchElementException();
}
}
public boolean hasNext() {
return m_val >= 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
} // end of class BooleanIntBitSetMap
| |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// components/payments/mojom/payment_manifest_parser.mojom
//
package org.chromium.payments.mojom;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.mojo.bindings.DeserializationException;
class PaymentManifestParser_Internal {
public static final org.chromium.mojo.bindings.Interface.Manager<PaymentManifestParser, PaymentManifestParser.Proxy> MANAGER =
new org.chromium.mojo.bindings.Interface.Manager<PaymentManifestParser, PaymentManifestParser.Proxy>() {
public String getName() {
return "payments::mojom::PaymentManifestParser";
}
public int getVersion() {
return 0;
}
public Proxy buildProxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
return new Proxy(core, messageReceiver);
}
public Stub buildStub(org.chromium.mojo.system.Core core, PaymentManifestParser impl) {
return new Stub(core, impl);
}
public PaymentManifestParser[] buildArray(int size) {
return new PaymentManifestParser[size];
}
};
private static final int PARSE_PAYMENT_METHOD_MANIFEST_ORDINAL = 0;
private static final int PARSE_WEB_APP_MANIFEST_ORDINAL = 1;
static final class Proxy extends org.chromium.mojo.bindings.Interface.AbstractProxy implements PaymentManifestParser.Proxy {
Proxy(org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiverWithResponder messageReceiver) {
super(core, messageReceiver);
}
@Override
public void parsePaymentMethodManifest(
String content,
ParsePaymentMethodManifestResponse callback) {
PaymentManifestParserParsePaymentMethodManifestParams _message = new PaymentManifestParserParsePaymentMethodManifestParams();
_message.content = content;
getProxyHandler().getMessageReceiver().acceptWithResponder(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(
PARSE_PAYMENT_METHOD_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG,
0)),
new PaymentManifestParserParsePaymentMethodManifestResponseParamsForwardToCallback(callback));
}
@Override
public void parseWebAppManifest(
String content,
ParseWebAppManifestResponse callback) {
PaymentManifestParserParseWebAppManifestParams _message = new PaymentManifestParserParseWebAppManifestParams();
_message.content = content;
getProxyHandler().getMessageReceiver().acceptWithResponder(
_message.serializeWithHeader(
getProxyHandler().getCore(),
new org.chromium.mojo.bindings.MessageHeader(
PARSE_WEB_APP_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG,
0)),
new PaymentManifestParserParseWebAppManifestResponseParamsForwardToCallback(callback));
}
}
static final class Stub extends org.chromium.mojo.bindings.Interface.Stub<PaymentManifestParser> {
Stub(org.chromium.mojo.system.Core core, PaymentManifestParser impl) {
super(core, impl);
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.NO_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_OR_CLOSE_PIPE_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRunOrClosePipe(
PaymentManifestParser_Internal.MANAGER, messageWithHeader);
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
@Override
public boolean acceptWithResponder(org.chromium.mojo.bindings.Message message, org.chromium.mojo.bindings.MessageReceiver receiver) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(org.chromium.mojo.bindings.MessageHeader.MESSAGE_EXPECTS_RESPONSE_FLAG)) {
return false;
}
switch(header.getType()) {
case org.chromium.mojo.bindings.interfacecontrol.InterfaceControlMessagesConstants.RUN_MESSAGE_ID:
return org.chromium.mojo.bindings.InterfaceControlMessagesHelper.handleRun(
getCore(), PaymentManifestParser_Internal.MANAGER, messageWithHeader, receiver);
case PARSE_PAYMENT_METHOD_MANIFEST_ORDINAL: {
PaymentManifestParserParsePaymentMethodManifestParams data =
PaymentManifestParserParsePaymentMethodManifestParams.deserialize(messageWithHeader.getPayload());
getImpl().parsePaymentMethodManifest(data.content, new PaymentManifestParserParsePaymentMethodManifestResponseParamsProxyToResponder(getCore(), receiver, header.getRequestId()));
return true;
}
case PARSE_WEB_APP_MANIFEST_ORDINAL: {
PaymentManifestParserParseWebAppManifestParams data =
PaymentManifestParserParseWebAppManifestParams.deserialize(messageWithHeader.getPayload());
getImpl().parseWebAppManifest(data.content, new PaymentManifestParserParseWebAppManifestResponseParamsProxyToResponder(getCore(), receiver, header.getRequestId()));
return true;
}
default:
return false;
}
} catch (org.chromium.mojo.bindings.DeserializationException e) {
System.err.println(e.toString());
return false;
}
}
}
static final class PaymentManifestParserParsePaymentMethodManifestParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String content;
private PaymentManifestParserParsePaymentMethodManifestParams(int version) {
super(STRUCT_SIZE, version);
}
public PaymentManifestParserParsePaymentMethodManifestParams() {
this(0);
}
public static PaymentManifestParserParsePaymentMethodManifestParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static PaymentManifestParserParsePaymentMethodManifestParams deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static PaymentManifestParserParsePaymentMethodManifestParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
PaymentManifestParserParsePaymentMethodManifestParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new PaymentManifestParserParsePaymentMethodManifestParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
result.content = decoder0.readString(8, false);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(content, 8, false);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
PaymentManifestParserParsePaymentMethodManifestParams other = (PaymentManifestParserParsePaymentMethodManifestParams) object;
if (!org.chromium.mojo.bindings.BindingsHelper.equals(this.content, other.content))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(content);
return result;
}
}
static final class PaymentManifestParserParsePaymentMethodManifestResponseParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public org.chromium.url.mojom.Url[] webAppManifestUrls;
private PaymentManifestParserParsePaymentMethodManifestResponseParams(int version) {
super(STRUCT_SIZE, version);
}
public PaymentManifestParserParsePaymentMethodManifestResponseParams() {
this(0);
}
public static PaymentManifestParserParsePaymentMethodManifestResponseParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static PaymentManifestParserParsePaymentMethodManifestResponseParams deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static PaymentManifestParserParsePaymentMethodManifestResponseParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
PaymentManifestParserParsePaymentMethodManifestResponseParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new PaymentManifestParserParsePaymentMethodManifestResponseParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false);
{
org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
result.webAppManifestUrls = new org.chromium.url.mojom.Url[si1.elementsOrVersion];
for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) {
org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false);
result.webAppManifestUrls[i1] = org.chromium.url.mojom.Url.decode(decoder2);
}
}
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
if (webAppManifestUrls == null) {
encoder0.encodeNullPointer(8, false);
} else {
org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(webAppManifestUrls.length, 8, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
for (int i0 = 0; i0 < webAppManifestUrls.length; ++i0) {
encoder1.encode(webAppManifestUrls[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false);
}
}
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
PaymentManifestParserParsePaymentMethodManifestResponseParams other = (PaymentManifestParserParsePaymentMethodManifestResponseParams) object;
if (!java.util.Arrays.deepEquals(this.webAppManifestUrls, other.webAppManifestUrls))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + java.util.Arrays.deepHashCode(webAppManifestUrls);
return result;
}
}
static class PaymentManifestParserParsePaymentMethodManifestResponseParamsForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable
implements org.chromium.mojo.bindings.MessageReceiver {
private final PaymentManifestParser.ParsePaymentMethodManifestResponse mCallback;
PaymentManifestParserParsePaymentMethodManifestResponseParamsForwardToCallback(PaymentManifestParser.ParsePaymentMethodManifestResponse callback) {
this.mCallback = callback;
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(PARSE_PAYMENT_METHOD_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) {
return false;
}
PaymentManifestParserParsePaymentMethodManifestResponseParams response = PaymentManifestParserParsePaymentMethodManifestResponseParams.deserialize(messageWithHeader.getPayload());
mCallback.call(response.webAppManifestUrls);
return true;
} catch (org.chromium.mojo.bindings.DeserializationException e) {
return false;
}
}
}
static class PaymentManifestParserParsePaymentMethodManifestResponseParamsProxyToResponder implements PaymentManifestParser.ParsePaymentMethodManifestResponse {
private final org.chromium.mojo.system.Core mCore;
private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver;
private final long mRequestId;
PaymentManifestParserParsePaymentMethodManifestResponseParamsProxyToResponder(
org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiver messageReceiver,
long requestId) {
mCore = core;
mMessageReceiver = messageReceiver;
mRequestId = requestId;
}
@Override
public void call(org.chromium.url.mojom.Url[] webAppManifestUrls) {
PaymentManifestParserParsePaymentMethodManifestResponseParams _response = new PaymentManifestParserParsePaymentMethodManifestResponseParams();
_response.webAppManifestUrls = webAppManifestUrls;
org.chromium.mojo.bindings.ServiceMessage _message =
_response.serializeWithHeader(
mCore,
new org.chromium.mojo.bindings.MessageHeader(
PARSE_PAYMENT_METHOD_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG,
mRequestId));
mMessageReceiver.accept(_message);
}
}
static final class PaymentManifestParserParseWebAppManifestParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public String content;
private PaymentManifestParserParseWebAppManifestParams(int version) {
super(STRUCT_SIZE, version);
}
public PaymentManifestParserParseWebAppManifestParams() {
this(0);
}
public static PaymentManifestParserParseWebAppManifestParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static PaymentManifestParserParseWebAppManifestParams deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static PaymentManifestParserParseWebAppManifestParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
PaymentManifestParserParseWebAppManifestParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new PaymentManifestParserParseWebAppManifestParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
result.content = decoder0.readString(8, false);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(content, 8, false);
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
PaymentManifestParserParseWebAppManifestParams other = (PaymentManifestParserParseWebAppManifestParams) object;
if (!org.chromium.mojo.bindings.BindingsHelper.equals(this.content, other.content))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + org.chromium.mojo.bindings.BindingsHelper.hashCode(content);
return result;
}
}
static final class PaymentManifestParserParseWebAppManifestResponseParams extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 16;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(16, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public WebAppManifestSection[] manifest;
private PaymentManifestParserParseWebAppManifestResponseParams(int version) {
super(STRUCT_SIZE, version);
}
public PaymentManifestParserParseWebAppManifestResponseParams() {
this(0);
}
public static PaymentManifestParserParseWebAppManifestResponseParams deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static PaymentManifestParserParseWebAppManifestResponseParams deserialize(java.nio.ByteBuffer data) {
if (data == null)
return null;
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static PaymentManifestParserParseWebAppManifestResponseParams decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
PaymentManifestParserParseWebAppManifestResponseParams result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
result = new PaymentManifestParserParseWebAppManifestResponseParams(mainDataHeader.elementsOrVersion);
if (mainDataHeader.elementsOrVersion >= 0) {
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(8, false);
{
org.chromium.mojo.bindings.DataHeader si1 = decoder1.readDataHeaderForPointerArray(org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
result.manifest = new WebAppManifestSection[si1.elementsOrVersion];
for (int i1 = 0; i1 < si1.elementsOrVersion; ++i1) {
org.chromium.mojo.bindings.Decoder decoder2 = decoder1.readPointer(org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i1, false);
result.manifest[i1] = WebAppManifestSection.decode(decoder2);
}
}
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
if (manifest == null) {
encoder0.encodeNullPointer(8, false);
} else {
org.chromium.mojo.bindings.Encoder encoder1 = encoder0.encodePointerArray(manifest.length, 8, org.chromium.mojo.bindings.BindingsHelper.UNSPECIFIED_ARRAY_LENGTH);
for (int i0 = 0; i0 < manifest.length; ++i0) {
encoder1.encode(manifest[i0], org.chromium.mojo.bindings.DataHeader.HEADER_SIZE + org.chromium.mojo.bindings.BindingsHelper.POINTER_SIZE * i0, false);
}
}
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object object) {
if (object == this)
return true;
if (object == null)
return false;
if (getClass() != object.getClass())
return false;
PaymentManifestParserParseWebAppManifestResponseParams other = (PaymentManifestParserParseWebAppManifestResponseParams) object;
if (!java.util.Arrays.deepEquals(this.manifest, other.manifest))
return false;
return true;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = prime + getClass().hashCode();
result = prime * result + java.util.Arrays.deepHashCode(manifest);
return result;
}
}
static class PaymentManifestParserParseWebAppManifestResponseParamsForwardToCallback extends org.chromium.mojo.bindings.SideEffectFreeCloseable
implements org.chromium.mojo.bindings.MessageReceiver {
private final PaymentManifestParser.ParseWebAppManifestResponse mCallback;
PaymentManifestParserParseWebAppManifestResponseParamsForwardToCallback(PaymentManifestParser.ParseWebAppManifestResponse callback) {
this.mCallback = callback;
}
@Override
public boolean accept(org.chromium.mojo.bindings.Message message) {
try {
org.chromium.mojo.bindings.ServiceMessage messageWithHeader =
message.asServiceMessage();
org.chromium.mojo.bindings.MessageHeader header = messageWithHeader.getHeader();
if (!header.validateHeader(PARSE_WEB_APP_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG)) {
return false;
}
PaymentManifestParserParseWebAppManifestResponseParams response = PaymentManifestParserParseWebAppManifestResponseParams.deserialize(messageWithHeader.getPayload());
mCallback.call(response.manifest);
return true;
} catch (org.chromium.mojo.bindings.DeserializationException e) {
return false;
}
}
}
static class PaymentManifestParserParseWebAppManifestResponseParamsProxyToResponder implements PaymentManifestParser.ParseWebAppManifestResponse {
private final org.chromium.mojo.system.Core mCore;
private final org.chromium.mojo.bindings.MessageReceiver mMessageReceiver;
private final long mRequestId;
PaymentManifestParserParseWebAppManifestResponseParamsProxyToResponder(
org.chromium.mojo.system.Core core,
org.chromium.mojo.bindings.MessageReceiver messageReceiver,
long requestId) {
mCore = core;
mMessageReceiver = messageReceiver;
mRequestId = requestId;
}
@Override
public void call(WebAppManifestSection[] manifest) {
PaymentManifestParserParseWebAppManifestResponseParams _response = new PaymentManifestParserParseWebAppManifestResponseParams();
_response.manifest = manifest;
org.chromium.mojo.bindings.ServiceMessage _message =
_response.serializeWithHeader(
mCore,
new org.chromium.mojo.bindings.MessageHeader(
PARSE_WEB_APP_MANIFEST_ORDINAL,
org.chromium.mojo.bindings.MessageHeader.MESSAGE_IS_RESPONSE_FLAG,
mRequestId));
mMessageReceiver.accept(_message);
}
}
}
| |
/*
* Copyright 2012 pmp-android development team
* Project: FileSystemResourceGroup
* Project-Site: https://github.com/stachch/Privacy_Management_Platform
*
* ---------------------------------------------------------------------
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.unistuttgart.ipvs.pmp.resourcegroups.filesystem;
import android.util.Log;
import de.unistuttgart.ipvs.pmp.shared.resource.Resource;
import de.unistuttgart.ipvs.pmp.shared.resource.ResourceGroup;
import de.unistuttgart.ipvs.pmp.shared.resource.privacysetting.PrivacySettingValueException;
import de.unistuttgart.ipvs.pmp.shared.resource.privacysetting.library.BooleanPrivacySetting;
/**
* Defines all privacy settings used by the resources for accessing the file system
*
* @author Patrick Strobel
* @version 0.3.0
*
*/
public class PrivacySettings {
public static final String GENERIC_READ = "gen_r";
public static final String GENERIC_WRITE = "gen_w";
public static final String GENERIC_LIST = "gen_l";
public static final String GENERIC_DELETE = "gen_d";
public static final String GENERIC_MAKE_DIRS = "gen_mkdirs";
/**
* Privacy setting for reading all files stored on the SD-Card including files and directories controlled by the
* other
* privacy settings (e.g. data in the music directory). This means, even if <code>EXTERNAL_MUSIC_READ</code> is set
* to
* false and <code>EXTERNAL_BASE_DIR_READ</code> is enabled, the access to <code>Music/</code> is allowed.
*/
public static final String EXTERNAL_BASE_DIR_READ = "ext_base_r";
/**
* Privacy Setting for writing files everywhere on the external SD-Card.
*
* @see EXTERNAL_BASE_DIR_READ
*/
public static final String EXTERNAL_BASE_DIR_WRITE = "ext_base_w";
public static final String EXTERNAL_BASE_DIR_LIST = "ext_base_l";
public static final String EXTERNAL_BASE_DIR_DELETE = "ext_base_d";
public static final String EXTERNAL_BASE_DIR_MAKE_DIRS = "ext_base_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Music/</code> directory
*/
public static final String EXTERNAL_MUSIC_READ = "ext_music_r";
public static final String EXTERNAL_MUSIC_WRITE = "ext_music_w";
public static final String EXTERNAL_MUSIC_LIST = "ext_music_l";
public static final String EXTERNAL_MUSIC_DELETE = "ext_music_d";
public static final String EXTERNAL_MUSIC_MAKE_DIRS = "ext_music_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Podcasts/</code> directory
*/
public static final String EXTERNAL_PODCASTS_READ = "ext_podcasts_r";
public static final String EXTERNAL_PODCASTS_WRITE = "ext_podcasts_w";
public static final String EXTERNAL_PODCASTS_LIST = "ext_podcasts_l";
public static final String EXTERNAL_PODCASTS_DELETE = "ext_podcasts_d";
public static final String EXTERNAL_PODCASTS_MAKE_DIRS = "ext_podcasts_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Ringtones/</code> directory
*/
public static final String EXTERNAL_RINGTONES_READ = "ext_ringtones_r";
public static final String EXTERNAL_RINGTONES_WRITE = "ext_ringtones_w";
public static final String EXTERNAL_RINGTONES_LIST = "ext_ringtones_l";
public static final String EXTERNAL_RINGTONES_DELETE = "ext_ringtones_d";
public static final String EXTERNAL_RINGTONES_MAKE_DIRS = "ext_ringtones_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Alarms/</code> directory
*/
public static final String EXTERNAL_ALARMS_READ = "ext_alarms_r";
public static final String EXTERNAL_ALARMS_WRITE = "ext_alarms_w";
public static final String EXTERNAL_ALARMS_LIST = "ext_alarms_l";
public static final String EXTERNAL_ALARMS_DELETE = "ext_alarms_d";
public static final String EXTERNAL_ALARMS_MAKE_DIRS = "ext_alarms_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Notifications/</code> directory
*/
public static final String EXTERNAL_NOTIFICATIONS_READ = "ext_notifications_r";
public static final String EXTERNAL_NOTIFICATIONS_WRITE = "ext_notifications_w";
public static final String EXTERNAL_NOTIFICATIONS_LIST = "ext_notifications_l";
public static final String EXTERNAL_NOTIFICATIONS_DELETE = "ext_notifications_d";
public static final String EXTERNAL_NOTIFICATIONS_MAKE_DIRS = "ext_notifications_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Pictures/</code> directory
*/
public static final String EXTERNAL_PICTURES_READ = "ext_pictures_r";
public static final String EXTERNAL_PICTURES_WRITE = "ext_pictures_w";
public static final String EXTERNAL_PICTURES_LIST = "ext_pictures_l";
public static final String EXTERNAL_PICTURES_DELETE = "ext_pictures_d";
public static final String EXTERNAL_PICTURES_MAKE_DIRS = "ext_pictures_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Movies/</code> directory
*/
public static final String EXTERNAL_MOVIES_READ = "ext_movies_r";
public static final String EXTERNAL_MOVIES_WRITE = "ext_movies_w";
public static final String EXTERNAL_MOVIES_LIST = "ext_movies_l";
public static final String EXTERNAL_MOVIES_DELETE = "ext_movies_d";
public static final String EXTERNAL_MOVIES_MAKE_DIRS = "ext_movies_mkdirs";
/**
* Privacy Setting for reading all files stored in the external <code>Download/</code> directory
*/
public static final String EXTERNAL_DOWNLOAD_READ = "ext_download_r";
public static final String EXTERNAL_DOWNLOAD_WRITE = "ext_download_w";
public static final String EXTERNAL_DOWNLOAD_LIST = "ext_download_l";
public static final String EXTERNAL_DOWNLOAD_DELETE = "ext_download_d";
public static final String EXTERNAL_DOWNLOAD_MAKE_DIRS = "ext_download_mkdirs";
private ResourceGroup rg;
/**
* This creates all privacy settings for reading, writing, deleting and listing files in different locations.
*
* @throws Exception
* Thrown,
*/
public PrivacySettings(ResourceGroup rg) {
this.rg = rg;
}
/**
* Adds all generated privacy settings to a resource-group
*
* @param rg
* Resource-group to which the privacy settings should be added
*/
public void registerPrivacySettings() {
this.rg.registerPrivacySetting(GENERIC_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(GENERIC_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(GENERIC_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(GENERIC_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(GENERIC_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_BASE_DIR_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_BASE_DIR_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_BASE_DIR_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_BASE_DIR_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_BASE_DIR_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MUSIC_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MUSIC_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MUSIC_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MUSIC_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MUSIC_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PODCASTS_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PODCASTS_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PODCASTS_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PODCASTS_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PODCASTS_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_RINGTONES_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_RINGTONES_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_RINGTONES_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_RINGTONES_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_RINGTONES_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_ALARMS_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_ALARMS_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_ALARMS_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_ALARMS_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_ALARMS_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_NOTIFICATIONS_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_NOTIFICATIONS_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_NOTIFICATIONS_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_NOTIFICATIONS_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_NOTIFICATIONS_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PICTURES_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PICTURES_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PICTURES_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PICTURES_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_PICTURES_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MOVIES_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MOVIES_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MOVIES_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MOVIES_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_MOVIES_MAKE_DIRS, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_DOWNLOAD_READ, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_DOWNLOAD_WRITE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_DOWNLOAD_LIST, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_DOWNLOAD_DELETE, new BooleanPrivacySetting());
this.rg.registerPrivacySetting(EXTERNAL_DOWNLOAD_MAKE_DIRS, new BooleanPrivacySetting());
}
/**
* Checks if a specific privacy setting is set for an application
*
* @param privacySettingName
* The privacy setting to check
* @param app
* The app to check
* @param resource
* Resource
* @return True, if privacy setting is set for this application
*/
public static boolean privacySettingSet(String privacySettingName, String app, Resource resource) {
if (privacySettingName == null) {
Log.e("PrivacySettings", "Name of the privacy setting cannot be null");
return false;
}
BooleanPrivacySetting privacySetting = (BooleanPrivacySetting) resource.getPrivacySetting(privacySettingName);
try {
return privacySetting.permits(app, true);
} catch (PrivacySettingValueException e) {
e.printStackTrace();
}
return false;
}
}
| |
package org.gbif.portal.action.species;
import org.gbif.api.exception.ServiceUnavailableException;
import org.gbif.api.model.checklistbank.DatasetMetrics;
import org.gbif.api.model.checklistbank.NameUsage;
import org.gbif.api.model.checklistbank.NameUsageContainer;
import org.gbif.api.model.checklistbank.NameUsageMetrics;
import org.gbif.api.model.metrics.cube.OccurrenceCube;
import org.gbif.api.model.metrics.cube.ReadBuilder;
import org.gbif.api.model.registry.Dataset;
import org.gbif.api.model.registry.Organization;
import org.gbif.api.service.checklistbank.DatasetMetricsService;
import org.gbif.api.service.checklistbank.NameUsageService;
import org.gbif.api.service.metrics.CubeService;
import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.OrganizationService;
import org.gbif.portal.action.BaseAction;
import org.gbif.portal.exception.NotFoundException;
import org.gbif.portal.exception.ReferentialIntegrityException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UsageBaseAction extends BaseAction {
protected final Logger LOG = LoggerFactory.getLogger(getClass());
@Inject
protected NameUsageService usageService;
@Inject
protected DatasetService datasetService;
@Inject
protected DatasetMetricsService metricsService;
@Inject
protected CubeService occurrenceCubeService;
@Inject
protected OrganizationService organizationService;
protected Integer id;
protected NameUsageContainer usage;
private NameUsageMetrics usageMetrics;
protected Dataset dataset;
private Dataset constituent;
private Organization publisher;
protected DatasetMetrics metrics;
private long numOccurrences;
private long numGeoreferencedOccurrences;
protected Map<UUID, Dataset> datasets = Maps.newHashMap();
/**
* @param maxSize
* @param <T>
* @return list of a size not larger then maxSize
*/
protected static <T> List<T> sublist(List<T> list, int maxSize) {
return sublist(list, 0, maxSize);
}
/**
* @param maxSize
* @param <T>
* @return list of a size not larger then maxSize
*/
protected static <T> List<T> sublist(List<T> list, int start, int maxSize) {
if (list.size() <= maxSize) {
if (start == 0) {
return list;
}
return list.subList(start, list.size());
}
return list.subList(start, maxSize);
}
public String getChecklistName(UUID key) {
if (key != null && datasets.containsKey(key)) {
return datasets.get(key).getTitle();
}
return "";
}
public Dataset getDataset() {
return dataset;
}
public Map<UUID, Dataset> getDatasets() {
return datasets;
}
public Integer getId() {
return id;
}
public DatasetMetrics getMetrics() {
return metrics;
}
public long getNumGeoreferencedOccurrences() {
return numGeoreferencedOccurrences;
}
public long getNumOccurrences() {
return numOccurrences;
}
public NameUsageContainer getUsage() {
return usage;
}
public NameUsageMetrics getUsageMetrics() {
return usageMetrics;
}
public boolean isNub() {
return usage.isNub();
}
/**
* Loads a name usage and its checklist by the id parameter.
*
* @throws NotFoundException if no usage for the given id can be found
*/
public void loadUsage() {
if (id == null) {
throw new NotFoundException("No checklist usage id given");
}
NameUsage u = usageService.get(id, getLocale());
if (u == null) {
throw new NotFoundException("No usage found with id " + id);
}
usage = new NameUsageContainer(u);
usageMetrics = usageService.getMetrics(id);
// make sure we got an empty one at least - its all ints and its references from lots of templates
if (usageMetrics == null) {
usageMetrics = new NameUsageMetrics();
usageMetrics.setKey(id);
}
// load checklist
dataset = datasetService.get(usage.getDatasetKey());
if (dataset == null) {
throw new ReferentialIntegrityException(NameUsage.class, id, "Missing dataset " + usage.getDatasetKey());
}
// load constituent dataset too if we have one
if (usage.getConstituentKey() != null) {
constituent = datasetService.get(usage.getConstituentKey());
}
// load publisher
publisher = organizationService.get(dataset.getPublishingOrganizationKey());
try {
metrics = metricsService.get(usage.getDatasetKey());
} catch (ServiceUnavailableException e) {
LOG.error("Failed to load checklist metrics for dataset {}", usage.getDatasetKey());
}
try {
numOccurrences = occurrenceCubeService.get(new ReadBuilder()
.at(OccurrenceCube.TAXON_KEY, usage.getKey()));
numGeoreferencedOccurrences = occurrenceCubeService.get(new ReadBuilder()
.at(OccurrenceCube.TAXON_KEY, usage.getKey())
.at(OccurrenceCube.IS_GEOREFERENCED, true));
} catch (ServiceUnavailableException e) {
LOG.error("Failed to load occurrence metrics for usage {}", usage.getKey(), e);
}
}
public void setId(Integer id) {
this.id = id;
}
/**
* Populates the checklists map with the checklists for the given keys.
* The method does not remove existing entries and can be called many times to add additional, new checklists.
*/
protected void loadChecklists(Collection<UUID> checklistKeys) {
for (UUID u : checklistKeys) {
loadDataset(u);
}
}
protected void loadDataset(UUID datasetKey) {
if (datasetKey != null && !datasets.containsKey(datasetKey)) {
try {
datasets.put(datasetKey, datasetService.get(datasetKey));
} catch (ServiceUnavailableException e) {
LOG.error("Failed to load dataset with key {}", datasetKey);
datasets.put(datasetKey, null);
}
}
}
public Dataset getConstituent() {
return constituent;
}
public Organization getPublisher() {
return publisher;
}
}
| |
package com.abewy.android.apps.klyph.core.graph;
import java.util.ArrayList;
public class Application extends GraphObject
{
private String id;
private String name;
private String description;
private String category;
private String company;
private String icon_url;
private String subcategory;
private String link;
private String logo_url;
private String daily_active_users;
private String weekly_active_users;
private String monthly_active_users;
private ArrayList<Object> migration;
private String namespace;
// private Restrictions restrictions;
private ArrayList<Object> app_domains;
private String auth_dialog_data_help_url;
private String auth_dialog_description;
private String auth_dialog_headline;
private String auth_dialog_perms_explanation;
private ArrayList<String> auth_referal_user_perms;
private ArrayList<String> auth_referal_friend_perms;
private String auth_referal_default_activity_privacy;
private boolean auth_referal_enabled;
private ArrayList<String> auth_referal_extended_perms;
private String auth_referal_response_type;
private boolean canvas_fluid_height;
private boolean canvas_fluid_width;
private String canvas_fluid_url;
private String contact_email;
private int created_time;
private int creator_uid;
private String deauth_callback_url;
private String iphone_app_store_id;
private String hosting_url;
private String mobile_web_url;
private String page_tab_default_name;
private String page_tab_url;
private String privacy_policy_url;
private String secure_canvas_url;
private String secure_page_tab_url;
private String server_ip_whitelist;
private boolean social_discovery;
private String terms_of_service_url;
private String user_support_email;
private String user_support_url;
private String website_url;
public Application()
{
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getCategory()
{
return category;
}
public void setCategory(String category)
{
this.category = category;
}
public String getCompany()
{
return company;
}
public void setCompany(String company)
{
this.company = company;
}
public String getIcon_url()
{
return icon_url;
}
public void setIcon_url(String icon_url)
{
this.icon_url = icon_url;
}
public String getSubcategory()
{
return subcategory;
}
public void setSubcategory(String subcategory)
{
this.subcategory = subcategory;
}
public String getLink()
{
return link;
}
public void setLink(String link)
{
this.link = link;
}
public String getLogo_url()
{
return logo_url;
}
public void setLogo_url(String logo_url)
{
this.logo_url = logo_url;
}
public String getDaily_active_users()
{
return daily_active_users;
}
public void setDaily_active_users(String daily_active_users)
{
this.daily_active_users = daily_active_users;
}
public String getWeekly_active_users()
{
return weekly_active_users;
}
public void setWeekly_active_users(String weekly_active_users)
{
this.weekly_active_users = weekly_active_users;
}
public String getMonthly_active_users()
{
return monthly_active_users;
}
public void setMonthly_active_users(String monthly_active_users)
{
this.monthly_active_users = monthly_active_users;
}
public ArrayList<Object> getMigration()
{
return migration;
}
public void setMigration(ArrayList<Object> migration)
{
this.migration = migration;
}
public String getNamespace()
{
return namespace;
}
public void setNamespace(String namespace)
{
this.namespace = namespace;
}
public ArrayList<Object> getApp_domains()
{
return app_domains;
}
public void setApp_domains(ArrayList<Object> app_domains)
{
this.app_domains = app_domains;
}
public String getAuth_dialog_data_help_url()
{
return auth_dialog_data_help_url;
}
public void setAuth_dialog_data_help_url(String auth_dialog_data_help_url)
{
this.auth_dialog_data_help_url = auth_dialog_data_help_url;
}
public String getAuth_dialog_description()
{
return auth_dialog_description;
}
public void setAuth_dialog_description(String auth_dialog_description)
{
this.auth_dialog_description = auth_dialog_description;
}
public String getAuth_dialog_headline()
{
return auth_dialog_headline;
}
public void setAuth_dialog_headline(String auth_dialog_headline)
{
this.auth_dialog_headline = auth_dialog_headline;
}
public String getAuth_dialog_perms_explanation()
{
return auth_dialog_perms_explanation;
}
public void setAuth_dialog_perms_explanation(
String auth_dialog_perms_explanation)
{
this.auth_dialog_perms_explanation = auth_dialog_perms_explanation;
}
public ArrayList<String> getAuth_referal_user_perms()
{
return auth_referal_user_perms;
}
public void setAuth_referal_user_perms(ArrayList<String> auth_referal_user_perms)
{
this.auth_referal_user_perms = auth_referal_user_perms;
}
public ArrayList<String> getAuth_referal_friend_perms()
{
return auth_referal_friend_perms;
}
public void setAuth_referal_friend_perms(
ArrayList<String> auth_referal_friend_perms)
{
this.auth_referal_friend_perms = auth_referal_friend_perms;
}
public String getAuth_referal_default_activity_privacy()
{
return auth_referal_default_activity_privacy;
}
public void setAuth_referal_default_activity_privacy(
String auth_referal_default_activity_privacy)
{
this.auth_referal_default_activity_privacy = auth_referal_default_activity_privacy;
}
public boolean getAuth_referal_enabled()
{
return auth_referal_enabled;
}
public void setAuth_referal_enabled(boolean auth_referal_enabled)
{
this.auth_referal_enabled = auth_referal_enabled;
}
public ArrayList<String> getAuth_referal_extended_perms()
{
return auth_referal_extended_perms;
}
public void setAuth_referal_extended_perms(
ArrayList<String> auth_referal_extended_perms)
{
this.auth_referal_extended_perms = auth_referal_extended_perms;
}
public String getAuth_referal_response_type()
{
return auth_referal_response_type;
}
public void setAuth_referal_response_type(String auth_referal_response_type)
{
this.auth_referal_response_type = auth_referal_response_type;
}
public boolean getCanvas_fluid_height()
{
return canvas_fluid_height;
}
public void setCanvas_fluid_height(boolean canvas_fluid_height)
{
this.canvas_fluid_height = canvas_fluid_height;
}
public boolean getCanvas_fluid_width()
{
return canvas_fluid_width;
}
public void setCanvas_fluid_width(boolean canvas_fluid_width)
{
this.canvas_fluid_width = canvas_fluid_width;
}
public String getCanvas_fluid_url()
{
return canvas_fluid_url;
}
public void setCanvas_fluid_url(String canvas_fluid_url)
{
this.canvas_fluid_url = canvas_fluid_url;
}
public String getContact_email()
{
return contact_email;
}
public void setContact_email(String contact_email)
{
this.contact_email = contact_email;
}
public int getCreated_time()
{
return created_time;
}
public void setCreated_time(int created_time)
{
this.created_time = created_time;
}
public int getCreator_uid()
{
return creator_uid;
}
public void setCreator_uid(int creator_uid)
{
this.creator_uid = creator_uid;
}
public String getDeauth_callback_url()
{
return deauth_callback_url;
}
public void setDeauth_callback_url(String deauth_callback_url)
{
this.deauth_callback_url = deauth_callback_url;
}
public String getIphone_app_store_id()
{
return iphone_app_store_id;
}
public void setIphone_app_store_id(String iphone_app_store_id)
{
this.iphone_app_store_id = iphone_app_store_id;
}
public String getHosting_url()
{
return hosting_url;
}
public void setHosting_url(String hosting_url)
{
this.hosting_url = hosting_url;
}
public String getMobile_web_url()
{
return mobile_web_url;
}
public void setMobile_web_url(String mobile_web_url)
{
this.mobile_web_url = mobile_web_url;
}
public String getPage_tab_default_name()
{
return page_tab_default_name;
}
public void setPage_tab_default_name(String page_tab_default_name)
{
this.page_tab_default_name = page_tab_default_name;
}
public String getPage_tab_url()
{
return page_tab_url;
}
public void setPage_tab_url(String page_tab_url)
{
this.page_tab_url = page_tab_url;
}
public String getPrivacy_policy_url()
{
return privacy_policy_url;
}
public void setPrivacy_policy_url(String privacy_policy_url)
{
this.privacy_policy_url = privacy_policy_url;
}
public String getSecure_canvas_url()
{
return secure_canvas_url;
}
public void setSecure_canvas_url(String secure_canvas_url)
{
this.secure_canvas_url = secure_canvas_url;
}
public String getSecure_page_tab_url()
{
return secure_page_tab_url;
}
public void setSecure_page_tab_url(String secure_page_tab_url)
{
this.secure_page_tab_url = secure_page_tab_url;
}
public String getServer_ip_whitelist()
{
return server_ip_whitelist;
}
public void setServer_ip_whitelist(String server_ip_whitelist)
{
this.server_ip_whitelist = server_ip_whitelist;
}
public boolean getSocial_discovery()
{
return social_discovery;
}
public void setSocial_discovery(boolean social_discovery)
{
this.social_discovery = social_discovery;
}
public String getTerms_of_service_url()
{
return terms_of_service_url;
}
public void setTerms_of_service_url(String terms_of_service_url)
{
this.terms_of_service_url = terms_of_service_url;
}
public String getUser_support_email()
{
return user_support_email;
}
public void setUser_support_email(String user_support_email)
{
this.user_support_email = user_support_email;
}
public String getUser_support_url()
{
return user_support_url;
}
public void setUser_support_url(String user_support_url)
{
this.user_support_url = user_support_url;
}
public String getWebsite_url()
{
return website_url;
}
public void setWebsite_url(String website_url)
{
this.website_url = website_url;
}
}
| |
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.openqa.selenium;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.environment.DomainHelper;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.JUnit4TestBase;
import org.openqa.selenium.testing.JavascriptEnabled;
import org.openqa.selenium.testing.NotYetImplemented;
import java.net.URI;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.openqa.selenium.testing.Ignore.Driver.ALL;
import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX;
import static org.openqa.selenium.testing.Ignore.Driver.HTMLUNIT;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE;
import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS;
import static org.openqa.selenium.testing.Ignore.Driver.REMOTE;
import static org.openqa.selenium.testing.Ignore.Driver.SAFARI;
public class CookieImplementationTest extends JUnit4TestBase {
private DomainHelper domainHelper;
private String cookiePage;
private static final Random random = new Random();
@Before
public void setUp() throws Exception {
domainHelper = new DomainHelper(appServer);
assumeTrue(domainHelper.checkIsOnValidHostname());
cookiePage = domainHelper.getUrlForFirstValidHostname("/common/cookie");
deleteAllCookiesOnServerSide();
// This page is the deepest page we go to in the cookie tests
// We go to it to ensure that cookies with /common/... paths are deleted
// Do not write test in this class which use pages other than under /common
// without ensuring that cookies are deleted on those pages as required
try {
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
} catch (IllegalArgumentException e) {
// Ideally we would throw an IgnoredTestError or something here,
// but our test runner doesn't pay attention to those.
// Rely on the tests skipping themselves if they need to be on a useful page.
return;
}
driver.manage().deleteAllCookies();
assertNoCookiesArePresent();
}
@JavascriptEnabled
@Test
public void testShouldGetCookieByName() {
String key = generateUniqueKey();
String value = "set";
assertCookieIsNotPresentWithName(key);
addCookieOnServerSide(new Cookie(key, value));
Cookie cookie = driver.manage().getCookieNamed(key);
assertEquals(value, cookie.getValue());
}
@JavascriptEnabled
@Test
public void testShouldBeAbleToAddCookie() {
String key = generateUniqueKey();
String value = "foo";
Cookie cookie = new Cookie.Builder(key, value).build();
assertCookieIsNotPresentWithName(key);
driver.manage().addCookie(cookie);
assertCookieHasValue(key, value);
openAnotherPage();
assertCookieHasValue(key, value);
}
@Test
public void testGetAllCookies() {
String key1 = generateUniqueKey();
String key2 = generateUniqueKey();
assertCookieIsNotPresentWithName(key1);
assertCookieIsNotPresentWithName(key2);
Set<Cookie> cookies = driver.manage().getCookies();
int countBefore = cookies.size();
Cookie one = new Cookie.Builder(key1, "value").build();
Cookie two = new Cookie.Builder(key2, "value").build();
driver.manage().addCookie(one);
driver.manage().addCookie(two);
openAnotherPage();
cookies = driver.manage().getCookies();
assertEquals(countBefore + 2, cookies.size());
assertTrue(cookies.contains(one));
assertTrue(cookies.contains(two));
}
@JavascriptEnabled
@Test
public void testDeleteAllCookies() {
addCookieOnServerSide(new Cookie("foo", "set"));
assertSomeCookiesArePresent();
driver.manage().deleteAllCookies();
assertNoCookiesArePresent();
openAnotherPage();
assertNoCookiesArePresent();
}
@JavascriptEnabled
@Test
public void testDeleteCookieWithName() {
String key1 = generateUniqueKey();
String key2 = generateUniqueKey();
addCookieOnServerSide(new Cookie(key1, "set"));
addCookieOnServerSide(new Cookie(key2, "set"));
assertCookieIsPresentWithName(key1);
assertCookieIsPresentWithName(key2);
driver.manage().deleteCookieNamed(key1);
assertCookieIsNotPresentWithName(key1);
assertCookieIsPresentWithName(key2);
openAnotherPage();
assertCookieIsNotPresentWithName(key1);
assertCookieIsPresentWithName(key2);
}
@Test
public void testShouldNotDeleteCookiesWithASimilarName() {
String cookieOneName = "fish";
Cookie cookie1 = new Cookie.Builder(cookieOneName, "cod").build();
Cookie cookie2 = new Cookie.Builder(cookieOneName + "x", "earth").build();
WebDriver.Options options = driver.manage();
assertCookieIsNotPresentWithName(cookie1.getName());
options.addCookie(cookie1);
options.addCookie(cookie2);
assertCookieIsPresentWithName(cookie1.getName());
options.deleteCookieNamed(cookieOneName);
Set<Cookie> cookies = options.getCookies();
assertFalse(cookies.toString(), cookies.contains(cookie1));
assertTrue(cookies.toString(), cookies.contains(cookie2));
}
@Test
public void testAddCookiesWithDifferentPathsThatAreRelatedToOurs() {
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
Cookie cookie1 = new Cookie.Builder("fish", "cod").path("/common/animals").build();
Cookie cookie2 = new Cookie.Builder("planet", "earth").path("/common/").build();
WebDriver.Options options = driver.manage();
options.addCookie(cookie1);
options.addCookie(cookie2);
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
assertCookieIsPresentWithName(cookie1.getName());
assertCookieIsPresentWithName(cookie2.getName());
driver.get(domainHelper.getUrlForFirstValidHostname("/common/simpleTest.html"));
assertCookieIsNotPresentWithName(cookie1.getName());
}
@Ignore(value = {CHROME, PHANTOMJS, SAFARI})
@NoDriverAfterTest // So that next test never starts with "inside a frame" base state.
@Test
public void testGetCookiesInAFrame() {
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
Cookie cookie1 = new Cookie.Builder("fish", "cod").path("/common/animals").build();
driver.manage().addCookie(cookie1);
driver.get(domainHelper.getUrlForFirstValidHostname("frameWithAnimals.html"));
assertCookieIsNotPresentWithName(cookie1.getName());
driver.switchTo().frame("iframe1");
assertCookieIsPresentWithName(cookie1.getName());
}
@Ignore({CHROME})
@Test
public void testCannotGetCookiesWithPathDifferingOnlyInCase() {
String cookieName = "fish";
Cookie cookie = new Cookie.Builder(cookieName, "cod").path("/Common/animals").build();
driver.manage().addCookie(cookie);
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
assertNull(driver.manage().getCookieNamed(cookieName));
}
@Test
@Ignore(MARIONETTE)
public void testShouldNotGetCookieOnDifferentDomain() {
assumeTrue(domainHelper.checkHasValidAlternateHostname());
String cookieName = "fish";
driver.manage().addCookie(new Cookie.Builder(cookieName, "cod").build());
assertCookieIsPresentWithName(cookieName);
driver.get(domainHelper.getUrlForSecondValidHostname("simpleTest.html"));
assertCookieIsNotPresentWithName(cookieName);
}
@Ignore(value = {CHROME})
@Test
public void testShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain() {
String cookieName = "name";
assertCookieIsNotPresentWithName(cookieName);
String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", ".");
Cookie cookie = new Cookie.Builder(cookieName, "value").domain(shorter).build();
driver.manage().addCookie(cookie);
assertCookieIsPresentWithName(cookieName);
}
@Ignore(value = {ALL})
@Test
public void testsShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod() {
String cookieName = "name";
assertCookieIsNotPresentWithName(cookieName);
String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", "");
Cookie cookie = new Cookie.Builder(cookieName, "value").domain(shorter).build();
driver.manage().addCookie(cookie);
assertCookieIsNotPresentWithName(cookieName);
}
@Ignore({REMOTE})
@Test
public void testShouldBeAbleToIncludeLeadingPeriodInDomainName() throws Exception {
String cookieName = "name";
assertCookieIsNotPresentWithName(cookieName);
String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", ".");
Cookie cookie = new Cookie.Builder("name", "value").domain(shorter).build();
driver.manage().addCookie(cookie);
assertCookieIsPresentWithName(cookieName);
}
@Test
public void testShouldBeAbleToSetDomainToTheCurrentDomain() throws Exception {
URI url = new URI(driver.getCurrentUrl());
String host = url.getHost() + ":" + url.getPort();
Cookie cookie = new Cookie.Builder("fish", "cod").domain(host).build();
driver.manage().addCookie(cookie);
driver.get(domainHelper.getUrlForFirstValidHostname("javascriptPage.html"));
Set<Cookie> cookies = driver.manage().getCookies();
assertTrue(cookies.contains(cookie));
}
@Test
public void testShouldWalkThePathToDeleteACookie() {
Cookie cookie1 = new Cookie.Builder("fish", "cod").build();
driver.manage().addCookie(cookie1);
driver.get(domainHelper.getUrlForFirstValidHostname("child/childPage.html"));
Cookie cookie2 = new Cookie("rodent", "hamster", "/common/child");
driver.manage().addCookie(cookie2);
driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));
Cookie cookie3 = new Cookie("dog", "dalmation", "/common/child/grandchild/");
driver.manage().addCookie(cookie3);
driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));
driver.manage().deleteCookieNamed("rodent");
assertNull(driver.manage().getCookies().toString(), driver.manage().getCookieNamed("rodent"));
Set<Cookie> cookies = driver.manage().getCookies();
assertEquals(2, cookies.size());
assertTrue(cookies.contains(cookie1));
assertTrue(cookies.contains(cookie3));
driver.manage().deleteAllCookies();
driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));
assertNoCookiesArePresent();
}
@Test
public void testShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie() throws Exception {
URI uri = new URI(driver.getCurrentUrl());
String host = String.format("%s:%d", uri.getHost(), uri.getPort());
String cookieName = "name";
assertCookieIsNotPresentWithName(cookieName);
Cookie cookie = new Cookie.Builder(cookieName, "value").domain(host).build();
driver.manage().addCookie(cookie);
assertCookieIsPresentWithName(cookieName);
}
@Test
public void testCookieEqualityAfterSetAndGet() {
driver.get(domainHelper.getUrlForFirstValidHostname("animals"));
driver.manage().deleteAllCookies();
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.expiresOn(someTimeInTheFuture())
.build();
driver.manage().addCookie(addedCookie);
Set<Cookie> cookies = driver.manage().getCookies();
Cookie retrievedCookie = null;
for (Cookie temp : cookies) {
if (addedCookie.equals(temp)) {
retrievedCookie = temp;
break;
}
}
assertNotNull("Cookie was null", retrievedCookie);
// Cookie.equals only compares name, domain and path
assertEquals(addedCookie, retrievedCookie);
}
@Test
@Ignore(MARIONETTE)
public void testRetainsCookieExpiry() {
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.expiresOn(someTimeInTheFuture())
.build();
driver.manage().addCookie(addedCookie);
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull(retrieved);
assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());
}
@Ignore(value = {IE, PHANTOMJS, SAFARI, MARIONETTE})
@Test
public void canHandleSecureCookie() {
driver.get(domainHelper.getSecureUrlForFirstValidHostname("animals"));
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.isSecure(true)
.build();
driver.manage().addCookie(addedCookie);
driver.navigate().refresh();
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull(retrieved);
}
@Ignore(value = {IE, PHANTOMJS, SAFARI, MARIONETTE})
@Test
public void testRetainsCookieSecure() {
driver.get(domainHelper.getSecureUrlForFirstValidHostname("animals"));
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.isSecure(true)
.build();
driver.manage().addCookie(addedCookie);
driver.navigate().refresh();
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull(retrieved);
assertTrue(retrieved.isSecure());
}
@Ignore(SAFARI)
@Test
public void canHandleHttpOnlyCookie() {
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.isHttpOnly(true)
.build();
addCookieOnServerSide(addedCookie);
driver.get(domainHelper.getUrlForFirstValidHostname("animals"));
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull(retrieved);
}
@Ignore(reason = "Needs jetty upgrade (servlet api 3)")
@Test
public void testRetainsHttpOnlyFlag() {
Cookie addedCookie =
new Cookie.Builder("fish", "cod")
.path("/common/animals")
.isHttpOnly(true)
.build();
addCookieOnServerSide(addedCookie);
driver.get(domainHelper.getUrlForFirstValidHostname("animals"));
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull(retrieved);
assertTrue(retrieved.isHttpOnly());
}
@Test
public void testSettingACookieThatExpiredInThePast() {
long expires = System.currentTimeMillis() - 1000;
Cookie cookie = new Cookie.Builder("expired", "yes").expiresOn(new Date(expires)).build();
driver.manage().addCookie(cookie);
cookie = driver.manage().getCookieNamed("fish");
assertNull(
"Cookie expired before it was set, so nothing should be returned: " + cookie, cookie);
}
@Test
public void testCanSetCookieWithoutOptionalFieldsSet() {
String key = generateUniqueKey();
String value = "foo";
Cookie cookie = new Cookie(key, value);
assertCookieIsNotPresentWithName(key);
driver.manage().addCookie(cookie);
assertCookieHasValue(key, value);
}
@Test
public void testDeleteNotExistedCookie() {
String key = generateUniqueKey();
assertCookieIsNotPresentWithName(key);
driver.manage().deleteCookieNamed(key);
}
@Ignore(value = {CHROME, FIREFOX, IE, PHANTOMJS, SAFARI, MARIONETTE})
@Test
public void testShouldDeleteOneOfTheCookiesWithTheSameName() {
driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));
Cookie cookie1 = new Cookie.Builder("fish", "cod")
.domain(domainHelper.getHostName()).path("/common/animals").build();
Cookie cookie2 = new Cookie.Builder("fish", "tune")
.domain(domainHelper.getHostName()).path("/common/").build();
WebDriver.Options options = driver.manage();
options.addCookie(cookie1);
options.addCookie(cookie2);
assertEquals(driver.manage().getCookies().size(), 2);
driver.manage().deleteCookie(cookie1);
assertEquals(driver.manage().getCookies().size(), 1);
Cookie retrieved = driver.manage().getCookieNamed("fish");
assertNotNull("Cookie was null", retrieved);
assertEquals(cookie2, retrieved);
}
private String generateUniqueKey() {
return String.format("key_%d", random.nextInt());
}
private void assertNoCookiesArePresent() {
Set<Cookie> cookies = driver.manage().getCookies();
assertTrue("Cookies were not empty, present: " + cookies,
cookies.isEmpty());
String documentCookie = getDocumentCookieOrNull();
if (documentCookie != null) {
assertEquals("Cookies were not empty", "", documentCookie);
}
}
private void assertSomeCookiesArePresent() {
assertFalse("Cookies were empty",
driver.manage().getCookies().isEmpty());
String documentCookie = getDocumentCookieOrNull();
if (documentCookie != null) {
assertNotSame("Cookies were empty", "", documentCookie);
}
}
private void assertCookieIsNotPresentWithName(final String key) {
assertNull("Cookie was present with name " + key, driver.manage().getCookieNamed(key));
String documentCookie = getDocumentCookieOrNull();
if (documentCookie != null) {
assertThat("Cookie was present with name " + key,
documentCookie,
not(containsString(key + "=")));
}
}
private void assertCookieIsPresentWithName(final String key) {
assertNotNull("Cookie was not present with name " + key, driver.manage().getCookieNamed(key));
String documentCookie = getDocumentCookieOrNull();
if (documentCookie != null) {
assertThat("Cookie was not present with name " + key + ", got: " + documentCookie,
documentCookie,
containsString(key + "="));
}
}
private void assertCookieHasValue(final String key, final String value) {
assertEquals("Cookie had wrong value",
value,
driver.manage().getCookieNamed(key).getValue());
String documentCookie = getDocumentCookieOrNull();
if (documentCookie != null) {
assertThat("Cookie was present with name " + key,
documentCookie,
containsString(key + "=" + value));
}
}
private String getDocumentCookieOrNull() {
if (!(driver instanceof JavascriptExecutor)) {
return null;
}
try {
return (String) ((JavascriptExecutor) driver).executeScript("return document.cookie");
} catch (UnsupportedOperationException e) {
return null;
}
}
private Date someTimeInTheFuture() {
return new Date(System.currentTimeMillis() + 100000);
}
private void openAnotherPage() {
driver.get(domainHelper.getUrlForFirstValidHostname("simpleTest.html"));
}
private void deleteAllCookiesOnServerSide() {
driver.get(cookiePage + "?action=deleteAll");
}
private void addCookieOnServerSide(Cookie cookie) {
StringBuilder url = new StringBuilder(cookiePage);
url.append("?action=add");
url.append("&name=").append(cookie.getName());
url.append("&value=").append(cookie.getValue());
if (cookie.getDomain() != null) {
url.append("&domain=").append(cookie.getDomain());
}
if (cookie.getPath() != null) {
url.append("&path=").append(cookie.getPath());
}
if (cookie.getExpiry() != null) {
url.append("&expiry=").append(cookie.getExpiry().getTime());
}
if (cookie.isSecure()) {
url.append("&secure=").append(cookie.isSecure());
}
if (cookie.isHttpOnly()) {
url.append("&httpOnly=").append(cookie.isHttpOnly());
}
driver.get(url.toString());
}
@Test
@Ignore(MARIONETTE)
public void deleteAllCookies() throws Exception {
assumeTrue(domainHelper.checkHasValidAlternateHostname());
Cookie cookie1 = new Cookie.Builder("fish1", "cod")
.domain(appServer.getHostName()).build();
Cookie cookie2 = new Cookie.Builder("fish2", "tune")
.domain(appServer.getAlternateHostName()).build();
String url1 = domainHelper.getUrlForFirstValidHostname("/common");
String url2 = domainHelper.getUrlForSecondValidHostname("/common");
WebDriver.Options options = driver.manage();
options.addCookie(cookie1);
assertCookieIsPresentWithName(cookie1.getName());
driver.get(url2);
options.addCookie(cookie2);
assertCookieIsNotPresentWithName(cookie1.getName());
assertCookieIsPresentWithName(cookie2.getName());
driver.get(url1);
assertCookieIsPresentWithName(cookie1.getName());
assertCookieIsNotPresentWithName(cookie2.getName());
options.deleteAllCookies();
assertCookieIsNotPresentWithName(cookie1.getName());
driver.get(url2);
assertCookieIsPresentWithName(cookie2.getName());
}
}
| |
package org.bouncycastle.x509;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.TBSCertificate;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator;
import org.bouncycastle.asn1.x509.X509ExtensionsGenerator;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.X509Principal;
import org.bouncycastle.jce.provider.X509CertificateObject;
import org.bouncycastle.x509.extension.X509ExtensionUtil;
/**
* class to produce an X.509 Version 3 certificate.
* @deprecated use org.bouncycastle.cert.X509v3CertificateBuilder.
*/
public class X509V3CertificateGenerator
{
private V3TBSCertificateGenerator tbsGen;
private ASN1ObjectIdentifier sigOID;
private AlgorithmIdentifier sigAlgId;
private String signatureAlgorithm;
private X509ExtensionsGenerator extGenerator;
public X509V3CertificateGenerator()
{
tbsGen = new V3TBSCertificateGenerator();
extGenerator = new X509ExtensionsGenerator();
}
/**
* reset the generator
*/
public void reset()
{
tbsGen = new V3TBSCertificateGenerator();
extGenerator.reset();
}
/**
* set the serial number for the certificate.
*/
public void setSerialNumber(
BigInteger serialNumber)
{
if (serialNumber.compareTo(BigInteger.ZERO) <= 0)
{
throw new IllegalArgumentException("serial number must be a positive integer");
}
tbsGen.setSerialNumber(new ASN1Integer(serialNumber));
}
/**
* Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
* certificate.
*/
public void setIssuerDN(
X500Principal issuer)
{
try
{
tbsGen.setIssuer(new X509Principal(issuer.getEncoded()));
}
catch (IOException e)
{
throw new IllegalArgumentException("can't process principal: " + e);
}
}
/**
* Set the issuer distinguished name - the issuer is the entity whose private key is used to sign the
* certificate.
*/
public void setIssuerDN(
X509Name issuer)
{
tbsGen.setIssuer(issuer);
}
public void setNotBefore(
Date date)
{
tbsGen.setStartDate(new Time(date));
}
public void setNotAfter(
Date date)
{
tbsGen.setEndDate(new Time(date));
}
/**
* Set the subject distinguished name. The subject describes the entity associated with the public key.
*/
public void setSubjectDN(
X500Principal subject)
{
try
{
tbsGen.setSubject(new X509Principal(subject.getEncoded()));
}
catch (IOException e)
{
throw new IllegalArgumentException("can't process principal: " + e);
}
}
/**
* Set the subject distinguished name. The subject describes the entity associated with the public key.
*/
public void setSubjectDN(
X509Name subject)
{
tbsGen.setSubject(subject);
}
public void setPublicKey(
PublicKey key)
throws IllegalArgumentException
{
try
{
tbsGen.setSubjectPublicKeyInfo(
SubjectPublicKeyInfo.getInstance(new ASN1InputStream(key.getEncoded()).readObject()));
}
catch (Exception e)
{
throw new IllegalArgumentException("unable to process key - " + e.toString());
}
}
/**
* Set the signature algorithm. This can be either a name or an OID, names
* are treated as case insensitive.
*
* @param signatureAlgorithm string representation of the algorithm name.
*/
public void setSignatureAlgorithm(
String signatureAlgorithm)
{
this.signatureAlgorithm = signatureAlgorithm;
try
{
sigOID = X509Util.getAlgorithmOID(signatureAlgorithm);
}
catch (Exception e)
{
throw new IllegalArgumentException("Unknown signature type requested: " + signatureAlgorithm);
}
sigAlgId = X509Util.getSigAlgID(sigOID, signatureAlgorithm);
tbsGen.setSignature(sigAlgId);
}
/**
* Set the subject unique ID - note: it is very rare that it is correct to do this.
*/
public void setSubjectUniqueID(boolean[] uniqueID)
{
tbsGen.setSubjectUniqueID(booleanToBitString(uniqueID));
}
/**
* Set the issuer unique ID - note: it is very rare that it is correct to do this.
*/
public void setIssuerUniqueID(boolean[] uniqueID)
{
tbsGen.setIssuerUniqueID(booleanToBitString(uniqueID));
}
private DERBitString booleanToBitString(boolean[] id)
{
byte[] bytes = new byte[(id.length + 7) / 8];
for (int i = 0; i != id.length; i++)
{
bytes[i / 8] |= (id[i]) ? (1 << ((7 - (i % 8)))) : 0;
}
int pad = id.length % 8;
if (pad == 0)
{
return new DERBitString(bytes);
}
else
{
return new DERBitString(bytes, 8 - pad);
}
}
/**
* add a given extension field for the standard extensions tag (tag 3)
*/
public void addExtension(
String oid,
boolean critical,
ASN1Encodable value)
{
this.addExtension(new ASN1ObjectIdentifier(oid), critical, value);
}
/**
* add a given extension field for the standard extensions tag (tag 3)
*/
public void addExtension(
ASN1ObjectIdentifier oid,
boolean critical,
ASN1Encodable value)
{
extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value);
}
/**
* add a given extension field for the standard extensions tag (tag 3)
* The value parameter becomes the contents of the octet string associated
* with the extension.
*/
public void addExtension(
String oid,
boolean critical,
byte[] value)
{
this.addExtension(new ASN1ObjectIdentifier(oid), critical, value);
}
/**
* add a given extension field for the standard extensions tag (tag 3)
*/
public void addExtension(
ASN1ObjectIdentifier oid,
boolean critical,
byte[] value)
{
extGenerator.addExtension(new ASN1ObjectIdentifier(oid.getId()), critical, value);
}
/**
* add a given extension field for the standard extensions tag (tag 3)
* copying the extension value from another certificate.
* @throws CertificateParsingException if the extension cannot be extracted.
*/
public void copyAndAddExtension(
String oid,
boolean critical,
X509Certificate cert)
throws CertificateParsingException
{
byte[] extValue = cert.getExtensionValue(oid);
if (extValue == null)
{
throw new CertificateParsingException("extension " + oid + " not present");
}
try
{
ASN1Encodable value = X509ExtensionUtil.fromExtensionValue(extValue);
this.addExtension(oid, critical, value);
}
catch (IOException e)
{
throw new CertificateParsingException(e.toString());
}
}
/**
* add a given extension field for the standard extensions tag (tag 3)
* copying the extension value from another certificate.
* @throws CertificateParsingException if the extension cannot be extracted.
*/
public void copyAndAddExtension(
ASN1ObjectIdentifier oid,
boolean critical,
X509Certificate cert)
throws CertificateParsingException
{
this.copyAndAddExtension(oid.getId(), critical, cert);
}
/**
* generate an X509 certificate, based on the current issuer and subject
* using the default provider "BC".
* @deprecated use generate(key, "BC")
*/
public X509Certificate generateX509Certificate(
PrivateKey key)
throws SecurityException, SignatureException, InvalidKeyException
{
try
{
return generateX509Certificate(key, "BC", null);
}
catch (NoSuchProviderException e)
{
throw new SecurityException("BC provider not installed!");
}
}
/**
* generate an X509 certificate, based on the current issuer and subject
* using the default provider "BC", and the passed in source of randomness
* (if required).
* @deprecated use generate(key, random, "BC")
*/
public X509Certificate generateX509Certificate(
PrivateKey key,
SecureRandom random)
throws SecurityException, SignatureException, InvalidKeyException
{
try
{
return generateX509Certificate(key, "BC", random);
}
catch (NoSuchProviderException e)
{
throw new SecurityException("BC provider not installed!");
}
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing.
* @deprecated use generate()
*/
public X509Certificate generateX509Certificate(
PrivateKey key,
String provider)
throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
return generateX509Certificate(key, provider, null);
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing and the supplied source
* of randomness, if required.
* @deprecated use generate()
*/
public X509Certificate generateX509Certificate(
PrivateKey key,
String provider,
SecureRandom random)
throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException
{
try
{
return generate(key, provider, random);
}
catch (NoSuchProviderException e)
{
throw e;
}
catch (SignatureException e)
{
throw e;
}
catch (InvalidKeyException e)
{
throw e;
}
catch (GeneralSecurityException e)
{
throw new SecurityException("exception: " + e);
}
}
/**
* generate an X509 certificate, based on the current issuer and subject
* using the default provider.
* <p>
* <b>Note:</b> this differs from the deprecated method in that the default provider is
* used - not "BC".
* </p>
*/
public X509Certificate generate(
PrivateKey key)
throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
return generate(key, (SecureRandom)null);
}
/**
* generate an X509 certificate, based on the current issuer and subject
* using the default provider, and the passed in source of randomness
* (if required).
* <p>
* <b>Note:</b> this differs from the deprecated method in that the default provider is
* used - not "BC".
* </p>
*/
public X509Certificate generate(
PrivateKey key,
SecureRandom random)
throws CertificateEncodingException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
TBSCertificate tbsCert = generateTbsCert();
byte[] signature;
try
{
signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCert);
}
catch (IOException e)
{
throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
}
try
{
return generateJcaObject(tbsCert, signature);
}
catch (CertificateParsingException e)
{
throw new ExtCertificateEncodingException("exception producing certificate object", e);
}
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing.
*/
public X509Certificate generate(
PrivateKey key,
String provider)
throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
return generate(key, provider, null);
}
/**
* generate an X509 certificate, based on the current issuer and subject,
* using the passed in provider for the signing and the supplied source
* of randomness, if required.
*/
public X509Certificate generate(
PrivateKey key,
String provider,
SecureRandom random)
throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException
{
TBSCertificate tbsCert = generateTbsCert();
byte[] signature;
try
{
signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, provider, key, random, tbsCert);
}
catch (IOException e)
{
throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
}
try
{
return generateJcaObject(tbsCert, signature);
}
catch (CertificateParsingException e)
{
throw new ExtCertificateEncodingException("exception producing certificate object", e);
}
}
private TBSCertificate generateTbsCert()
{
if (!extGenerator.isEmpty())
{
tbsGen.setExtensions(extGenerator.generate());
}
return tbsGen.generateTBSCertificate();
}
private X509Certificate generateJcaObject(TBSCertificate tbsCert, byte[] signature)
throws CertificateParsingException
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbsCert);
v.add(sigAlgId);
v.add(new DERBitString(signature));
return new X509CertificateObject(Certificate.getInstance(new DERSequence(v)));
}
/**
* Return an iterator of the signature names supported by the generator.
*
* @return an iterator containing recognised names.
*/
public Iterator getSignatureAlgNames()
{
return X509Util.getAlgNames();
}
}
| |
/*
* This file is part of "lunisolar-magma".
*
* (C) Copyright 2014-2022 Lunisolar (http://lunisolar.eu/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.lunisolar.magma.func.consumer.primitives;
import eu.lunisolar.magma.func.*; // NOSONAR
import javax.annotation.Nonnull; // NOSONAR
import javax.annotation.Nullable; // NOSONAR
import java.util.Objects;// NOSONAR
import eu.lunisolar.magma.basics.meta.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.type.*; // NOSONAR
import eu.lunisolar.magma.basics.meta.functional.domain.*; // NOSONAR
import eu.lunisolar.magma.func.action.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.bi.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.obj.*; // NOSONAR
import eu.lunisolar.magma.func.consumer.primitives.tri.*; // NOSONAR
import eu.lunisolar.magma.func.function.*; // NOSONAR
import eu.lunisolar.magma.func.function.conversion.*; // NOSONAR
import eu.lunisolar.magma.func.function.from.*; // NOSONAR
import eu.lunisolar.magma.func.function.to.*; // NOSONAR
import eu.lunisolar.magma.func.operator.binary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.ternary.*; // NOSONAR
import eu.lunisolar.magma.func.operator.unary.*; // NOSONAR
import eu.lunisolar.magma.func.predicate.*; // NOSONAR
import eu.lunisolar.magma.func.supplier.*; // NOSONAR
import org.testng.Assert;
import org.testng.annotations.*; //NOSONAR
import java.util.regex.Pattern; //NOSONAR
import java.text.ParseException; //NOSONAR
import eu.lunisolar.magma.basics.*; //NOSONAR
import eu.lunisolar.magma.basics.exceptions.*; //NOSONAR
import java.util.concurrent.atomic.AtomicInteger; //NOSONAR
import eu.lunisolar.magma.func.tuple.*; // NOSONAR
import java.util.function.*; // NOSONAR
/** The test obviously concentrate on the interface methods the function it self is very simple. */
public class LCharConsumerTest {
private static final String ORIGINAL_MESSAGE = "Original message";
private static final String EXCEPTION_WAS_WRAPPED = "Exception was wrapped.";
private static final String NO_EXCEPTION_WERE_THROWN = "No exception were thrown.";
private LCharConsumer sut = new LCharConsumer(){
public void acceptX(char a) {
LCharConsumer.doNothing(a);
}
};
private LCharConsumer sutAlwaysThrowing = LCharConsumer.charCons(a -> {
throw new ParseException(ORIGINAL_MESSAGE, 0);
});
private LCharConsumer sutAlwaysThrowingUnchecked = LCharConsumer.charCons(a -> {
throw new IndexOutOfBoundsException(ORIGINAL_MESSAGE);
});
@Test
public void testTupleCall() throws Throwable {
LCharSingle domainObject = Tuple4U.charSingle('\u0100');
Object result = sut.tupleAccept(domainObject);
Assert.assertSame(result, LTuple.Void.INSTANCE);
}
@Test
public void testNestingAcceptUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.nestingAccept('\u0100');
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testShovingAcceptUnchecked() throws Throwable {
// then
try {
sutAlwaysThrowingUnchecked.shovingAccept('\u0100');
Assert.fail(NO_EXCEPTION_WERE_THROWN);
} catch (Exception e) {
Assert.assertEquals(e.getClass(), IndexOutOfBoundsException.class);
Assert.assertNull(e.getCause());
Assert.assertEquals(e.getMessage(), ORIGINAL_MESSAGE);
}
}
@Test
public void testFunctionalInterfaceDescription() throws Throwable {
Assert.assertEquals(sut.functionalInterfaceDescription(), "LCharConsumer: void accept(char a)");
}
@Test
public void testCharConsMethod() throws Throwable {
Assert.assertTrue(LCharConsumer.charCons(LCharConsumer::doNothing) instanceof LCharConsumer);
}
// <editor-fold desc="compose (functional)">
@Test
public void testCompose() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final AtomicInteger beforeCalls = new AtomicInteger(0);
//given (+ some assertions)
LCharConsumer sutO = a -> {
mainFunctionCalled.set(true);
Assert.assertEquals(a, (Object) '\u0090');
};
LCharUnaryOperator before = p0 -> {
Assert.assertEquals(p0, (Object) '\u0080');
beforeCalls.incrementAndGet();
return '\u0090';
};
//when
LCharConsumer function = sutO.compose(before);
function.accept('\u0080');
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertEquals(beforeCalls.get(), 1);
}
@Test
public void testCharConsCompose() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final AtomicInteger beforeCalls = new AtomicInteger(0);
//given (+ some assertions)
LCharConsumer sutO = a -> {
mainFunctionCalled.set(true);
Assert.assertEquals(a, (Object) '\u0090');
};
LToCharFunction<Integer> before = p0 -> {
Assert.assertEquals(p0, (Object) 80);
beforeCalls.incrementAndGet();
return '\u0090';
};
//when
LConsumer<Integer> function = sutO.charConsCompose(before);
function.accept(80);
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertEquals(beforeCalls.get(), 1);
}
// </editor-fold>
@Test
public void testAndThen() throws Throwable {
final ThreadLocal<Boolean> mainFunctionCalled = ThreadLocal.withInitial(()-> false);
final ThreadLocal<Boolean> thenFunctionCalled = ThreadLocal.withInitial(()-> false);
//given (+ some assertions)
LCharConsumer sutO = a -> {
mainFunctionCalled.set(true);
Assert.assertEquals((Object)a, (Object) '\u0080');
};
LCharConsumer thenFunction = a -> {
thenFunctionCalled.set(true);
Assert.assertEquals((Object)a, (Object) '\u0080');
};
//when
LCharConsumer function = sutO.andThen(thenFunction);
function.accept('\u0080');
//then - finals
Assert.assertTrue(mainFunctionCalled.get());
Assert.assertTrue(thenFunctionCalled.get());
}
@Test(expectedExceptions = RuntimeException.class)
public void testShove() {
// given
LCharConsumer sutThrowing = LCharConsumer.charCons(a -> {
throw new UnsupportedOperationException();
});
// when
sutThrowing.shovingAccept('\u0100');
}
@Test
public void testToString() throws Throwable {
Assert.assertTrue(sut.toString().startsWith(this.getClass().getName()+"$"));
Assert.assertTrue(String.format("%s", sut).contains("LCharConsumer: void accept(char a)"));
}
@Test
public void isThrowing() {
Assert.assertFalse(sut.isThrowing());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.guacamole.auth.jdbc.user;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import javax.servlet.http.HttpServletRequest;
import org.apache.guacamole.net.auth.Credentials;
import org.apache.guacamole.auth.jdbc.base.ModeledDirectoryObjectMapper;
import org.apache.guacamole.auth.jdbc.base.ModeledDirectoryObjectService;
import org.apache.guacamole.GuacamoleClientException;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleUnsupportedException;
import org.apache.guacamole.auth.jdbc.permission.ObjectPermissionMapper;
import org.apache.guacamole.auth.jdbc.permission.ObjectPermissionModel;
import org.apache.guacamole.auth.jdbc.permission.UserPermissionMapper;
import org.apache.guacamole.auth.jdbc.security.PasswordEncryptionService;
import org.apache.guacamole.auth.jdbc.security.PasswordPolicyService;
import org.apache.guacamole.form.Field;
import org.apache.guacamole.form.PasswordField;
import org.apache.guacamole.net.auth.AuthenticatedUser;
import org.apache.guacamole.net.auth.AuthenticationProvider;
import org.apache.guacamole.net.auth.User;
import org.apache.guacamole.net.auth.credentials.CredentialsInfo;
import org.apache.guacamole.net.auth.credentials.GuacamoleInsufficientCredentialsException;
import org.apache.guacamole.net.auth.permission.ObjectPermission;
import org.apache.guacamole.net.auth.permission.ObjectPermissionSet;
import org.apache.guacamole.net.auth.permission.SystemPermission;
import org.apache.guacamole.net.auth.permission.SystemPermissionSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Service which provides convenience methods for creating, retrieving, and
* manipulating users.
*/
public class UserService extends ModeledDirectoryObjectService<ModeledUser, User, UserModel> {
/**
* Logger for this class.
*/
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
/**
* All user permissions which are implicitly granted to the new user upon
* creation.
*/
private static final ObjectPermission.Type[] IMPLICIT_USER_PERMISSIONS = {
ObjectPermission.Type.READ
};
/**
* The name of the HTTP password parameter to expect if the user is
* changing their expired password upon login.
*/
private static final String NEW_PASSWORD_PARAMETER = "new-password";
/**
* The password field to provide the user when their password is expired
* and must be changed.
*/
private static final Field NEW_PASSWORD = new PasswordField(NEW_PASSWORD_PARAMETER);
/**
* The name of the HTTP password confirmation parameter to expect if the
* user is changing their expired password upon login.
*/
private static final String CONFIRM_NEW_PASSWORD_PARAMETER = "confirm-new-password";
/**
* The password confirmation field to provide the user when their password
* is expired and must be changed.
*/
private static final Field CONFIRM_NEW_PASSWORD = new PasswordField(CONFIRM_NEW_PASSWORD_PARAMETER);
/**
* Information describing the expected credentials if a user's password is
* expired. If a user's password is expired, it must be changed during the
* login process.
*/
private static final CredentialsInfo EXPIRED_PASSWORD = new CredentialsInfo(Arrays.asList(
CredentialsInfo.USERNAME,
CredentialsInfo.PASSWORD,
NEW_PASSWORD,
CONFIRM_NEW_PASSWORD
));
/**
* Mapper for accessing users.
*/
@Inject
private UserMapper userMapper;
/**
* Mapper for manipulating user permissions.
*/
@Inject
private UserPermissionMapper userPermissionMapper;
/**
* Provider for creating users.
*/
@Inject
private Provider<ModeledUser> userProvider;
/**
* Service for hashing passwords.
*/
@Inject
private PasswordEncryptionService encryptionService;
/**
* Service for enforcing password complexity policies.
*/
@Inject
private PasswordPolicyService passwordPolicyService;
@Override
protected ModeledDirectoryObjectMapper<UserModel> getObjectMapper() {
return userMapper;
}
@Override
protected ObjectPermissionMapper getPermissionMapper() {
return userPermissionMapper;
}
@Override
protected ModeledUser getObjectInstance(ModeledAuthenticatedUser currentUser,
UserModel model) throws GuacamoleException {
boolean exposeRestrictedAttributes;
// Expose restricted attributes if the user does not yet exist
if (model.getObjectID() == null)
exposeRestrictedAttributes = true;
// Otherwise, if the user permissions are available, expose restricted
// attributes only if the user has ADMINISTER permission
else if (currentUser != null)
exposeRestrictedAttributes = hasObjectPermission(currentUser,
model.getIdentifier(), ObjectPermission.Type.ADMINISTER);
// If user permissions are not available, do not expose anything
else
exposeRestrictedAttributes = false;
// Produce ModeledUser exposing only those attributes for which the
// current user has permission
ModeledUser user = userProvider.get();
user.init(currentUser, model, exposeRestrictedAttributes);
return user;
}
@Override
protected UserModel getModelInstance(ModeledAuthenticatedUser currentUser,
final User object) throws GuacamoleException {
// Create new ModeledUser backed by blank model
UserModel model = new UserModel();
ModeledUser user = getObjectInstance(currentUser, model);
// Set model contents through ModeledUser, copying the provided user
user.setIdentifier(object.getIdentifier());
user.setPassword(object.getPassword());
user.setAttributes(object.getAttributes());
return model;
}
@Override
protected boolean hasCreatePermission(ModeledAuthenticatedUser user)
throws GuacamoleException {
// Return whether user has explicit user creation permission
SystemPermissionSet permissionSet = user.getUser().getSystemPermissions();
return permissionSet.hasPermission(SystemPermission.Type.CREATE_USER);
}
@Override
protected ObjectPermissionSet getPermissionSet(ModeledAuthenticatedUser user)
throws GuacamoleException {
// Return permissions related to users
return user.getUser().getUserPermissions();
}
@Override
protected void beforeCreate(ModeledAuthenticatedUser user, User object,
UserModel model) throws GuacamoleException {
super.beforeCreate(user, object, model);
// Username must not be blank
if (model.getIdentifier() == null || model.getIdentifier().trim().isEmpty())
throw new GuacamoleClientException("The username must not be blank.");
// Do not create duplicate users
Collection<UserModel> existing = userMapper.select(Collections.singleton(model.getIdentifier()));
if (!existing.isEmpty())
throw new GuacamoleClientException("User \"" + model.getIdentifier() + "\" already exists.");
// Verify new password does not violate defined policies (if specified)
if (object.getPassword() != null)
passwordPolicyService.verifyPassword(object.getIdentifier(), object.getPassword());
}
@Override
protected void beforeUpdate(ModeledAuthenticatedUser user,
ModeledUser object, UserModel model) throws GuacamoleException {
super.beforeUpdate(user, object, model);
// Username must not be blank
if (model.getIdentifier() == null || model.getIdentifier().trim().isEmpty())
throw new GuacamoleClientException("The username must not be blank.");
// Check whether such a user is already present
UserModel existing = userMapper.selectOne(model.getIdentifier());
if (existing != null) {
// Do not rename to existing user
if (!existing.getObjectID().equals(model.getObjectID()))
throw new GuacamoleClientException("User \"" + model.getIdentifier() + "\" already exists.");
}
// Verify new password does not violate defined policies (if specified)
if (object.getPassword() != null) {
// Enforce password age only for non-adminstrators
if (!user.getUser().isAdministrator())
passwordPolicyService.verifyPasswordAge(object);
// Always verify password complexity
passwordPolicyService.verifyPassword(object.getIdentifier(), object.getPassword());
// Store previous password in history
passwordPolicyService.recordPassword(object);
}
}
@Override
protected Collection<ObjectPermissionModel>
getImplicitPermissions(ModeledAuthenticatedUser user, UserModel model) {
// Get original set of implicit permissions
Collection<ObjectPermissionModel> implicitPermissions = super.getImplicitPermissions(user, model);
// Grant implicit permissions to the new user
for (ObjectPermission.Type permissionType : IMPLICIT_USER_PERMISSIONS) {
ObjectPermissionModel permissionModel = new ObjectPermissionModel();
permissionModel.setUserID(model.getObjectID());
permissionModel.setUsername(model.getIdentifier());
permissionModel.setType(permissionType);
permissionModel.setObjectIdentifier(model.getIdentifier());
// Add new permission to implicit permission set
implicitPermissions.add(permissionModel);
}
return implicitPermissions;
}
@Override
protected void beforeDelete(ModeledAuthenticatedUser user, String identifier) throws GuacamoleException {
super.beforeDelete(user, identifier);
// Do not allow users to delete themselves
if (identifier.equals(user.getUser().getIdentifier()))
throw new GuacamoleUnsupportedException("Deleting your own user is not allowed.");
}
@Override
protected boolean isValidIdentifier(String identifier) {
// All strings are valid user identifiers
return true;
}
/**
* Retrieves the user corresponding to the given credentials from the
* database. Note that this function will not enforce any additional
* account restrictions, including explicitly disabled accounts,
* scheduling, and password expiration. It is the responsibility of the
* caller to enforce such restrictions, if desired.
*
* @param authenticationProvider
* The AuthenticationProvider on behalf of which the user is being
* retrieved.
*
* @param credentials
* The credentials to use when locating the user.
*
* @return
* An AuthenticatedUser containing the existing ModeledUser object if
* the credentials given are valid, null otherwise.
*
* @throws GuacamoleException
* If the provided credentials to not conform to expectations.
*/
public ModeledAuthenticatedUser retrieveAuthenticatedUser(AuthenticationProvider authenticationProvider,
Credentials credentials) throws GuacamoleException {
// Get username and password
String username = credentials.getUsername();
String password = credentials.getPassword();
// Retrieve corresponding user model, if such a user exists
UserModel userModel = userMapper.selectOne(username);
if (userModel == null)
return null;
// Verify provided password is correct
byte[] hash = encryptionService.createPasswordHash(password, userModel.getPasswordSalt());
if (!Arrays.equals(hash, userModel.getPasswordHash()))
return null;
// If 2fa authentication is enabled, validate it
if(userModel.isGAuthEnabled()) {
logger.info("Using google authenticator for user ", username);
GoogleAuthenticator gAuth = new GoogleAuthenticator();
String receivedSecret = credentials.getSecret();
Integer receivedSecretI;
try {
receivedSecretI = Integer.parseInt(receivedSecret);
if(!gAuth.authorize(userModel.getSecretKey(), receivedSecretI)) {
return null;
}
}
catch(Exception e) {
return null;
}
}
// Create corresponding user object, set up cyclic reference
ModeledUser user = getObjectInstance(null, userModel);
user.setCurrentUser(new ModeledAuthenticatedUser(authenticationProvider, user, credentials));
// Return now-authenticated user
return user.getCurrentUser();
}
/**
* Retrieves the user corresponding to the given AuthenticatedUser from the
* database.
*
* @param authenticationProvider
* The AuthenticationProvider on behalf of which the user is being
* retrieved.
*
* @param authenticatedUser
* The AuthenticatedUser to retrieve the corresponding ModeledUser of.
*
* @return
* The ModeledUser which corresponds to the given AuthenticatedUser, or
* null if no such user exists.
*
* @throws GuacamoleException
* If a ModeledUser object for the user corresponding to the given
* AuthenticatedUser cannot be created.
*/
public ModeledUser retrieveUser(AuthenticationProvider authenticationProvider,
AuthenticatedUser authenticatedUser) throws GuacamoleException {
// If we already queried this user, return that rather than querying again
if (authenticatedUser instanceof ModeledAuthenticatedUser)
return ((ModeledAuthenticatedUser) authenticatedUser).getUser();
// Get username
String username = authenticatedUser.getIdentifier();
// Retrieve corresponding user model, if such a user exists
UserModel userModel = userMapper.selectOne(username);
if (userModel == null)
return null;
// Create corresponding user object, set up cyclic reference
ModeledUser user = getObjectInstance(null, userModel);
user.setCurrentUser(new ModeledAuthenticatedUser(authenticatedUser,
authenticationProvider, user));
// Return already-authenticated user
return user;
}
/**
* Resets the password of the given user to the new password specified via
* the "new-password" and "confirm-new-password" parameters from the
* provided credentials. If these parameters are missing or invalid,
* additional credentials will be requested.
*
* @param user
* The user whose password should be reset.
*
* @param credentials
* The credentials from which the parameters required for password
* reset should be retrieved.
*
* @throws GuacamoleException
* If the password reset parameters within the given credentials are
* invalid or missing.
*/
public void resetExpiredPassword(ModeledUser user, Credentials credentials)
throws GuacamoleException {
UserModel userModel = user.getModel();
// Get username
String username = user.getIdentifier();
// Pull new password from HTTP request
HttpServletRequest request = credentials.getRequest();
String newPassword = request.getParameter(NEW_PASSWORD_PARAMETER);
String confirmNewPassword = request.getParameter(CONFIRM_NEW_PASSWORD_PARAMETER);
// Require new password if account is expired
if (newPassword == null || confirmNewPassword == null) {
logger.info("The password of user \"{}\" has expired and must be reset.", username);
throw new GuacamoleInsufficientCredentialsException("LOGIN.INFO_PASSWORD_EXPIRED", EXPIRED_PASSWORD);
}
// New password must be different from old password
if (newPassword.equals(credentials.getPassword()))
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_SAME");
// New password must not be blank
if (newPassword.isEmpty())
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_BLANK");
// Confirm that the password was entered correctly twice
if (!newPassword.equals(confirmNewPassword))
throw new GuacamoleClientException("LOGIN.ERROR_PASSWORD_MISMATCH");
// Verify new password does not violate defined policies
passwordPolicyService.verifyPassword(username, newPassword);
// Change password and reset expiration flag
userModel.setExpired(false);
user.setPassword(newPassword);
userMapper.update(userModel);
logger.info("Expired password of user \"{}\" has been reset.", username);
}
}
| |
/*
*
*/
package relationalMetaModel.diagram.edit.policies;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
import org.eclipse.gmf.runtime.diagram.ui.commands.DeferredLayoutCommand;
import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
import org.eclipse.gmf.runtime.diagram.ui.commands.SetViewMutabilityCommand;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CanonicalEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.Edge;
import org.eclipse.gmf.runtime.notation.Node;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.update.UpdaterLinkDescriptor;
/**
* @generated
*/
public class RelationalSchemaCanonicalEditPolicy extends CanonicalEditPolicy {
/**
* @generated
*/
protected void refreshOnActivate() {
// Need to activate editpart children before invoking the canonical refresh for EditParts to add event listeners
List<?> c = getHost().getChildren();
for (int i = 0; i < c.size(); i++) {
((EditPart) c.get(i)).activate();
}
super.refreshOnActivate();
}
/**
* @generated
*/
protected EStructuralFeature getFeatureToSynchronize() {
return relationalMetaModel.RelationalMetaModelPackage.eINSTANCE
.getRelationalSchema_Tables();
}
/**
* @generated
*/
@SuppressWarnings("rawtypes")
protected List getSemanticChildrenList() {
View viewObject = (View) getHost().getModel();
LinkedList<EObject> result = new LinkedList<EObject>();
List<relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor> childDescriptors = relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.getRelationalSchema_1000SemanticChildren(viewObject);
for (relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor d : childDescriptors) {
result.add(d.getModelElement());
}
return result;
}
/**
* @generated
*/
protected boolean isOrphaned(Collection<EObject> semanticChildren,
final View view) {
if (isShortcut(view)) {
return relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.isShortcutOrphaned(view);
}
return isMyDiagramElement(view)
&& !semanticChildren.contains(view.getElement());
}
/**
* @generated
*/
private boolean isMyDiagramElement(View view) {
return relationalMetaModel.diagram.edit.parts.RelationalTableEditPart.VISUAL_ID == relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getVisualID(view);
}
/**
* @generated
*/
protected static boolean isShortcut(View view) {
return view.getEAnnotation("Shortcut") != null; //$NON-NLS-1$
}
/**
* @generated
*/
protected void refreshSemantic() {
if (resolveSemanticElement() == null) {
return;
}
LinkedList<IAdaptable> createdViews = new LinkedList<IAdaptable>();
List<relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor> childDescriptors = relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.getRelationalSchema_1000SemanticChildren((View) getHost()
.getModel());
LinkedList<View> orphaned = new LinkedList<View>();
// we care to check only views we recognize as ours and not shortcuts
LinkedList<View> knownViewChildren = new LinkedList<View>();
for (View v : getViewChildren()) {
if (isShortcut(v)) {
if (relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.isShortcutOrphaned(v)) {
orphaned.add(v);
}
continue;
}
if (isMyDiagramElement(v)) {
knownViewChildren.add(v);
}
}
// alternative to #cleanCanonicalSemanticChildren(getViewChildren(), semanticChildren)
//
// iteration happens over list of desired semantic elements, trying to find best matching View, while original CEP
// iterates views, potentially losing view (size/bounds) information - i.e. if there are few views to reference same EObject, only last one
// to answer isOrphaned == true will be used for the domain element representation, see #cleanCanonicalSemanticChildren()
for (Iterator<relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor> descriptorsIterator = childDescriptors
.iterator(); descriptorsIterator.hasNext();) {
relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor next = descriptorsIterator
.next();
String hint = relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getType(next.getVisualID());
LinkedList<View> perfectMatch = new LinkedList<View>(); // both semanticElement and hint match that of NodeDescriptor
for (View childView : getViewChildren()) {
EObject semanticElement = childView.getElement();
if (next.getModelElement().equals(semanticElement)) {
if (hint.equals(childView.getType())) {
perfectMatch.add(childView);
// actually, can stop iteration over view children here, but
// may want to use not the first view but last one as a 'real' match (the way original CEP does
// with its trick with viewToSemanticMap inside #cleanCanonicalSemanticChildren
}
}
}
if (perfectMatch.size() > 0) {
descriptorsIterator.remove(); // precise match found no need to create anything for the NodeDescriptor
// use only one view (first or last?), keep rest as orphaned for further consideration
knownViewChildren.remove(perfectMatch.getFirst());
}
}
// those left in knownViewChildren are subject to removal - they are our diagram elements we didn't find match to,
// or those we have potential matches to, and thus need to be recreated, preserving size/location information.
orphaned.addAll(knownViewChildren);
//
ArrayList<CreateViewRequest.ViewDescriptor> viewDescriptors = new ArrayList<CreateViewRequest.ViewDescriptor>(
childDescriptors.size());
for (relationalMetaModel.diagram.part.RelationalMetaModelNodeDescriptor next : childDescriptors) {
String hint = relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getType(next.getVisualID());
IAdaptable elementAdapter = new CanonicalElementAdapter(
next.getModelElement(), hint);
CreateViewRequest.ViewDescriptor descriptor = new CreateViewRequest.ViewDescriptor(
elementAdapter, Node.class, hint, ViewUtil.APPEND, false,
host().getDiagramPreferencesHint());
viewDescriptors.add(descriptor);
}
boolean changed = deleteViews(orphaned.iterator());
//
CreateViewRequest request = getCreateViewRequest(viewDescriptors);
Command cmd = getCreateViewCommand(request);
if (cmd != null && cmd.canExecute()) {
SetViewMutabilityCommand.makeMutable(
new EObjectAdapter(host().getNotationView())).execute();
executeCommand(cmd);
@SuppressWarnings("unchecked")
List<IAdaptable> nl = (List<IAdaptable>) request.getNewObject();
createdViews.addAll(nl);
}
if (changed || createdViews.size() > 0) {
postProcessRefreshSemantic(createdViews);
}
Collection<IAdaptable> createdConnectionViews = refreshConnections();
if (createdViews.size() > 1) {
// perform a layout of the container
DeferredLayoutCommand layoutCmd = new DeferredLayoutCommand(host()
.getEditingDomain(), createdViews, host());
executeCommand(new ICommandProxy(layoutCmd));
}
createdViews.addAll(createdConnectionViews);
makeViewsImmutable(createdViews);
}
/**
* @generated
*/
private Collection<IAdaptable> refreshConnections() {
Domain2Notation domain2NotationMap = new Domain2Notation();
Collection<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor> linkDescriptors = collectAllLinks(
getDiagram(), domain2NotationMap);
Collection existingLinks = new LinkedList(getDiagram().getEdges());
for (Iterator linksIterator = existingLinks.iterator(); linksIterator
.hasNext();) {
Edge nextDiagramLink = (Edge) linksIterator.next();
int diagramLinkVisualID = relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getVisualID(nextDiagramLink);
if (diagramLinkVisualID == -1) {
if (nextDiagramLink.getSource() != null
&& nextDiagramLink.getTarget() != null) {
linksIterator.remove();
}
continue;
}
EObject diagramLinkObject = nextDiagramLink.getElement();
EObject diagramLinkSrc = nextDiagramLink.getSource().getElement();
EObject diagramLinkDst = nextDiagramLink.getTarget().getElement();
for (Iterator<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor> linkDescriptorsIterator = linkDescriptors
.iterator(); linkDescriptorsIterator.hasNext();) {
relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor nextLinkDescriptor = linkDescriptorsIterator
.next();
if (diagramLinkObject == nextLinkDescriptor.getModelElement()
&& diagramLinkSrc == nextLinkDescriptor.getSource()
&& diagramLinkDst == nextLinkDescriptor
.getDestination()
&& diagramLinkVisualID == nextLinkDescriptor
.getVisualID()) {
linksIterator.remove();
linkDescriptorsIterator.remove();
break;
}
}
}
deleteViews(existingLinks.iterator());
return createConnections(linkDescriptors, domain2NotationMap);
}
/**
* @generated
*/
private Collection<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor> collectAllLinks(
View view, Domain2Notation domain2NotationMap) {
if (!relationalMetaModel.diagram.edit.parts.RelationalSchemaEditPart.MODEL_ID
.equals(relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getModelID(view))) {
return Collections.emptyList();
}
LinkedList<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor> result = new LinkedList<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor>();
switch (relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getVisualID(view)) {
case relationalMetaModel.diagram.edit.parts.RelationalSchemaEditPart.VISUAL_ID: {
if (!domain2NotationMap.containsKey(view.getElement())) {
result.addAll(relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.getRelationalSchema_1000ContainedLinks(view));
}
domain2NotationMap.putView(view.getElement(), view);
break;
}
case relationalMetaModel.diagram.edit.parts.RelationalTableEditPart.VISUAL_ID: {
if (!domain2NotationMap.containsKey(view.getElement())) {
result.addAll(relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.getRelationalTable_2001ContainedLinks(view));
}
domain2NotationMap.putView(view.getElement(), view);
break;
}
case relationalMetaModel.diagram.edit.parts.RelationalForeignKeyEditPart.VISUAL_ID: {
if (!domain2NotationMap.containsKey(view.getElement())) {
result.addAll(relationalMetaModel.diagram.part.RelationalMetaModelDiagramUpdater
.getRelationalForeignKey_3001ContainedLinks(view));
}
domain2NotationMap.putView(view.getElement(), view);
break;
}
}
for (Iterator children = view.getChildren().iterator(); children
.hasNext();) {
result.addAll(collectAllLinks((View) children.next(),
domain2NotationMap));
}
for (Iterator edges = view.getSourceEdges().iterator(); edges.hasNext();) {
result.addAll(collectAllLinks((View) edges.next(),
domain2NotationMap));
}
return result;
}
/**
* @generated
*/
private Collection<IAdaptable> createConnections(
Collection<relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor> linkDescriptors,
Domain2Notation domain2NotationMap) {
LinkedList<IAdaptable> adapters = new LinkedList<IAdaptable>();
for (relationalMetaModel.diagram.part.RelationalMetaModelLinkDescriptor nextLinkDescriptor : linkDescriptors) {
EditPart sourceEditPart = getSourceEditPart(nextLinkDescriptor,
domain2NotationMap);
EditPart targetEditPart = getTargetEditPart(nextLinkDescriptor,
domain2NotationMap);
if (sourceEditPart == null || targetEditPart == null) {
continue;
}
CreateConnectionViewRequest.ConnectionViewDescriptor descriptor = new CreateConnectionViewRequest.ConnectionViewDescriptor(
nextLinkDescriptor.getSemanticAdapter(),
relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getType(nextLinkDescriptor.getVisualID()),
ViewUtil.APPEND, false, ((IGraphicalEditPart) getHost())
.getDiagramPreferencesHint());
CreateConnectionViewRequest ccr = new CreateConnectionViewRequest(
descriptor);
ccr.setType(RequestConstants.REQ_CONNECTION_START);
ccr.setSourceEditPart(sourceEditPart);
sourceEditPart.getCommand(ccr);
ccr.setTargetEditPart(targetEditPart);
ccr.setType(RequestConstants.REQ_CONNECTION_END);
Command cmd = targetEditPart.getCommand(ccr);
if (cmd != null && cmd.canExecute()) {
executeCommand(cmd);
IAdaptable viewAdapter = (IAdaptable) ccr.getNewObject();
if (viewAdapter != null) {
adapters.add(viewAdapter);
}
}
}
return adapters;
}
/**
* @generated
*/
private EditPart getEditPart(EObject domainModelElement,
Domain2Notation domain2NotationMap) {
View view = (View) domain2NotationMap.get(domainModelElement);
if (view != null) {
return (EditPart) getHost().getViewer().getEditPartRegistry()
.get(view);
}
return null;
}
/**
* @generated
*/
private Diagram getDiagram() {
return ((View) getHost().getModel()).getDiagram();
}
/**
* @generated
*/
private EditPart getSourceEditPart(UpdaterLinkDescriptor descriptor,
Domain2Notation domain2NotationMap) {
return getEditPart(descriptor.getSource(), domain2NotationMap);
}
/**
* @generated
*/
private EditPart getTargetEditPart(UpdaterLinkDescriptor descriptor,
Domain2Notation domain2NotationMap) {
return getEditPart(descriptor.getDestination(), domain2NotationMap);
}
/**
* @generated
*/
protected final EditPart getHintedEditPart(EObject domainModelElement,
Domain2Notation domain2NotationMap, int hintVisualId) {
View view = (View) domain2NotationMap
.getHinted(
domainModelElement,
relationalMetaModel.diagram.part.RelationalMetaModelVisualIDRegistry
.getType(hintVisualId));
if (view != null) {
return (EditPart) getHost().getViewer().getEditPartRegistry()
.get(view);
}
return null;
}
/**
* @generated
*/
@SuppressWarnings("serial")
protected static class Domain2Notation extends HashMap<EObject, View> {
/**
* @generated
*/
public boolean containsDomainElement(EObject domainElement) {
return this.containsKey(domainElement);
}
/**
* @generated
*/
public View getHinted(EObject domainEObject, String hint) {
return this.get(domainEObject);
}
/**
* @generated
*/
public void putView(EObject domainElement, View view) {
if (!containsKey(view.getElement()) || !isShortcut(view)) {
this.put(domainElement, view);
}
}
}
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shape.in.sunshine.data;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;
import com.shape.in.sunshine.data.WeatherContract.LocationEntry;
import com.shape.in.sunshine.data.WeatherContract.WeatherEntry;
/*
Note: This is not a complete set of tests of the Sunshine ContentProvider, but it does test
that at least the basic functionality has been implemented correctly.
Students: Uncomment the tests in this class as you implement the functionality in your
ContentProvider to make sure that you've implemented things reasonably correctly.
*/
public class TestProvider extends AndroidTestCase {
public static final String LOG_TAG = TestProvider.class.getSimpleName();
/*
This helper function deletes all records from both database tables using the ContentProvider.
It also queries the ContentProvider to make sure that the database has been successfully
deleted, so it cannot be used until the Query and Delete functions have been written
in the ContentProvider.
Students: Replace the calls to deleteAllRecordsFromDB with this one after you have written
the delete functionality in the ContentProvider.
*/
public void deleteAllRecordsFromProvider() {
mContext.getContentResolver().delete(
WeatherEntry.CONTENT_URI,
null,
null
);
mContext.getContentResolver().delete(
LocationEntry.CONTENT_URI,
null,
null
);
Cursor cursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
cursor.close();
cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null,
null,
null,
null
);
assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
cursor.close();
}
/*
This helper function deletes all records from both database tables using the database
functions only. This is designed to be used to reset the state of the database until the
delete functionality is available in the ContentProvider.
*/
public void deleteAllRecordsFromDB() {
WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete(WeatherEntry.TABLE_NAME, null, null);
db.delete(LocationEntry.TABLE_NAME, null, null);
db.close();
}
/*
Student: Refactor this function to use the deleteAllRecordsFromProvider functionality once
you have implemented delete functionality there.
*/
public void deleteAllRecords() {
deleteAllRecordsFromDB();
}
// Since we want each test to start with a clean slate, run deleteAllRecords
// in setUp (called by the test runner before each test).
@Override
protected void setUp() throws Exception {
super.setUp();
deleteAllRecords();
}
/*
This test checks to make sure that the content provider is registered correctly.
Students: Uncomment this test to make sure you've correctly registered the WeatherProvider.
*/
// public void testProviderRegistry() {
// PackageManager pm = mContext.getPackageManager();
//
// // We define the component name based on the package name from the context and the
// // WeatherProvider class.
// ComponentName componentName = new ComponentName(mContext.getPackageName(),
// WeatherProvider.class.getName());
// try {
// // Fetch the provider info using the component name from the PackageManager
// // This throws an exception if the provider isn't registered.
// ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);
//
// // Make sure that the registered authority matches the authority from the Contract.
// assertEquals("Error: WeatherProvider registered with authority: " + providerInfo.authority +
// " instead of authority: " + WeatherContract.CONTENT_AUTHORITY,
// providerInfo.authority, WeatherContract.CONTENT_AUTHORITY);
// } catch (PackageManager.NameNotFoundException e) {
// // I guess the provider isn't registered correctly.
// assertTrue("Error: WeatherProvider not registered at " + mContext.getPackageName(),
// false);
// }
// }
/*
This test doesn't touch the database. It verifies that the ContentProvider returns
the correct type for each type of URI that it can handle.
Students: Uncomment this test to verify that your implementation of GetType is
functioning correctly.
*/
public void testGetType() {
// content://com.example.android.sunshine.app/weather/
String type = mContext.getContentResolver().getType(WeatherEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.example.android.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
String testLocation = "94074";
// content://com.shape.in.sunshine.app/weather/94074
type = mContext.getContentResolver().getType(
WeatherEntry.buildWeatherLocation(testLocation));
// vnd.android.cursor.dir/com.shape.in.sunshine.app/weather
assertEquals("Error: the WeatherEntry CONTENT_URI with location should return WeatherEntry.CONTENT_TYPE",
WeatherEntry.CONTENT_TYPE, type);
long testDate = 1419120000L; // December 21st, 2014
// content://com.shape.in.sunshine.app/weather/94074/20140612
type = mContext.getContentResolver().getType(
WeatherEntry.buildWeatherLocationWithDate(testLocation, testDate));
// vnd.android.cursor.item/com.shape.in.sunshine.app/weather/1419120000
assertEquals("Error: the WeatherEntry CONTENT_URI with location and date should return WeatherEntry.CONTENT_ITEM_TYPE",
WeatherEntry.CONTENT_ITEM_TYPE, type);
// content://com.shape.in.sunshine.app/location/
type = mContext.getContentResolver().getType(LocationEntry.CONTENT_URI);
// vnd.android.cursor.dir/com.shape.in.sunshine.app/location
assertEquals("Error: the LocationEntry CONTENT_URI should return LocationEntry.CONTENT_TYPE",
LocationEntry.CONTENT_TYPE, type);
}
/*
This test uses the database directly to insert and then uses the ContentProvider to
read out the data. Uncomment this test to see if the basic weather query functionality
given in the ContentProvider is working correctly.
*/
public void testBasicWeatherQuery() {
// insert our test records into the database
WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext);
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
long weatherRowId = db.insert(WeatherEntry.TABLE_NAME, null, weatherValues);
assertTrue("Unable to Insert WeatherEntry into the Database", weatherRowId != -1);
db.close();
// Test the basic content provider query
Cursor weatherCursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI,
null,
null,
null,
null
);
// Make sure we get the correct cursor out of the database
TestUtilities.validateCursor("testBasicWeatherQuery", weatherCursor, weatherValues);
}
/*
This test uses the database directly to insert and then uses the ContentProvider to
read out the data. Uncomment this test to see if your location queries are
performing correctly.
*/
// public void testBasicLocationQueries() {
// // insert our test records into the database
// WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
// SQLiteDatabase db = dbHelper.getWritableDatabase();
//
// ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
// long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext);
//
// // Test the basic content provider query
// Cursor locationCursor = mContext.getContentResolver().query(
// LocationEntry.CONTENT_URI,
// null,
// null,
// null,
// null
// );
//
// // Make sure we get the correct cursor out of the database
// TestUtilities.validateCursor("testBasicLocationQueries, location query", locationCursor, testValues);
//
// // Has the NotificationUri been set correctly? --- we can only test this easily against API
// // level 19 or greater because getNotificationUri was added in API level 19.
// if ( Build.VERSION.SDK_INT >= 19 ) {
// assertEquals("Error: Location Query did not properly set NotificationUri",
// locationCursor.getNotificationUri(), LocationEntry.CONTENT_URI);
// }
// }
/*
This test uses the provider to insert and then update the data. Uncomment this test to
see if your update location is functioning correctly.
*/
public void testUpdateLocation() {
// Create a new map of values, where column names are the keys
ContentValues values = TestUtilities.createNorthPoleLocationValues();
Uri locationUri = mContext.getContentResolver().
insert(LocationEntry.CONTENT_URI, values);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
Log.d(LOG_TAG, "New row id: " + locationRowId);
ContentValues updatedValues = new ContentValues(values);
updatedValues.put(LocationEntry._ID, locationRowId);
updatedValues.put(LocationEntry.COLUMN_CITY_NAME, "Santa's Village");
// Create a cursor with observer to make sure that the content provider is notifying
// the observers as expected
Cursor locationCursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI, null, null, null, null);
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
locationCursor.registerContentObserver(tco);
int count = mContext.getContentResolver().update(
LocationEntry.CONTENT_URI, updatedValues, LocationEntry._ID + "= ?",
new String[] { Long.toString(locationRowId)});
assertEquals(count, 1);
// Test to make sure our observer is called. If not, we throw an assertion.
//
// Students: If your code is failing here, it means that your content provider
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
locationCursor.unregisterContentObserver(tco);
locationCursor.close();
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // projection
LocationEntry._ID + " = " + locationRowId,
null, // Values for the "where" clause
null // sort order
);
TestUtilities.validateCursor("testUpdateLocation. Error validating location entry update.",
cursor, updatedValues);
cursor.close();
}
// Make sure we can still delete after adding/updating stuff
//
// Student: Uncomment this test after you have completed writing the insert functionality
// in your provider. It relies on insertions with testInsertReadProvider, so insert and
// query functionality must also be complete before this test can be used.
public void testInsertReadProvider() {
ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
// Register a content observer for our insert. This time, directly with the content resolver
TestUtilities.TestContentObserver tco = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, tco);
Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);
// Did our content observer get called? Students: If this fails, your insert location
// isn't calling getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(tco);
long locationRowId = ContentUris.parseId(locationUri);
// Verify we got a row back.
assertTrue(locationRowId != -1);
// Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// the round trip.
// A cursor is your primary interface to the query results.
Cursor cursor = mContext.getContentResolver().query(
LocationEntry.CONTENT_URI,
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating LocationEntry.",
cursor, testValues);
// Fantastic. Now that we have a location, add some weather!
ContentValues weatherValues = TestUtilities.createWeatherValues(locationRowId);
// The TestContentObserver is a one-shot class
tco = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, tco);
Uri weatherInsertUri = mContext.getContentResolver()
.insert(WeatherEntry.CONTENT_URI, weatherValues);
assertTrue(weatherInsertUri != null);
// Did our content observer get called? Students: If this fails, your insert weather
// in your ContentProvider isn't calling
// getContext().getContentResolver().notifyChange(uri, null);
tco.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(tco);
// A cursor is your primary interface to the query results.
Cursor weatherCursor = mContext.getContentResolver().query(
WeatherEntry.CONTENT_URI, // Table to Query
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // columns to group by
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating WeatherEntry insert.",
weatherCursor, weatherValues);
// Add the location values in with the weather data so that we can make
// sure that the join worked and we actually get all the values back
weatherValues.putAll(testValues);
// Get the joined Weather and Location data
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocation(TestUtilities.TEST_LOCATION),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data.",
weatherCursor, weatherValues);
// Get the joined Weather and Location data with a start date
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocationWithStartDate(
TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null, // leaving "columns" null just returns all the columns.
null, // cols for "where" clause
null, // values for "where" clause
null // sort order
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location Data with start date.",
weatherCursor, weatherValues);
// Get the joined Weather data for a specific date
weatherCursor = mContext.getContentResolver().query(
WeatherEntry.buildWeatherLocationWithDate(TestUtilities.TEST_LOCATION, TestUtilities.TEST_DATE),
null,
null,
null,
null
);
TestUtilities.validateCursor("testInsertReadProvider. Error validating joined Weather and Location data for a specific date.",
weatherCursor, weatherValues);
}
// Make sure we can still delete after adding/updating stuff
//
// Student: Uncomment this test after you have completed writing the delete functionality
// in your provider. It relies on insertions with testInsertReadProvider, so insert and
// query functionality must also be complete before this test can be used.
public void testDeleteRecords() {
testInsertReadProvider();
// Register a content observer for our location delete.
TestUtilities.TestContentObserver locationObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(LocationEntry.CONTENT_URI, true, locationObserver);
// Register a content observer for our weather delete.
TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);
deleteAllRecordsFromProvider();
// Students: If either of these fail, you most-likely are not calling the
// getContext().getContentResolver().notifyChange(uri, null); in the ContentProvider
// delete. (only if the insertReadProvider is succeeding)
locationObserver.waitForNotificationOrFail();
weatherObserver.waitForNotificationOrFail();
mContext.getContentResolver().unregisterContentObserver(locationObserver);
mContext.getContentResolver().unregisterContentObserver(weatherObserver);
}
static private final int BULK_INSERT_RECORDS_TO_INSERT = 10;
static ContentValues[] createBulkInsertWeatherValues(long locationRowId) {
long currentTestDate = TestUtilities.TEST_DATE;
long millisecondsInADay = 1000*60*60*24;
ContentValues[] returnContentValues = new ContentValues[BULK_INSERT_RECORDS_TO_INSERT];
for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, currentTestDate+= millisecondsInADay ) {
ContentValues weatherValues = new ContentValues();
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationRowId);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, currentTestDate);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, 1.1);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, 1.2 + 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, 1.3 - 0.01 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, 75 + i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, 65 - i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, "Asteroids");
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, 5.5 + 0.2 * (float) i);
weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, 321);
returnContentValues[i] = weatherValues;
}
return returnContentValues;
}
// Student: Uncomment this test after you have completed writing the BulkInsert functionality
// in your provider. Note that this test will work with the built-in (default) provider
// implementation, which just inserts records one-at-a-time, so really do implement the
// BulkInsert ContentProvider function.
// public void testBulkInsert() {
// // first, let's create a location value
// ContentValues testValues = TestUtilities.createNorthPoleLocationValues();
// Uri locationUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, testValues);
// long locationRowId = ContentUris.parseId(locationUri);
//
// // Verify we got a row back.
// assertTrue(locationRowId != -1);
//
// // Data's inserted. IN THEORY. Now pull some out to stare at it and verify it made
// // the round trip.
//
// // A cursor is your primary interface to the query results.
// Cursor cursor = mContext.getContentResolver().query(
// LocationEntry.CONTENT_URI,
// null, // leaving "columns" null just returns all the columns.
// null, // cols for "where" clause
// null, // values for "where" clause
// null // sort order
// );
//
// TestUtilities.validateCursor("testBulkInsert. Error validating LocationEntry.",
// cursor, testValues);
//
// // Now we can bulkInsert some weather. In fact, we only implement BulkInsert for weather
// // entries. With ContentProviders, you really only have to implement the features you
// // use, after all.
// ContentValues[] bulkInsertContentValues = createBulkInsertWeatherValues(locationRowId);
//
// // Register a content observer for our bulk insert.
// TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();
// mContext.getContentResolver().registerContentObserver(WeatherEntry.CONTENT_URI, true, weatherObserver);
//
// int insertCount = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, bulkInsertContentValues);
//
// // Students: If this fails, it means that you most-likely are not calling the
// // getContext().getContentResolver().notifyChange(uri, null); in your BulkInsert
// // ContentProvider method.
// weatherObserver.waitForNotificationOrFail();
// mContext.getContentResolver().unregisterContentObserver(weatherObserver);
//
// assertEquals(insertCount, BULK_INSERT_RECORDS_TO_INSERT);
//
// // A cursor is your primary interface to the query results.
// cursor = mContext.getContentResolver().query(
// WeatherEntry.CONTENT_URI,
// null, // leaving "columns" null just returns all the columns.
// null, // cols for "where" clause
// null, // values for "where" clause
// WeatherEntry.COLUMN_DATE + " ASC" // sort order == by DATE ASCENDING
// );
//
// // we should have as many records in the database as we've inserted
// assertEquals(cursor.getCount(), BULK_INSERT_RECORDS_TO_INSERT);
//
// // and let's make sure they match the ones we created
// cursor.moveToFirst();
// for ( int i = 0; i < BULK_INSERT_RECORDS_TO_INSERT; i++, cursor.moveToNext() ) {
// TestUtilities.validateCurrentRecord("testBulkInsert. Error validating WeatherEntry " + i,
// cursor, bulkInsertContentValues[i]);
// }
// cursor.close();
// }
}
| |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.clustering.randomprojection;
import org.nd4j.shade.guava.primitives.Doubles;
import lombok.val;
import org.nd4j.autodiff.functions.DifferentialFunction;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.ReduceFloatOp;
import org.nd4j.linalg.api.ops.ReduceOp;
import org.nd4j.linalg.api.ops.impl.reduce3.*;
import org.nd4j.linalg.exception.ND4JIllegalArgumentException;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.primitives.Pair;
import java.util.*;
/**
* A port of: <a href="https://github.com/lyst/rpforest">https://github.com/lyst/rpforest</a> to nd4j
*
* @author
*/
public class RPUtils {
private static ThreadLocal<Map<String,DifferentialFunction>> functionInstances = new ThreadLocal<>();
public static <T extends DifferentialFunction> DifferentialFunction getOp(String name,
INDArray x,
INDArray y,
INDArray result) {
Map<String,DifferentialFunction> ops = functionInstances.get();
if(ops == null) {
ops = new HashMap<>();
functionInstances.set(ops);
}
boolean allDistances = x.length() != y.length();
switch(name) {
case "cosinedistance":
if(!ops.containsKey(name) || ((CosineDistance)ops.get(name)).isComplexAccumulation() != allDistances) {
CosineDistance cosineDistance = new CosineDistance(x,y,result,allDistances);
ops.put(name,cosineDistance);
return cosineDistance;
}
else {
CosineDistance cosineDistance = (CosineDistance) ops.get(name);
return cosineDistance;
}
case "cosinesimilarity":
if(!ops.containsKey(name) || ((CosineSimilarity)ops.get(name)).isComplexAccumulation() != allDistances) {
CosineSimilarity cosineSimilarity = new CosineSimilarity(x,y,result,allDistances);
ops.put(name,cosineSimilarity);
return cosineSimilarity;
}
else {
CosineSimilarity cosineSimilarity = (CosineSimilarity) ops.get(name);
cosineSimilarity.setX(x);
cosineSimilarity.setY(y);
cosineSimilarity.setZ(result);
return cosineSimilarity;
}
case "manhattan":
if(!ops.containsKey(name) || ((ManhattanDistance)ops.get(name)).isComplexAccumulation() != allDistances) {
ManhattanDistance manhattanDistance = new ManhattanDistance(x,y,result,allDistances);
ops.put(name,manhattanDistance);
return manhattanDistance;
}
else {
ManhattanDistance manhattanDistance = (ManhattanDistance) ops.get(name);
manhattanDistance.setX(x);
manhattanDistance.setY(y);
manhattanDistance.setZ(result);
return manhattanDistance;
}
case "jaccard":
if(!ops.containsKey(name) || ((JaccardDistance)ops.get(name)).isComplexAccumulation() != allDistances) {
JaccardDistance jaccardDistance = new JaccardDistance(x,y,result,allDistances);
ops.put(name,jaccardDistance);
return jaccardDistance;
}
else {
JaccardDistance jaccardDistance = (JaccardDistance) ops.get(name);
jaccardDistance.setX(x);
jaccardDistance.setY(y);
jaccardDistance.setZ(result);
return jaccardDistance;
}
case "hamming":
if(!ops.containsKey(name) || ((HammingDistance)ops.get(name)).isComplexAccumulation() != allDistances) {
HammingDistance hammingDistance = new HammingDistance(x,y,result,allDistances);
ops.put(name,hammingDistance);
return hammingDistance;
}
else {
HammingDistance hammingDistance = (HammingDistance) ops.get(name);
hammingDistance.setX(x);
hammingDistance.setY(y);
hammingDistance.setZ(result);
return hammingDistance;
}
//euclidean
default:
if(!ops.containsKey(name) || ((EuclideanDistance)ops.get(name)).isComplexAccumulation() != allDistances) {
EuclideanDistance euclideanDistance = new EuclideanDistance(x,y,result,allDistances);
ops.put(name,euclideanDistance);
return euclideanDistance;
}
else {
EuclideanDistance euclideanDistance = (EuclideanDistance) ops.get(name);
euclideanDistance.setX(x);
euclideanDistance.setY(y);
euclideanDistance.setZ(result);
return euclideanDistance;
}
}
}
/**
* Query all trees using the given input and data
* @param toQuery the query vector
* @param X the input data to query
* @param trees the trees to query
* @param n the number of results to search for
* @param similarityFunction the similarity function to use
* @return the indices (in order) in the ndarray
*/
public static List<Pair<Double,Integer>> queryAllWithDistances(INDArray toQuery,INDArray X,List<RPTree> trees,int n,String similarityFunction) {
if(trees.isEmpty()) {
throw new ND4JIllegalArgumentException("Trees is empty!");
}
List<Integer> candidates = getCandidates(toQuery, trees,similarityFunction);
val sortedCandidates = sortCandidates(toQuery,X,candidates,similarityFunction);
int numReturns = Math.min(n,sortedCandidates.size());
List<Pair<Double,Integer>> ret = new ArrayList<>(numReturns);
for(int i = 0; i < numReturns; i++) {
ret.add(sortedCandidates.get(i));
}
return ret;
}
/**
* Query all trees using the given input and data
* @param toQuery the query vector
* @param X the input data to query
* @param trees the trees to query
* @param n the number of results to search for
* @param similarityFunction the similarity function to use
* @return the indices (in order) in the ndarray
*/
public static INDArray queryAll(INDArray toQuery,INDArray X,List<RPTree> trees,int n,String similarityFunction) {
if(trees.isEmpty()) {
throw new ND4JIllegalArgumentException("Trees is empty!");
}
List<Integer> candidates = getCandidates(toQuery, trees,similarityFunction);
val sortedCandidates = sortCandidates(toQuery,X,candidates,similarityFunction);
int numReturns = Math.min(n,sortedCandidates.size());
INDArray result = Nd4j.create(numReturns);
for(int i = 0; i < numReturns; i++) {
result.putScalar(i,sortedCandidates.get(i).getSecond());
}
return result;
}
/**
* Get the sorted distances given the
* query vector, input data, given the list of possible search candidates
* @param x the query vector
* @param X the input data to use
* @param candidates the possible search candidates
* @param similarityFunction the similarity function to use
* @return the sorted distances
*/
public static List<Pair<Double,Integer>> sortCandidates(INDArray x,INDArray X,
List<Integer> candidates,
String similarityFunction) {
int prevIdx = -1;
List<Pair<Double,Integer>> ret = new ArrayList<>();
for(int i = 0; i < candidates.size(); i++) {
if(candidates.get(i) != prevIdx) {
ret.add(Pair.of(computeDistance(similarityFunction,X.slice(candidates.get(i)),x),candidates.get(i)));
}
prevIdx = i;
}
Collections.sort(ret, new Comparator<Pair<Double, Integer>>() {
@Override
public int compare(Pair<Double, Integer> doubleIntegerPair, Pair<Double, Integer> t1) {
return Doubles.compare(doubleIntegerPair.getFirst(),t1.getFirst());
}
});
return ret;
}
/**
* Get the search candidates as indices given the input
* and similarity function
* @param x the input data to search with
* @param trees the trees to search
* @param similarityFunction the function to use for similarity
* @return the list of indices as the search results
*/
public static INDArray getAllCandidates(INDArray x,List<RPTree> trees,String similarityFunction) {
List<Integer> candidates = getCandidates(x,trees,similarityFunction);
Collections.sort(candidates);
int prevIdx = -1;
int idxCount = 0;
List<Pair<Integer,Integer>> scores = new ArrayList<>();
for(int i = 0; i < candidates.size(); i++) {
if(candidates.get(i) == prevIdx) {
idxCount++;
}
else if(prevIdx != -1) {
scores.add(Pair.of(idxCount,prevIdx));
idxCount = 1;
}
prevIdx = i;
}
scores.add(Pair.of(idxCount,prevIdx));
INDArray arr = Nd4j.create(scores.size());
for(int i = 0; i < scores.size(); i++) {
arr.putScalar(i,scores.get(i).getSecond());
}
return arr;
}
/**
* Get the search candidates as indices given the input
* and similarity function
* @param x the input data to search with
* @param roots the trees to search
* @param similarityFunction the function to use for similarity
* @return the list of indices as the search results
*/
public static List<Integer> getCandidates(INDArray x,List<RPTree> roots,String similarityFunction) {
Set<Integer> ret = new LinkedHashSet<>();
for(RPTree tree : roots) {
RPNode root = tree.getRoot();
RPNode query = query(root,tree.getRpHyperPlanes(),x,similarityFunction);
ret.addAll(query.getIndices());
}
return new ArrayList<>(ret);
}
/**
* Query the tree starting from the given node
* using the given hyper plane and similarity function
* @param from the node to start from
* @param planes the hyper plane to query
* @param x the input data
* @param similarityFunction the similarity function to use
* @return the leaf node representing the given query from a
* search in the tree
*/
public static RPNode query(RPNode from,RPHyperPlanes planes,INDArray x,String similarityFunction) {
if(from.getLeft() == null && from.getRight() == null) {
return from;
}
INDArray hyperPlane = planes.getHyperPlaneAt(from.getDepth());
double dist = computeDistance(similarityFunction,x,hyperPlane);
if(dist <= from.getMedian()) {
return query(from.getLeft(),planes,x,similarityFunction);
}
else {
return query(from.getRight(),planes,x,similarityFunction);
}
}
/**
* Compute the distance between 2 vectors
* given a function name. Valid function names:
* euclidean: euclidean distance
* cosinedistance: cosine distance
* cosine similarity: cosine similarity
* manhattan: manhattan distance
* jaccard: jaccard distance
* hamming: hamming distance
* @param function the function to use (default euclidean distance)
* @param x the first vector
* @param y the second vector
* @return the distance between the 2 vectors given the inputs
*/
public static INDArray computeDistanceMulti(String function,INDArray x,INDArray y,INDArray result) {
ReduceOp op = (ReduceOp) getOp(function, x, y, result);
op.setDimensions(1);
Nd4j.getExecutioner().exec(op);
return op.z();
}
/**
/**
* Compute the distance between 2 vectors
* given a function name. Valid function names:
* euclidean: euclidean distance
* cosinedistance: cosine distance
* cosine similarity: cosine similarity
* manhattan: manhattan distance
* jaccard: jaccard distance
* hamming: hamming distance
* @param function the function to use (default euclidean distance)
* @param x the first vector
* @param y the second vector
* @return the distance between the 2 vectors given the inputs
*/
public static double computeDistance(String function,INDArray x,INDArray y,INDArray result) {
ReduceOp op = (ReduceOp) getOp(function, x, y, result);
Nd4j.getExecutioner().exec(op);
return op.z().getDouble(0);
}
/**
* Compute the distance between 2 vectors
* given a function name. Valid function names:
* euclidean: euclidean distance
* cosinedistance: cosine distance
* cosine similarity: cosine similarity
* manhattan: manhattan distance
* jaccard: jaccard distance
* hamming: hamming distance
* @param function the function to use (default euclidean distance)
* @param x the first vector
* @param y the second vector
* @return the distance between the 2 vectors given the inputs
*/
public static double computeDistance(String function,INDArray x,INDArray y) {
return computeDistance(function,x,y,Nd4j.scalar(0.0));
}
/**
* Initialize the tree given the input parameters
* @param tree the tree to initialize
* @param from the starting node
* @param planes the hyper planes to use (vector space for similarity)
* @param X the input data
* @param maxSize the max number of indices on a given leaf node
* @param depth the current depth of the tree
* @param similarityFunction the similarity function to use
*/
public static void buildTree(RPTree tree,
RPNode from,
RPHyperPlanes planes,
INDArray X,
int maxSize,
int depth,
String similarityFunction) {
if(from.getIndices().size() <= maxSize) {
//slimNode
slimNode(from);
return;
}
List<Double> distances = new ArrayList<>();
RPNode left = new RPNode(tree,depth + 1);
RPNode right = new RPNode(tree,depth + 1);
if(planes.getWholeHyperPlane() == null || depth >= planes.getWholeHyperPlane().rows()) {
planes.addRandomHyperPlane();
}
INDArray hyperPlane = planes.getHyperPlaneAt(depth);
for(int i = 0; i < from.getIndices().size(); i++) {
double cosineSim = computeDistance(similarityFunction,hyperPlane,X.slice(from.getIndices().get(i)));
distances.add(cosineSim);
}
Collections.sort(distances);
from.setMedian(distances.get(distances.size() / 2));
for(int i = 0; i < from.getIndices().size(); i++) {
double cosineSim = computeDistance(similarityFunction,hyperPlane,X.slice(from.getIndices().get(i)));
if(cosineSim <= from.getMedian()) {
left.getIndices().add(from.getIndices().get(i));
}
else {
right.getIndices().add(from.getIndices().get(i));
}
}
//failed split
if(left.getIndices().isEmpty() || right.getIndices().isEmpty()) {
slimNode(from);
return;
}
from.setLeft(left);
from.setRight(right);
slimNode(from);
buildTree(tree,left,planes,X,maxSize,depth + 1,similarityFunction);
buildTree(tree,right,planes,X,maxSize,depth + 1,similarityFunction);
}
/**
* Scan for leaves accumulating
* the nodes in the passed in list
* @param nodes the nodes so far
* @param scan the tree to scan
*/
public static void scanForLeaves(List<RPNode> nodes,RPTree scan) {
scanForLeaves(nodes,scan.getRoot());
}
/**
* Scan for leaves accumulating
* the nodes in the passed in list
* @param nodes the nodes so far
*/
public static void scanForLeaves(List<RPNode> nodes,RPNode current) {
if(current.getLeft() == null && current.getRight() == null)
nodes.add(current);
if(current.getLeft() != null)
scanForLeaves(nodes,current.getLeft());
if(current.getRight() != null)
scanForLeaves(nodes,current.getRight());
}
/**
* Prune indices from the given node
* when it's a leaf
* @param node the node to prune
*/
public static void slimNode(RPNode node) {
if(node.getRight() != null && node.getLeft() != null) {
node.getIndices().clear();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.impl.cloud;
import java.util.List;
import java.util.UUID;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.cloud.ServiceDefinition;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.engine.DefaultChannel;
import org.apache.camel.model.cloud.ServiceCallConfigurationDefinition;
import org.apache.camel.model.cloud.ServiceCallDefinitionConstants;
import org.apache.camel.model.cloud.ServiceCallExpressionConfiguration;
import org.apache.camel.model.language.SimpleExpression;
import org.apache.camel.support.DefaultExchange;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ServiceCallConfigurationTest {
// ****************************************
// test default resolution
// ****************************************
@Test
public void testDynamicUri() throws Exception {
StaticServiceDiscovery sd = new StaticServiceDiscovery();
sd.addServer("scall@127.0.0.1:8080");
sd.addServer("scall@127.0.0.1:8081");
ServiceCallConfigurationDefinition conf = new ServiceCallConfigurationDefinition();
conf.setServiceDiscovery(sd);
conf.setComponent("mock");
DefaultCamelContext context = new DefaultCamelContext();
context.setServiceCallConfiguration(conf);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall("scall", "scall/api/${header.customerId}");
}
});
context.start();
MockEndpoint mock = context.getEndpoint("mock:127.0.0.1:8080/api/123", MockEndpoint.class);
mock.expectedMessageCount(1);
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(sd, loadBalancer.getServiceDiscovery());
// call the route
context.createFluentProducerTemplate().to("direct:start").withHeader("customerId", "123").send();
// the service should call the mock
mock.assertIsSatisfied();
context.stop();
}
@Test
public void testDefaultConfigurationFromCamelContext() throws Exception {
StaticServiceDiscovery sd = new StaticServiceDiscovery();
sd.addServer("service@127.0.0.1:8080");
sd.addServer("service@127.0.0.1:8081");
BlacklistServiceFilter sf = new BlacklistServiceFilter();
sf.addServer("*@127.0.0.1:8080");
ServiceCallConfigurationDefinition conf = new ServiceCallConfigurationDefinition();
conf.setServiceDiscovery(sd);
conf.setServiceFilter(sf);
DefaultCamelContext context = new DefaultCamelContext();
context.setServiceCallConfiguration(conf);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall()
.name("scall")
.component("file")
.end();
}
});
context.start();
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(sd, loadBalancer.getServiceDiscovery());
assertEquals(sf, loadBalancer.getServiceFilter());
context.stop();
}
@Test
public void testDefaultConfigurationFromRegistryWithDefaultName() throws Exception {
StaticServiceDiscovery sd = new StaticServiceDiscovery();
sd.addServer("service@127.0.0.1:8080");
sd.addServer("service@127.0.0.1:8081");
BlacklistServiceFilter sf = new BlacklistServiceFilter();
sf.addServer("*@127.0.0.1:8080");
ServiceCallConfigurationDefinition conf = new ServiceCallConfigurationDefinition();
conf.setServiceDiscovery(sd);
conf.serviceFilter(sf);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall()
.name("scall")
.component("file")
.end();
}
});
context.getRegistry().bind(ServiceCallDefinitionConstants.DEFAULT_SERVICE_CALL_CONFIG_ID, conf);
context.start();
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(sd, loadBalancer.getServiceDiscovery());
assertEquals(sf, loadBalancer.getServiceFilter());
context.stop();
}
@Test
public void testDefaultConfigurationFromRegistryWithNonDefaultName() throws Exception {
StaticServiceDiscovery sd = new StaticServiceDiscovery();
sd.addServer("service@127.0.0.1:8080");
sd.addServer("service@127.0.0.1:8081");
BlacklistServiceFilter sf = new BlacklistServiceFilter();
sf.addServer("*@127.0.0.1:8080");
ServiceCallConfigurationDefinition conf = new ServiceCallConfigurationDefinition();
conf.setServiceDiscovery(sd);
conf.serviceFilter(sf);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall()
.name("scall")
.component("file")
.end();
}
});
context.getRegistry().bind(UUID.randomUUID().toString(), conf);
context.start();
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(sd, loadBalancer.getServiceDiscovery());
assertEquals(sf, loadBalancer.getServiceFilter());
context.stop();
}
// ****************************************
// test mixed resolution
// ****************************************
@Test
public void testMixedConfiguration() throws Exception {
// Default
StaticServiceDiscovery defaultServiceDiscovery = new StaticServiceDiscovery();
defaultServiceDiscovery.addServer("service@127.0.0.1:8080");
defaultServiceDiscovery.addServer("service@127.0.0.1:8081");
defaultServiceDiscovery.addServer("service@127.0.0.1:8082");
BlacklistServiceFilter defaultServiceFilter = new BlacklistServiceFilter();
defaultServiceFilter.addServer("*@127.0.0.1:8080");
ServiceCallConfigurationDefinition defaultConfiguration = new ServiceCallConfigurationDefinition();
defaultConfiguration.setServiceDiscovery(defaultServiceDiscovery);
defaultConfiguration.serviceFilter(defaultServiceFilter);
// Named
BlacklistServiceFilter namedServiceFilter = new BlacklistServiceFilter();
namedServiceFilter.addServer("*@127.0.0.1:8081");
ServiceCallConfigurationDefinition namedConfiguration = new ServiceCallConfigurationDefinition();
namedConfiguration.serviceFilter(namedServiceFilter);
// Local
StaticServiceDiscovery localServiceDiscovery = new StaticServiceDiscovery();
localServiceDiscovery.addServer("service@127.0.0.1:8080");
localServiceDiscovery.addServer("service@127.0.0.1:8081");
localServiceDiscovery.addServer("service@127.0.0.1:8082");
localServiceDiscovery.addServer("service@127.0.0.1:8084");
// Camel context
DefaultCamelContext context = new DefaultCamelContext();
context.setServiceCallConfiguration(defaultConfiguration);
context.addServiceCallConfiguration("named", namedConfiguration);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:default")
.id("default")
.serviceCall()
.name("default-scall")
.component("file")
.end();
from("direct:named")
.id("named")
.serviceCall()
.serviceCallConfiguration("named")
.name("named-scall")
.component("file")
.end();
from("direct:local")
.id("local")
.serviceCall()
.serviceCallConfiguration("named")
.name("local-scall")
.component("file")
.serviceDiscovery(localServiceDiscovery)
.end();
}
});
context.start();
{
// Default
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(defaultServiceDiscovery, loadBalancer.getServiceDiscovery());
assertEquals(defaultServiceFilter, loadBalancer.getServiceFilter());
}
{
// Named
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("named"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(defaultServiceDiscovery, loadBalancer.getServiceDiscovery());
assertEquals(namedServiceFilter, loadBalancer.getServiceFilter());
}
{
// Local
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("local"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
DefaultServiceLoadBalancer loadBalancer = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertEquals(localServiceDiscovery, loadBalancer.getServiceDiscovery());
assertEquals(namedServiceFilter, loadBalancer.getServiceFilter());
}
context.stop();
}
// **********************************************
// test placeholders
// **********************************************
@Test
public void testPlaceholders() throws Exception {
DefaultCamelContext context = null;
try {
System.setProperty("scall.name", "service-name");
System.setProperty("scall.scheme", "file");
System.setProperty("scall.servers1", "hello-service@localhost:8081,hello-service@localhost:8082");
System.setProperty("scall.servers2", "hello-svc@localhost:8083,hello-svc@localhost:8084");
System.setProperty("scall.filter", "hello-svc@localhost:8083");
ServiceCallConfigurationDefinition global = new ServiceCallConfigurationDefinition();
global.blacklistFilter().servers("{{scall.filter}}");
context = new DefaultCamelContext();
context.setServiceCallConfiguration(global);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall()
.name("{{scall.name}}")
.component("{{scall.scheme}}")
.uri("direct:{{scall.name}}")
.staticServiceDiscovery()
.servers("{{scall.servers1}}")
.servers("{{scall.servers2}}")
.end()
.end();
}
});
context.start();
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertTrue(proc.getLoadBalancer() instanceof DefaultServiceLoadBalancer);
assertEquals("service-name", proc.getName());
assertEquals("file", proc.getScheme());
assertEquals("direct:service-name", proc.getUri());
DefaultServiceLoadBalancer lb = (DefaultServiceLoadBalancer) proc.getLoadBalancer();
assertTrue(lb.getServiceFilter() instanceof BlacklistServiceFilter);
BlacklistServiceFilter filter = (BlacklistServiceFilter) lb.getServiceFilter();
List<ServiceDefinition> blacklist = filter.getBlacklistedServices();
assertEquals(1, blacklist.size());
assertTrue(lb.getServiceDiscovery() instanceof StaticServiceDiscovery);
Exchange exchange = new DefaultExchange(context);
List<ServiceDefinition> services1 = lb.getServiceDiscovery().getServices("hello-service");
assertEquals(2, filter.apply(exchange, services1).size());
List<ServiceDefinition> services2 = lb.getServiceDiscovery().getServices("hello-svc");
assertEquals(1, filter.apply(exchange, services2).size());
} finally {
if (context != null) {
context.stop();
}
// Cleanup system properties
System.clearProperty("scall.name");
System.clearProperty("scall.scheme");
System.clearProperty("scall.servers1");
System.clearProperty("scall.servers2");
System.clearProperty("scall.filter");
}
context.stop();
}
// **********************************************
// test placeholders
// **********************************************
@Test
public void testExpression() throws Exception {
DefaultCamelContext context = null;
try {
ServiceCallConfigurationDefinition config = new ServiceCallConfigurationDefinition();
config.setServiceDiscovery(new StaticServiceDiscovery());
config.setExpressionConfiguration(
new ServiceCallExpressionConfiguration().expression(
new SimpleExpression(
"file:${header.CamelServiceCallServiceHost}:${header.CamelServiceCallServicePort}")));
context = new DefaultCamelContext();
context.setServiceCallConfiguration(config);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.routeId("default")
.serviceCall("scall");
}
});
context.start();
DefaultServiceCallProcessor proc = findServiceCallProcessor(context.getRoute("default"));
assertNotNull(proc);
assertEquals("file:${header.CamelServiceCallServiceHost}:${header.CamelServiceCallServicePort}",
proc.getExpression().toString());
} finally {
if (context != null) {
context.stop();
}
}
context.stop();
}
// **********************************************
// Helper
// **********************************************
private DefaultServiceCallProcessor findServiceCallProcessor(Route route) {
for (Processor processor : route.navigate().next()) {
if (processor instanceof DefaultChannel) {
processor = ((DefaultChannel) processor).getNextProcessor();
}
if (processor instanceof DefaultServiceCallProcessor) {
return (DefaultServiceCallProcessor) processor;
}
}
throw new IllegalStateException("Unable to find a ServiceCallProcessor");
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.lucene.analysis.miscellaneous;
import org.apache.lucene.util.RamUsageEstimator;
/**
* A Trie structure for analysing byte streams for duplicate sequences. Bytes
* from a stream are added one at a time using the addByte method and the number
* of times it has been seen as part of a sequence is returned.
*
* The minimum required length for a duplicate sequence detected is 6 bytes.
*
* The design goals are to maximize speed of lookup while minimizing the space
* required to do so. This has led to a hybrid solution for representing the
* bytes that make up a sequence in the trie.
*
* If we have 6 bytes in sequence e.g. abcdef then they are represented as
* object nodes in the tree as follows:
* <p>
* (a)-(b)-(c)-(def as an int)
* <p>
*
*
* {@link RootTreeNode} objects are used for the first two levels of the tree
* (representing bytes a and b in the example sequence). The combinations of
* objects at these 2 levels are few so internally these objects allocate an
* array of 256 child node objects to quickly address children by indexing
* directly into the densely packed array using a byte value. The third level in
* the tree holds {@link LightweightTreeNode} nodes that have few children
* (typically much less than 256) and so use a dynamically-grown array to hold
* child nodes as simple int primitives. These ints represent the final 3 bytes
* of a sequence and also hold a count of the number of times the entire sequence
* path has been visited (count is a single byte).
* <p>
* The Trie grows indefinitely as more content is added and while theoretically
* it could be massive (a 6-depth tree could produce 256^6 nodes) non-random
* content e.g English text contains fewer variations.
* <p>
* In future we may look at using one of these strategies when memory is tight:
* <ol>
* <li>auto-pruning methods to remove less-visited parts of the tree
* <li>auto-reset to wipe the whole tree and restart when a memory threshold is
* reached
* <li>halting any growth of the tree
* </ol>
*
* Tests on real-world-text show that the size of the tree is a multiple of the
* input text where that multiplier varies between 10 and 5 times as the content
* size increased from 10 to 100 megabytes of content.
*
*/
public class DuplicateByteSequenceSpotter {
public static final int TREE_DEPTH = 6;
// The maximum number of repetitions that are counted
public static final int MAX_HIT_COUNT = 255;
private final TreeNode root;
private boolean sequenceBufferFilled = false;
private final byte[] sequenceBuffer = new byte[TREE_DEPTH];
private int nextFreePos = 0;
// ==Performance info
private final int[] nodesAllocatedByDepth;
private int nodesResizedByDepth;
// ==== RAM usage estimation settings ====
private long bytesAllocated;
// Root node object plus inner-class reference to containing "this"
// (profiler suggested this was a cost)
static final long TREE_NODE_OBJECT_SIZE = RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + RamUsageEstimator.NUM_BYTES_OBJECT_REF;
// A TreeNode specialization with an array ref (dynamically allocated and
// fixed-size)
static final long ROOT_TREE_NODE_OBJECT_SIZE = TREE_NODE_OBJECT_SIZE + RamUsageEstimator.NUM_BYTES_OBJECT_REF;
// A KeyedTreeNode specialization with an array ref (dynamically allocated
// and grown)
static final long LIGHTWEIGHT_TREE_NODE_OBJECT_SIZE = TREE_NODE_OBJECT_SIZE + RamUsageEstimator.NUM_BYTES_OBJECT_REF;
// A KeyedTreeNode specialization with a short-based hit count and a
// sequence of bytes encoded as an int
static final long LEAF_NODE_OBJECT_SIZE = TREE_NODE_OBJECT_SIZE + Short.BYTES + Integer.BYTES;
public DuplicateByteSequenceSpotter() {
this.nodesAllocatedByDepth = new int[4];
this.bytesAllocated = 0;
root = new RootTreeNode((byte) 1, null, 0);
}
/**
* Reset the sequence detection logic to avoid any continuation of the
* immediately previous bytes. A minimum of dupSequenceSize bytes need to be
* added before any new duplicate sequences will be reported.
* Hit counts are not reset by calling this method.
*/
public void startNewSequence() {
sequenceBufferFilled = false;
nextFreePos = 0;
}
/**
* Add a byte to the sequence.
* @param b
* the next byte in a sequence
* @return number of times this byte and the preceding 6 bytes have been
* seen before as a sequence (only counts up to 255)
*
*/
public short addByte(byte b) {
// Add latest byte to circular buffer
sequenceBuffer[nextFreePos] = b;
nextFreePos++;
if (nextFreePos >= sequenceBuffer.length) {
nextFreePos = 0;
sequenceBufferFilled = true;
}
if (sequenceBufferFilled == false) {
return 0;
}
TreeNode node = root;
// replay updated sequence of bytes represented in the circular
// buffer starting from the tail
int p = nextFreePos;
// The first tier of nodes are addressed using individual bytes from the
// sequence
node = node.add(sequenceBuffer[p], 0);
p = nextBufferPos(p);
node = node.add(sequenceBuffer[p], 1);
p = nextBufferPos(p);
node = node.add(sequenceBuffer[p], 2);
// The final 3 bytes in the sequence are represented in an int
// where the 4th byte will contain a hit count.
p = nextBufferPos(p);
int sequence = 0xFF & sequenceBuffer[p];
p = nextBufferPos(p);
sequence = sequence << 8 | (0xFF & sequenceBuffer[p]);
p = nextBufferPos(p);
sequence = sequence << 8 | (0xFF & sequenceBuffer[p]);
return (short) (node.add(sequence << 8) - 1);
}
private int nextBufferPos(int p) {
p++;
if (p >= sequenceBuffer.length) {
p = 0;
}
return p;
}
/**
* Base class for nodes in the tree. Subclasses are optimised for use at
* different locations in the tree - speed-optimized nodes represent
* branches near the root while space-optimized nodes are used for deeper
* leaves/branches.
*/
abstract class TreeNode {
TreeNode(byte key, TreeNode parentNode, int depth) {
nodesAllocatedByDepth[depth]++;
}
public abstract TreeNode add(byte b, int depth);
/**
*
* @param byteSequence
* a sequence of bytes encoded as an int
* @return the number of times the full sequence has been seen (counting
* up to a maximum of 32767).
*/
public abstract short add(int byteSequence);
}
// Node implementation for use at the root of the tree that sacrifices space
// for speed.
class RootTreeNode extends TreeNode {
// A null-or-256 sized array that can be indexed into using a byte for
// fast access.
// Being near the root of the tree it is expected that this is a
// non-sparse array.
TreeNode[] children;
RootTreeNode(byte key, TreeNode parentNode, int depth) {
super(key, parentNode, depth);
bytesAllocated += ROOT_TREE_NODE_OBJECT_SIZE;
}
public TreeNode add(byte b, int depth) {
if (children == null) {
children = new TreeNode[256];
bytesAllocated += (RamUsageEstimator.NUM_BYTES_OBJECT_REF * 256);
}
int bIndex = 0xFF & b;
TreeNode node = children[bIndex];
if (node == null) {
if (depth <= 1) {
// Depths 0 and 1 use RootTreeNode impl and create
// RootTreeNodeImpl children
node = new RootTreeNode(b, this, depth);
} else {
// Deeper-level nodes are less visited but more numerous
// so use a more space-friendly data structure
node = new LightweightTreeNode(b, this, depth);
}
children[bIndex] = node;
}
return node;
}
@Override
public short add(int byteSequence) {
throw new UnsupportedOperationException("Root nodes do not support byte sequences encoded as integers");
}
}
// Node implementation for use by the depth 3 branches of the tree that
// sacrifices speed for space.
final class LightweightTreeNode extends TreeNode {
// An array dynamically resized but frequently only sized 1 as most
// sequences leading to end leaves are one-off paths.
// It is scanned for matches sequentially and benchmarks showed
// that sorting contents on insertion didn't improve performance.
int[] children = null;
LightweightTreeNode(byte key, TreeNode parentNode, int depth) {
super(key, parentNode, depth);
bytesAllocated += LIGHTWEIGHT_TREE_NODE_OBJECT_SIZE;
}
@Override
public short add(int byteSequence) {
if (children == null) {
// Create array adding new child with the byte sequence combined with hitcount of 1.
// Most nodes at this level we expect to have only 1 child so we start with the
// smallest possible child array.
children = new int[1];
bytesAllocated += RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + Integer.BYTES;
children[0] = byteSequence + 1;
return 1;
}
// Find existing child and if discovered increment count
for (int i = 0; i < children.length; i++) {
int child = children[i];
if (byteSequence == (child & 0xFFFFFF00)) {
int hitCount = child & 0xFF;
if (hitCount < MAX_HIT_COUNT) {
children[i]++;
}
return (short) (hitCount + 1);
}
}
// Grow array adding new child
int[] newChildren = new int[children.length + 1];
bytesAllocated += Integer.BYTES;
System.arraycopy(children, 0, newChildren, 0, children.length);
children = newChildren;
// Combine the byte sequence with a hit count of 1 into an int.
children[newChildren.length - 1] = byteSequence + 1;
nodesResizedByDepth++;
return 1;
}
@Override
public TreeNode add(byte b, int depth) {
throw new UnsupportedOperationException("Leaf nodes do not take byte sequences");
}
}
public final long getEstimatedSizeInBytes() {
return bytesAllocated;
}
/**
* @return Performance info - the number of nodes allocated at each depth
*/
public int[] getNodesAllocatedByDepth() {
return nodesAllocatedByDepth.clone();
}
/**
* @return Performance info - the number of resizing of children arrays, at
* each depth
*/
public int getNodesResizedByDepth() {
return nodesResizedByDepth;
}
}
| |
package net.violet.platform.daemons.crawlers;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.violet.common.StringShop;
import net.violet.db.records.Record.RecordWalker;
import net.violet.platform.applications.GmailTwitterHandler;
import net.violet.platform.applications.VActionFreeHandler;
import net.violet.platform.applications.VActionFullHandler;
import net.violet.platform.datamodel.Application;
import net.violet.platform.datamodel.ApplicationSetting;
import net.violet.platform.datamodel.Content;
import net.violet.platform.datamodel.Feed;
import net.violet.platform.datamodel.Subscription;
import net.violet.platform.datamodel.VAction;
import net.violet.platform.datamodel.factories.Factories;
import net.violet.platform.datamodel.factories.implementations.VActionFactoryImpl;
/**
* Migration crawler to the new subscription settings system
*/
public class FeedsCrawler {
private static abstract class AbstractRssPodcastWalker implements RecordWalker<VAction> {
private final Feed.Type type;
private final Feed.AccessRight accessRight;
private final Executor executor;
private final int nbItems;
protected AbstractRssPodcastWalker(Feed.Type type, Feed.AccessRight accessRight, Executor executor) {
this.type = type;
this.accessRight = accessRight;
this.executor = executor;
this.nbItems = type == Feed.Type.RSS ? 30 : 1;
}
protected void doSomethingSpecial(VAction theAction, Feed newFeed) {
return;
}
public void process(final VAction theAction) {
this.executor.execute(new Runnable() {
public void run() {
if (!theAction.getUrl().equals(StringShop.EMPTY_STRING)) {
// new feed creation
Feed newFeed = Factories.FEED.create(theAction.getUrl().trim(), AbstractRssPodcastWalker.this.type, theAction.getLang(), AbstractRssPodcastWalker.this.accessRight);
if (newFeed == null) { // creation failed, but the feed may already exist
newFeed = Factories.FEED.findByUrlAndType(theAction.getUrl().trim(), AbstractRssPodcastWalker.this.type);
if (newFeed == null) { // no, it's a real failure
System.err.println("Failed : " + theAction.getId() + " " + theAction.getUrl());
return;
}
} else {
final Date lastModified = theAction.getLastModified();
final Timestamp newLastModified = (lastModified == null) ? null : new Timestamp(lastModified.getTime());
newFeed.updateInformation(theAction.getETag(), newLastModified);
}
doSomethingSpecial(theAction, newFeed); // special treatment for the free feeds
// now, we can take care of the full applications using this action as feed
final Application theAppli = (AbstractRssPodcastWalker.this.type == Feed.Type.PODCAST) ? Application.NativeApplication.PODCAST_FULL.getApplication() : Application.NativeApplication.RSS_FULL.getApplication();
final Feed theRealFeed = newFeed; // trick to make it available in the anonymous class
for (final Subscription aSubscription : Factories.SUBSCRIPTION.findAllByApplication(theAppli)) {
final Map<String, Object> currentSettings = aSubscription.getSettings();
if (!currentSettings.containsKey(VActionFullHandler.FEED) && currentSettings.get(VActionFullHandler.ACTION).toString().equals(theAction.getId().toString())) {
currentSettings.put(VActionFullHandler.FEED, theRealFeed.getId().toString());
aSubscription.setSettings(currentSettings);
}
}
// try to rescue the contents
final List<Content> existingContents = Factories.CONTENT.findMostRecentsByAction(theAction, AbstractRssPodcastWalker.this.nbItems, true);
Collections.reverse(existingContents);
for (final Content aContent : existingContents) {
Factories.FEED_ITEM.create(newFeed, Collections.singletonList(aContent.getFile()), aContent.getTitle(), aContent.getLink(), aContent.getId_xml());
}
}
}
});
}
}
private static class RssPodcastFreeWalker extends AbstractRssPodcastWalker {
private RssPodcastFreeWalker(Feed.Type type, Executor executor) {
super(type, Feed.AccessRight.FREE, executor);
}
@Override
public void doSomethingSpecial(VAction theAction, Feed newFeed) {
final Application theApplicationUsingThisAction = Factories.APPLICATION.find(theAction.getApplicationId());
if ((theApplicationUsingThisAction != null) && ((Application.NativeApplication.findByApplication(theApplicationUsingThisAction) == Application.NativeApplication.RSS_FREE) || (Application.NativeApplication.findByApplication(theApplicationUsingThisAction) == Application.NativeApplication.PODCAST_FREE))) {
if (Factories.APPLICATION_SETTING.findByApplicationAndKey(theApplicationUsingThisAction, ApplicationSetting.FeedHandler.FEED_ID) == null) {
Factories.APPLICATION_SETTING.create(theApplicationUsingThisAction, ApplicationSetting.FeedHandler.FEED_ID, newFeed.getId().toString());
}
}
// Here the application free has a link to the feed
// We edit the free subscriptions to this application, only nbNews is required
for (final Subscription aSubscription : Factories.SUBSCRIPTION.findAllByApplication(theApplicationUsingThisAction)) {
final Object nbNewsSetting = aSubscription.getSettings().get(VActionFreeHandler.NB_NEWS);
aSubscription.setSettings(Collections.singletonMap(VActionFreeHandler.NB_NEWS, nbNewsSetting.toString()));
}
}
}
private static class RssPodcastFullWalker extends AbstractRssPodcastWalker {
private RssPodcastFullWalker(Feed.Type type, Executor executor) {
super(type, Feed.AccessRight.FULL, executor);
}
}
private static class GmailTwitterWalker implements RecordWalker<Subscription> {
private final Executor executor;
private GmailTwitterWalker(Executor executor) {
this.executor = executor;
}
public void process(final Subscription inObject) {
this.executor.execute(new Runnable() {
public void run() {
final Map<String, Object> settings = new HashMap<String, Object>(inObject.getSettings());
settings.put(GmailTwitterHandler.LAST_ENTRY_ID, inObject.getSettings().get("id_last_news"));
inObject.setSettings(settings);
}
});
}
}
private static final Set<VAction> usedActions = Collections.synchronizedSet(new HashSet<VAction>());
// fills up usedActions, actions which are not in the set are unused and have to be removed
private static class RssPodcastFullSuppressor implements RecordWalker<Subscription> {
private final Executor executor;
private RssPodcastFullSuppressor(Executor executor) {
this.executor = executor;
}
public void process(final Subscription inObject) {
this.executor.execute(new Runnable() {
public void run() {
final Object actionSetting = inObject.getSettings().get(VActionFullHandler.ACTION);
if (actionSetting != null) {
final VAction action = Factories.VACTION.find(Long.parseLong(actionSetting.toString()));
if ((action != null) && (action.getAccess_right().equals("FULL"))) {
FeedsCrawler.usedActions.add(action);
}
}
}
});
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(50);
/** migration gmail/twitter **/
final GmailTwitterWalker gmailTwitterWalker = new GmailTwitterWalker(executor);
Factories.SUBSCRIPTION.walkByApplication(Application.NativeApplication.GMAIL.getApplication(), gmailTwitterWalker);
Factories.SUBSCRIPTION.walkByApplication(Application.NativeApplication.TWITTER.getApplication(), gmailTwitterWalker);
/** removed unused full actions **/
final RssPodcastFullSuppressor remover = new RssPodcastFullSuppressor(executor);
Factories.SUBSCRIPTION.walkByApplication(Application.NativeApplication.RSS_FULL.getApplication(), remover);
Factories.SUBSCRIPTION.walkByApplication(Application.NativeApplication.PODCAST_FULL.getApplication(), remover);
FeedsCrawler.waitForTermination(executor); // needs to wait for the executor to be terminated : the usedActions set will be fully populated then
Factories.VACTION.walk(new RecordWalker<VAction>() {
public void process(VAction inObject) {
if ((inObject.getAccess_right().equals("FULL")) && !FeedsCrawler.usedActions.contains(inObject)) {
inObject.delete();
}
}
});
/** rss/podcast free migration **/
executor = Executors.newFixedThreadPool(50);
((VActionFactoryImpl) Factories.VACTION).walkByServiceAndAccessRight(2, "FREE", new RssPodcastFreeWalker(Feed.Type.RSS, executor));
((VActionFactoryImpl) Factories.VACTION).walkByServiceAndAccessRight(1, "FREE", new RssPodcastFreeWalker(Feed.Type.PODCAST, executor));
FeedsCrawler.waitForTermination(executor); // have to wait for the free feed to be fully migrated before starting processing the full ones
/** rss/podcast full migration **/
executor = Executors.newFixedThreadPool(50);
((VActionFactoryImpl) Factories.VACTION).walkByServiceAndAccessRight(2, "FULL", new RssPodcastFullWalker(Feed.Type.RSS, executor));
((VActionFactoryImpl) Factories.VACTION).walkByServiceAndAccessRight(1, "FULL", new RssPodcastFullWalker(Feed.Type.PODCAST, executor));
FeedsCrawler.waitForTermination(executor);
}
private static void waitForTermination(ExecutorService executor) throws InterruptedException {
Thread.sleep(5000);
executor.shutdown();
System.err.println("executor shuted down");
while (!executor.isTerminated()) {
System.err.println("waiting for full termination");
executor.awaitTermination(10, TimeUnit.SECONDS);
}
System.err.println("Terminated");
}
}
| |
package edu.csh.chase.RestfulAPIConnector.JSONWrapper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public abstract class JSONWrapper {
private JSONException noObjectOrArrayExccetion = new JSONException("No JSONObjecr or JSONArray");
private JSONException noArrayExcetion = new JSONException("No JSONArray");
private boolean debugMode = false;
private final String TAG = "JSONWRAPPER";
/**
* Returns a new JSONObjectWrapper or JSONArrayWrapper from the given String
*
* @param string A valid JSONEncoded string of either a JSONObject or JSONArray
* @return A JSONObjectWrapper if the string was a JSONObject or JSONArrayWrapper if the string was a JSONArray
* @throws JSONException if the string could not be parsed into valid JSON
*/
public static JSONWrapper parseJSON(String string) throws JSONException {
try {
return new JSONObjectWrapper(string);
} catch (JSONException e) {
}
try {
return new JSONArrayWrapper(string);
} catch (JSONException e) {
}
throw new JSONException("Couldn't parse" + string);
}
/**
* Wraps the given JSONObject in a JSONObjectWrapper
*
* @param object The JSONObject to wrap
* @return The wrapped JSONObject
*/
public static JSONObjectWrapper wrapperFromObject(JSONObject object) {
return new JSONObjectWrapper(object);
}
/**
* Wraps the given JSONArray into a JSONArray
*
* @param array The JSONArray to wrap
* @return The wrapped JSONArray
*/
public static JSONArrayWrapper wrapperFromArray(JSONArray array) {
return new JSONArrayWrapper(array);
}
//***************************Debug functions****************************************************
/**
* Sets the debug mode. Defaults to false.
*
* @param debug true to print debug messages, false to not.
*/
public void setDebugMode(boolean debug) {
this.debugMode = debug;
}
protected void debug(String message) {
if (debugMode) {
Log.d(TAG, message);
}
}
//***************************Valid Stuff********************************************************
public abstract String getValidKey(String... keys);
/**
* Checks to see if the given key exists in the currently wrapped JSONItem
*
* @param key The key to check, can be a multikey
* @return true if the key exists, false otherwise
*/
public boolean has(String key) {
return getValidKey(key) != null;
}
//****************************PARSERS***********************************************************
protected Object parseKey(JSONWrapperKeyset keySet, JSONArray array) throws JSONException {
boolean hasNext = keySet.hasNext();
String key = keySet.next();
int arrayKey = -1;
debug("Trying key: " + key + " : With JSONArray");
try {
arrayKey = Integer.parseInt(key);
} catch (NumberFormatException ex) {
debug(key + " is not a valid array key");
throw new JSONException(key + " is not a valid key for array");
}
if (hasNext) {
if (isObjectJSONObject(array.get(arrayKey))) {
return parseKey(keySet, array.getJSONObject(arrayKey));
} else {
return parseKey(keySet, array.getJSONArray(arrayKey));
}
} else {
return array.get(arrayKey);
}
}
protected Object parseKey(JSONWrapperKeyset keySet, JSONObject object) throws JSONException {
boolean hasNext = keySet.hasNext();
String key = keySet.next();
debug("Trying key: " + key + " : On JSONObject");
if (hasNext) {
if (isObjectJSONObject(object.get(key))) {
return parseKey(keySet, object.getJSONObject(key));
} else {
return parseKey(keySet, object.getJSONArray(key));
}
} else {
return object.get(key);
}
}
protected boolean isObjectJSONObject(Object o) {
return o instanceof JSONObject;
}
//****************************Getters***********************************************************
/**
* Gets a standard java Object with the given key
*
* @param key The key to check, can be a multikey
* @return The Object found at the specific key
* @throws JSONException if the key does not exist
*/
public abstract Object getObject(String key) throws JSONException;
/**
* Gets the String at the specific key
*
* @param key The key to check, can be a multikey
* @return The String found at the key
* @throws JSONException if the key does not exist or is not a String
*/
public String getString(String key) throws JSONException {
Object string = this.getObject(key);
if (string == null) {
throw new JSONException("Invalid key:" + key);
}
return String.valueOf(string);
}
/**
* Gets the boolean at the specific key
*
* @param key The key to check, can be a multikey
* @return The boolean found at the key
* @throws JSONException if the key does not exist, or is not a boolean
*/
public boolean getBoolean(String key) throws JSONException {
Object bool = this.getObject(key);
if (bool == null) {
throw new JSONException("Invalid key:" + key);
}
return Boolean.parseBoolean(String.valueOf(bool));
}
/**
* Gets the int at the specific key
*
* @param key The key to check, can be a multikey
* @return the int found at the key
* @throws JSONException if the key does not exist, or is not an int
*/
public int getInt(String key) throws JSONException {
Object integer = this.getObject(key);
if (integer == null) {
throw new JSONException("Invalid key:" + key);
}
try {
return Integer.parseInt(String.valueOf(integer));
} catch (NumberFormatException ex) {
throw new JSONException(integer + " in an invalid int");
}
}
/**
* Gets the double at the specific key
*
* @param key The key to check, can be a multikey
* @return the double found at the key
* @throws JSONException if the key does not exist, or is not a double
*/
public double getDouble(String key) throws JSONException {
Object doubleValue = this.getObject(key);
if (doubleValue == null) {
throw new JSONException("Invalid key:" + key);
}
try {
return Double.parseDouble(String.valueOf(doubleValue));
} catch (NumberFormatException ex) {
throw new JSONException(doubleValue + " is an invalid double");
}
}
/**
* Gets the long found at the specific key
*
* @param key The key to check, can be a multikey
* @return the long found at the specific key
* @throws JSONException if the key is not found or was not a long
*/
public long getLong(String key) throws JSONException {
Object longValue = this.getObject(key);
if (longValue == null) {
throw new JSONException("Invalid key:" + key);
}
try {
return Long.parseLong(String.valueOf(longValue));
} catch (NumberFormatException ex) {
throw new JSONException(longValue.toString() + " is an invalid long");
}
}
/**
* Gets the JSONArray at the specific key
*
* @param key The key to check, can be a multikey
* @return The JSONArray found at the specific key
* @throws JSONException if the key is not found or not a JSONArray
*/
public JSONArray getJSONArray(String key) throws JSONException {
Object jsonArray = this.getObject(key);
if (jsonArray == null) {
throw new JSONException("Invalid key: " + key);
}
try {
return (JSONArray) jsonArray;
} catch (ClassCastException ex) {
throw new JSONException(key + " does not link to a JSONArray");
}
}
/**
* Gets the JSONObject at the given key
*
* @param key The key to check, can be a multikey
* @return The JSONObject found at the given key
* @throws JSONException if the key was invalid, or not a JSONObject
*/
public JSONObject getJSONObject(String key) throws JSONException {
Object jsonObject = getObject(key);
if (jsonObject == null) {
throw new JSONException("Invalid key: " + key);
}
try {
return (JSONObject) jsonObject;
} catch (ClassCastException ex) {
throw new JSONException(key + " does not link to a JSONArray");
}
}
/**
* Gets a JSONArray from a given key and converts it to a String Array for convience
*
* @param key The key to check, can be a multikey
* @return A String Array from a JSONArray at the given key
* @throws JSONException if the key was invalid or not a JSONArray
*/
public String[] getStringArray(String key) throws JSONException {
JSONArray jsonArray = this.getJSONArray(key);
if (jsonArray == null) {
throw new JSONException("Invalid key:" + key);
}
return JSONArrayToStringArray(jsonArray);
}
//**********getters with int
public Object getObject(int i) throws JSONException {
return null;
}
public JSONObject getJSONObject(int i) throws JSONException {
Object json = getObject(i);
if (json == null) {
throw new JSONException("Wrapper is not JSONArray");
}
try {
return (JSONObject) json;
} catch (ClassCastException ex) {
throw new JSONException(i + " does not link to a JSONArray");
}
}
public JSONArray getJSONArray(int i) throws JSONException {
Object array = getJSONObject(i);
if (array == null) {
throw new JSONException("Wrapper is not array");
}
try {
return (JSONArray) array;
} catch (ClassCastException ex) {
throw new JSONException(i + " does not link to a JSONArray");
}
}
public String[] getStringArray(int i) throws JSONException {
return JSONArrayToStringArray(getJSONArray(i));
}
public String getString(int i) throws JSONException {
Object string = getObject(i);
if (string == null) {
throw new JSONException("Wrapper is not JSONArray");
}
return String.valueOf(string);
}
public int getInt(int i) throws JSONException {
try {
return Integer.parseInt(String.valueOf(getObject(i)));
} catch (NumberFormatException ex) {
throw new JSONException("Couldn't convert to int");
}
}
public double getDouble(int i) throws JSONException {
try {
return Double.parseDouble(String.valueOf(getObject(i)));
} catch (NumberFormatException ex) {
throw new JSONException("Couldn't convert to double");
}
}
public long getLong(int i) throws JSONException {
try {
return Long.parseLong(String.valueOf(getObject(i)));
} catch (NumberFormatException ex) {
throw new JSONException("Couldn't convert to long");
}
}
public boolean getBoolean(int i) throws JSONException {
return Boolean.parseBoolean(String.valueOf(getObject(i)));
}
//************************checkAndGetters*******************************************************
public abstract Object checkAndGetObject(Object failed, String... keys);
public JSONObject checkAndGetJSONObject(JSONObject failed, String... keys) {
try {
return new JSONObject(String.valueOf(checkAndGetObject(failed, keys)));
} catch (JSONException e) {
debug("Couldn't convert to JSONObject");
}
return failed;
}
public long checkAndGetLong(long failed, String... keys) {
try {
return Long.parseLong(String.valueOf(checkAndGetObject(failed, keys)));
} catch (NumberFormatException ex) {
debug("Couldn't convert to long");
}
return failed;
}
public String checkAndGetString(String failed, String... keys) {
String returned = String.valueOf(checkAndGetObject(failed, keys));
return "null".equals(returned) ? failed : returned;
}
public String[] checkAndGetStringArray(String[] failed, String... keys) {
JSONArray array = checkAndGetJSONArray(null, keys);
if (array == null) {
return failed;
}
return JSONArrayToStringArray(array);
}
public JSONArray checkAndGetJSONArray(JSONArray failed, String... keys) {
try {
return new JSONArray(String.valueOf(checkAndGetObject(failed, keys)));
} catch (JSONException e) {
debug("Couldn't convernt to JSONArray");
}
return failed;
}
public double checkAndGetDouble(double failed, String... keys) {
try {
return Double.parseDouble(String.valueOf(checkAndGetObject(failed, keys)));
} catch (NumberFormatException e) {
debug("Couldn't convert to double");
}
return failed;
}
public int checkAndGetInt(int failed, String... keys) {
try {
return Integer.parseInt(String.valueOf(checkAndGetObject(failed, keys)));
} catch (NumberFormatException ex) {
debug("Item not an int");
}
return failed;
}
public boolean checkAndGetBoolean(boolean failed, String... keys) {
return Boolean.parseBoolean(String.valueOf(checkAndGetObject(failed, keys)));
}
public int length() {
return -1;
}
public boolean isValid() {
return false;
}
private String[] JSONArrayToStringArray(JSONArray array) {
String[] data = new String[array.length()];
for (int z = 0; z < array.length(); z++) {
try {
data[z] = String.valueOf(array.get(z));
} catch (JSONException e) {
}
}
return data;
}
public String toString() {
return "Invalid JSONWrapper";
}
}
| |
package org.holoeverywhere.app;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collection;
import org.holoeverywhere.ThemeManager;
import org.holoeverywhere.addon.AddonSherlock;
import org.holoeverywhere.addon.AddonSherlock.AddonSherlockA;
import org.holoeverywhere.addon.IAddon;
import org.holoeverywhere.addon.IAddonActivity;
import org.holoeverywhere.addon.IAddonBasicAttacher;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.v4.app._HoloActivity;
import android.view.KeyEvent;
import android.view.View;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.internal.view.menu.MenuItemWrapper;
import com.actionbarsherlock.internal.view.menu.MenuWrapper;
import com.actionbarsherlock.view.ActionMode;
public abstract class Activity extends _HoloActivity {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public static @interface Addons {
public String[] value();
}
private final class FindViewAction extends AddonCallback<IAddonActivity> {
private int mId;
private View mView;
@Override
public boolean action(IAddonActivity addon) {
return (mView = addon.findViewById(mId)) != null;
}
@Override
public boolean post() {
return (mView = getWindow().findViewById(mId)) != null;
}
}
private final class KeyEventAction extends AddonCallback<IAddonActivity> {
private KeyEvent mEvent;
@Override
public boolean action(IAddonActivity addon) {
return addon.dispatchKeyEvent(mEvent);
}
@Override
public boolean post() {
return Activity.super.dispatchKeyEvent(mEvent);
}
}
public static final String ADDON_ROBOGUICE = "Roboguice";
public static final String ADDON_SHERLOCK = "Sherlock";
public static final String ADDON_SLIDER = "Slider";
/**
* Use {@link #ADDON_SLIDER} instead
*/
@Deprecated
public static final String ADDON_SLIDING_MENU = ADDON_SLIDER;
public static final String ADDON_TABBER = "Tabber";
private final IAddonBasicAttacher<IAddonActivity, Activity> mAttacher =
new IAddonBasicAttacher<IAddonActivity, Activity>(this);
private boolean mCreatedByThemeManager = false;
private final FindViewAction mFindViewAction = new FindViewAction();
private final KeyEventAction mKeyEventAction = new KeyEventAction();
@Override
public <T extends IAddonActivity> T addon(Class<? extends IAddon> clazz) {
return mAttacher.addon(clazz);
}
@Override
public void addon(Collection<Class<? extends IAddon>> classes) {
mAttacher.addon(classes);
}
@Override
public <T extends IAddonActivity> T addon(String classname) {
return mAttacher.addon(classname);
}
public AddonSherlockA addonSherlock() {
return addon(AddonSherlock.class);
}
@Override
public void closeOptionsMenu() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.closeOptionsMenu();
}
@Override
public void justPost() {
Activity.super.closeOptionsMenu();
}
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
mKeyEventAction.mEvent = event;
return performAddonAction(mKeyEventAction);
}
@Override
public View findViewById(int id) {
mFindViewAction.mView = null;
mFindViewAction.mId = id;
performAddonAction(mFindViewAction);
return mFindViewAction.mView;
}
@Override
public ActionBar getSupportActionBar() {
return addonSherlock().getActionBar();
}
public Bundle instanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
return savedInstanceState;
}
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(ThemeManager.KEY_INSTANCE_STATE)) {
return extras.getBundle(ThemeManager.KEY_INSTANCE_STATE);
}
return null;
}
@Override
public boolean isAddonAttached(Class<? extends IAddon> clazz) {
return mAttacher.isAddonAttached(clazz);
}
public boolean isCreatedByThemeManager() {
return mCreatedByThemeManager;
}
@Override
public void lockAttaching() {
mAttacher.lockAttaching();
}
@Override
public Collection<Class<? extends IAddon>> obtainAddonsList() {
return mAttacher.obtainAddonsList();
}
@Override
public void onActionModeFinished(ActionMode mode) {
}
@Override
public void onActionModeStarted(ActionMode mode) {
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onActivityResult(requestCode, resultCode, data);
}
});
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
final Configuration oldConfig = getResources().getConfiguration();
super.onConfigurationChanged(newConfig);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onConfigurationChanged(oldConfig, newConfig);
}
});
}
@Override
public void onContentChanged() {
super.onContentChanged();
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onContentChanged();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
final Bundle state = instanceState(savedInstanceState);
mCreatedByThemeManager = getIntent().getBooleanExtra(
ThemeManager.KEY_CREATED_BY_THEME_MANAGER, false);
mAttacher.inhert(getSupportApplication());
forceInit(state);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onPreCreate(state);
}
});
super.onCreate(state);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onCreate(state);
}
});
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return onCreateOptionsMenu(new MenuWrapper(menu));
}
@Override
public boolean onCreatePanelMenu(final int featureId, final android.view.Menu menu) {
return performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.onCreatePanelMenu(featureId, menu);
}
@Override
public boolean post() {
return Activity.super.onCreatePanelMenu(featureId, menu);
}
});
}
@Override
protected void onDestroy() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onDestroy();
}
});
super.onDestroy();
}
@Override
public boolean onHomePressed() {
return performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.onHomePressed();
}
@Override
public boolean post() {
return Activity.super.onHomePressed();
}
});
}
@Override
public boolean onMenuItemSelected(final int featureId,
final android.view.MenuItem item) {
return performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.onMenuItemSelected(featureId, item);
}
@Override
public boolean post() {
return Activity.super.onMenuItemSelected(featureId, item);
}
});
}
@Override
public boolean onMenuOpened(final int featureId, final android.view.Menu menu) {
return performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.onMenuOpened(featureId, menu);
}
@Override
public boolean post() {
return Activity.super.onMenuOpened(featureId, menu);
}
});
}
@Override
protected void onNewIntent(final Intent intent) {
super.onNewIntent(intent);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onNewIntent(intent);
}
});
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return onOptionsItemSelected(new MenuItemWrapper(item));
}
@Override
public void onPanelClosed(final int featureId, final android.view.Menu menu) {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onPanelClosed(featureId, menu);
}
});
super.onPanelClosed(featureId, menu);
}
@Override
protected void onPause() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onPause();
}
});
super.onPause();
}
@Override
protected void onPostCreate(Bundle sSavedInstanceState) {
final Bundle savedInstanceState = instanceState(sSavedInstanceState);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onPostCreate(savedInstanceState);
}
});
super.onPostCreate(savedInstanceState);
}
@Override
protected void onPostInit(Holo config, Bundle savedInstanceState) {
lockAttaching();
}
@Override
protected void onPostResume() {
super.onPostResume();
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onPostResume();
}
});
}
@Override
protected void onPreInit(Holo config, Bundle savedInstanceState) {
if (getClass().isAnnotationPresent(Addons.class)) {
for (String addon : getClass().getAnnotation(Addons.class).value()) {
if (ADDON_SHERLOCK.equals(addon)) {
config.requireSherlock = true;
} else if (ADDON_SLIDER.equals(addon)) {
config.requireSlider = true;
} else if (ADDON_ROBOGUICE.equals(addon)) {
config.requireRoboguice = true;
} else if (ADDON_TABBER.equals(addon)) {
config.requireTabber = true;
} else {
addon(addon);
}
}
}
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return onPrepareOptionsMenu(new MenuWrapper(menu));
}
@Override
public boolean onPreparePanel(final int featureId, final View view,
final android.view.Menu menu) {
return performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.onPreparePanel(featureId, view, menu);
}
@Override
public boolean post() {
return Activity.super.onPreparePanel(featureId, view, menu);
}
});
}
@Override
protected void onRestart() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onRestart();
}
});
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onResume();
}
});
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onSaveInstanceState(outState);
}
});
}
@Override
protected void onStart() {
super.onStart();
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onStart();
}
});
}
@Override
protected void onStop() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onStop();
}
});
super.onStop();
}
@Override
protected void onTitleChanged(final CharSequence title, final int color) {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public void justAction(IAddonActivity addon) {
addon.onTitleChanged(title, color);
}
});
super.onTitleChanged(title, color);
}
@Override
public void openOptionsMenu() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.openOptionsMenu();
}
@Override
public void justPost() {
Activity.super.openOptionsMenu();
}
});
}
@Override
public boolean performAddonAction(AddonCallback<IAddonActivity> callback) {
return mAttacher.performAddonAction(callback);
}
@Override
public void requestWindowFeature(long featureIdLong) {
super.requestWindowFeature(featureIdLong);
final int featureId = (int) featureIdLong;
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.requestWindowFeature(featureId);
}
@Override
public void justPost() {
requestWindowFeature(featureId);
}
});
}
public Bundle saveInstanceState() {
Bundle bundle = new Bundle(getClassLoader());
onSaveInstanceState(bundle);
return bundle.size() > 0 ? bundle : null;
}
@Override
public void setSupportProgress(int progress) {
addonSherlock().setProgress(progress);
}
@Override
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
addonSherlock().setProgressBarIndeterminate(indeterminate);
}
@Override
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
addonSherlock().setProgressBarIndeterminateVisibility(visible);
}
@Override
public void setSupportProgressBarVisibility(boolean visible) {
addonSherlock().setProgressBarVisibility(visible);
}
@Override
public void setSupportSecondaryProgress(int secondaryProgress) {
addonSherlock().setSecondaryProgress(secondaryProgress);
}
public void setUiOptions(int uiOptions) {
if (isAddonAttached(AddonSherlock.class)) {
addonSherlock().setUiOptions(uiOptions);
} else if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
getWindow().setUiOptions(uiOptions);
}
}
public void setUiOptions(int uiOptions, int mask) {
if (isAddonAttached(AddonSherlock.class)) {
addonSherlock().setUiOptions(uiOptions, mask);
} else if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
getWindow().setUiOptions(uiOptions, mask);
}
}
@Override
public ActionMode startActionMode(ActionMode.Callback callback) {
return addonSherlock().startActionMode(callback);
}
@Override
public void supportInvalidateOptionsMenu() {
performAddonAction(new AddonCallback<IAddonActivity>() {
@Override
public boolean action(IAddonActivity addon) {
return addon.invalidateOptionsMenu();
}
@Override
public void justPost() {
Activity.super.supportInvalidateOptionsMenu();
}
});
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.amqp;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.tests.integration.IntegrationTestLogger;
import org.apache.activemq.transport.amqp.client.AmqpClient;
import org.apache.activemq.transport.amqp.client.AmqpConnection;
import org.apache.activemq.transport.amqp.client.AmqpMessage;
import org.apache.activemq.transport.amqp.client.AmqpSender;
import org.apache.activemq.transport.amqp.client.AmqpSession;
import org.apache.activemq.transport.amqp.client.AmqpValidator;
import org.apache.qpid.proton.amqp.messaging.Rejected;
import org.apache.qpid.proton.amqp.transport.AmqpError;
import org.apache.qpid.proton.amqp.transport.DeliveryState;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;
import org.apache.qpid.proton.engine.Delivery;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Sender;
import org.junit.Test;
public class AmqpSecurityTest extends AmqpClientTestSupport {
@Override
protected boolean isSecurityEnabled() {
return true;
}
@Test(timeout = 60000)
public void testSaslAuthWithInvalidCredentials() throws Exception {
AmqpConnection connection = null;
AmqpClient client = createAmqpClient(fullUser, guestUser);
try {
connection = client.connect();
fail("Should not authenticate when invalid credentials provided");
} catch (Exception ex) {
// Expected
} finally {
if (connection != null) {
connection.close();
}
}
}
@Test(timeout = 60000)
public void testSaslAuthWithAuthzid() throws Exception {
AmqpConnection connection = null;
AmqpClient client = createAmqpClient(guestUser, guestPass);
client.setAuthzid(guestUser);
try {
connection = client.connect();
} catch (Exception ex) {
fail("Should authenticate even with authzid set");
} finally {
if (connection != null) {
connection.close();
}
}
}
@Test(timeout = 60000)
public void testSaslAuthWithoutAuthzid() throws Exception {
AmqpConnection connection = null;
AmqpClient client = createAmqpClient(guestUser, guestPass);
try {
connection = client.connect();
} catch (Exception ex) {
fail("Should authenticate even with authzid set");
} finally {
if (connection != null) {
connection.close();
}
}
}
@Test(timeout = 60000)
public void testSendAndRejected() throws Exception {
AmqpClient client = createAmqpClient(guestUser, guestPass);
client.setValidator(new AmqpValidator() {
@Override
public void inspectOpenedResource(Sender sender) {
ErrorCondition condition = sender.getRemoteCondition();
if (condition != null && condition.getCondition() != null) {
if (!condition.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
markAsInvalid("Should have been tagged with unauthorized access error");
}
} else {
markAsInvalid("Sender should have been opened with an error");
}
}
});
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
try {
try {
session.createSender(getQueueName());
fail("Should not be able to consume here.");
} catch (Exception ex) {
IntegrationTestLogger.LOGGER.info("Caught expected exception");
}
connection.getStateInspector().assertValid();
} finally {
connection.close();
}
}
@Test(timeout = 60000)
public void testSendMessageFailsOnAnonymousRelayWhenNotAuthorizedToSendToAddress() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
AmqpClient client = createAmqpClient(guestUser, guestPass);
client.setValidator(new AmqpValidator() {
@Override
public void inspectDeliveryUpdate(Sender sender, Delivery delivery) {
DeliveryState state = delivery.getRemoteState();
if (!delivery.remotelySettled()) {
markAsInvalid("delivery is not remotely settled");
}
if (state instanceof Rejected) {
Rejected rejected = (Rejected) state;
if (rejected.getError() == null || rejected.getError().getCondition() == null) {
markAsInvalid("Delivery should have been Rejected with an error condition");
} else {
ErrorCondition error = rejected.getError();
if (!error.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
markAsInvalid("Should have been tagged with unauthorized access error");
}
}
} else {
markAsInvalid("Delivery should have been Rejected");
}
latch.countDown();
}
});
AmqpConnection connection = client.connect();
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createAnonymousSender();
AmqpMessage message = new AmqpMessage();
message.setAddress(getQueueName());
message.setMessageId("msg" + 1);
message.setText("Test-Message");
try {
sender.send(message);
fail("Should not be able to send, message should be rejected");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
sender.close();
}
assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
connection.getStateInspector().assertValid();
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testReceiverNotAuthorized() throws Exception {
AmqpClient client = createAmqpClient(noprivUser, noprivPass);
client.setValidator(new AmqpValidator() {
@Override
public void inspectOpenedResource(Receiver receiver) {
ErrorCondition condition = receiver.getRemoteCondition();
if (condition != null && condition.getCondition() != null) {
if (!condition.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
markAsInvalid("Should have been tagged with unauthorized access error");
}
} else {
markAsInvalid("Receiver should have been opened with an error");
}
}
});
AmqpConnection connection = client.connect();
try {
AmqpSession session = connection.createSession();
try {
session.createReceiver(getQueueName());
fail("Should not be able to consume here.");
} catch (Exception ex) {
IntegrationTestLogger.LOGGER.info("Caught expected exception");
}
connection.getStateInspector().assertValid();
} finally {
connection.close();
}
}
@Test(timeout = 30000)
public void testConsumerNotAuthorizedToCreateQueues() throws Exception {
AmqpClient client = createAmqpClient(noprivUser, noprivPass);
client.setValidator(new AmqpValidator() {
@Override
public void inspectOpenedResource(Sender sender) {
ErrorCondition condition = sender.getRemoteCondition();
if (condition != null && condition.getCondition() != null) {
if (!condition.getCondition().equals(AmqpError.UNAUTHORIZED_ACCESS)) {
markAsInvalid("Should have been tagged with unauthorized access error");
}
} else {
markAsInvalid("Sender should have been opened with an error");
}
}
});
AmqpConnection connection = client.connect();
try {
AmqpSession session = connection.createSession();
try {
session.createReceiver(getQueueName(getPrecreatedQueueSize() + 1));
fail("Should not be able to consume here.");
} catch (Exception ex) {
IntegrationTestLogger.LOGGER.info("Caught expected exception");
}
connection.getStateInspector().assertValid();
} finally {
connection.close();
}
}
}
| |
package com.hockeyhurd.hcorelib.api.math;
/**
* @author hockeyhurd
* @version 9/3/15
*/
public final class Color4f extends Color {
private float r, g, b, a;
public static final float MAX_VALUE = 1.0f;
public static final float MIN_VALUE = 0.0f;
/**
* Generic constructor which defaults all channel values to '0.0f'.
*/
public Color4f() {
this.r = 0.0f;
this.g = 0.0f;
this.b = 0.0f;
this.a = 1.0f;
}
/**
* Constructor from hexadecimal.
*
* @param hex hexdecimal (must be in 'ARGB'!) to use.
*/
public Color4f(final int hex) {
a = (hex >> 0x18) & 0xff;
r = (hex >> 0x10) & 0xff;
g = (hex >> 0x8) & 0xff;
b = (hex) & 0xff;
r /= (float) 0xff;
g /= (float) 0xff;
b /= (float) 0xff;
a /= (float) 0xff;
r = colorCorrect(r);
g = colorCorrect(g);
b = colorCorrect(b);
a = colorCorrect(a);
}
/**
* Generic constructor; assumes alpha value to be '1.0f'.
*
* @param r channel.
* @param g channel.
* @param b channel.
*/
public Color4f(float r, float g, float b) {
this(r, g, b, 1.0f);
}
/**
* Main constructor used for initializing and storing color channel data.
*
* @param r channel.
* @param g channel.
* @param b channel.
* @param a channel.
*/
public Color4f(float r, float g, float b, float a) {
this.r = colorCorrect(r);
this.g = colorCorrect(g);
this.b = colorCorrect(b);
this.a = colorCorrect(a);
}
/**
* Simple copy constructor.
*
* @param color Color4f reference.
*/
private Color4f(Color4f color) {
this.r = color.r;
this.g = color.g;
this.b = color.b;
this.a = color.a;
}
/**
* Function used to clamp value to interval [0.0f, 1.0f] (inclusively).
*
* @param value value to evaluate.
* @return color corrected value.
*/
public static float colorCorrect(float value) {
return value < MIN_VALUE ? MIN_VALUE : value > MAX_VALUE ? MAX_VALUE : value;
}
/**
* @return the r channel.
*/
public float getR() {
return r;
}
/**
* @param r the r to set
*/
public void setR(float r) {
this.r = colorCorrect(r);
}
/**
* @param r the r to set
*/
public void setR(int r) {
setR(r / 255.0f);
}
/**
* @return the g channel.
*/
public float getG() {
return g;
}
/**
* @param g the g to set
*/
public void setG(float g) {
this.g = colorCorrect(g);
}
/**
* @param g the g to set
*/
public void setG(int g) {
setG(g / 255.0f);
}
/**
* @return the b channel.
*/
public float getB() {
return b;
}
/**
* @param b the b to set
*/
public void setB(float b) {
this.b = colorCorrect(b);
}
/**
* @param b the a to set
*/
public void setB(int b) {
setB(b / 255.0f);
}
/**
* @return the a channel.
*/
public float getA() {
return a;
}
/**
* @param a the a to set
*/
public void setA(float a) {
this.a = colorCorrect(a);
}
/**
* @param a the r to set
*/
public void setA(int a) {
setA(a / 255.0f);
}
/**
* @return color int represented in rgba as decimal number.
*/
@Override
public int getRGBA() {
int r = (int) Math.floor(this.r * Color4i.MAX_VALUE);
int g = (int) Math.floor(this.g * Color4i.MAX_VALUE);
int b = (int) Math.floor(this.b * Color4i.MAX_VALUE);
int a = (int) Math.floor(this.a * Color4i.MAX_VALUE);
return (r << 0x18) + (g << 0x10) + (b << 0x8) + a;
}
/**
* @return color int represented in argb as decimal number.
*/
@Override
public int getARGB() {
int r = (int) Math.floor(this.r * Color4i.MAX_VALUE);
int g = (int) Math.floor(this.g * Color4i.MAX_VALUE);
int b = (int) Math.floor(this.b * Color4i.MAX_VALUE);
int a = (int) Math.floor(this.a * Color4i.MAX_VALUE);
return (a << 0x18) + (r << 0x10) + (g << 0x8) + b;
}
@Override
public Color4f copy() {
return new Color4f(this);
}
@Override
public String toString() {
return String.format("R: %f, G: %f, B: %f, A: %f\n", r, g, b, a);
}
}
| |
/*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.reactivex.netty.protocol.http.client;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.cookie.Cookie;
import io.reactivex.netty.channel.AllocatingTransformer;
import io.reactivex.netty.protocol.http.TrailingHeaders;
import io.reactivex.netty.protocol.http.ws.client.WebSocketRequest;
import rx.Observable;
import rx.annotations.Experimental;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* An HTTP request. An instance of a request can only be created from an associated {@link HttpClient} and can be
* modified after creation.
*
* <h2>Request URIs</h2>
*
* While creating a request, the user should provide a URI to be used for the request. The URI can be relative or
* absolute. If the URI is relative (missing host and port information), the target host and port are inferred from the
* {@link HttpClient} that created the request. If the URI is absolute, the host and port are used from the URI.
*
* <h2>Mutations</h2>
*
* All mutations to this request creates a brand new instance.
* <h2>Trailing headers</h2>
*
* One can write HTTP trailing headers by using
*
* <h2> Executing request</h2>
*
* The request is executed every time {@link HttpClientRequest}, or {@link Observable} returned by
* {@code write*Content} is subscribed and is the only way of executing the request.
*
* @param <I> The type of objects read from the request content.
* @param <O> The type of objects read from the response content.
*/
public abstract class HttpClientRequest<I, O> extends Observable<HttpClientResponse<O>> {
protected HttpClientRequest(OnSubscribe<HttpClientResponse<O>> onSubscribe) {
super(onSubscribe);
}
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeContent(Observable<I> contentSource);
/**
* Uses the passed {@link Observable} as the source of content for this request. Every item is written and flushed
* immediately.
*
* @param contentSource Content source for the request.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeContentAndFlushOnEach(Observable<I> contentSource);
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeContent(Observable<I> contentSource,
Func1<I, Boolean> flushSelector);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeContent(Observable<I> contentSource,
Func0<T> trailerFactory,
Func2<T, I, T> trailerMutator);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeContent(Observable<I> contentSource,
Func0<T> trailerFactory,
Func2<T, I, T> trailerMutator,
Func1<I, Boolean> flushSelector);
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeStringContent(Observable<String> contentSource);
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeStringContent(Observable<String> contentSource,
Func1<String, Boolean> flushSelector);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeStringContent(Observable<String> contentSource,
Func0<T> trailerFactory,
Func2<T, String, T> trailerMutator);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeStringContent(Observable<String> contentSource,
Func0<T> trailerFactory,
Func2<T, String, T> trailerMutator,
Func1<String, Boolean> flushSelector);
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeBytesContent(Observable<byte[]> contentSource);
/**
* Uses the passed {@link Observable} as the source of content for this request.
*
* @param contentSource Content source for the request.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
public abstract Observable<HttpClientResponse<O>> writeBytesContent(Observable<byte[]> contentSource,
Func1<byte[], Boolean> flushSelector);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeBytesContent(Observable<byte[]> contentSource,
Func0<T> trailerFactory,
Func2<T, byte[], T> trailerMutator);
/**
* Uses the passed {@link Observable} as the source of content for this request. This method provides a way to
* write trailing headers.
*
* A new instance of {@link TrailingHeaders} will be created using the passed {@code trailerFactory} and the passed
* {@code trailerMutator} will be invoked for every item emitted from the content source, giving a chance to modify
* the trailing headers instance.
*
* @param contentSource Content source for the request.
* @param trailerFactory A factory function to create a new {@link TrailingHeaders} per subscription of the content.
* @param trailerMutator A function to mutate the trailing header on each item emitted from the content source.
* @param flushSelector A {@link Func1} which is invoked for every item emitted from {@code msgs}. All pending
* writes are flushed, iff this function returns, {@code true}.
*
* @return An new instance of {@link Observable} which can be subscribed to execute the request.
*/
@Experimental
public abstract <T extends TrailingHeaders> Observable<HttpClientResponse<O>> writeBytesContent(Observable<byte[]> contentSource,
Func0<T> trailerFactory,
Func2<T, byte[], T> trailerMutator,
Func1<byte[], Boolean> flushSelector);
/**
* Enables read timeout for the response of the newly created and returned request.
*
* @param timeOut Read timeout duration.
* @param timeUnit Read timeout time unit.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> readTimeOut(int timeOut, TimeUnit timeUnit);
/**
* Enables following HTTP redirects for the newly created and returned request.
*
* @param maxRedirects Maximum number of redirects allowed.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> followRedirects(int maxRedirects);
/**
* Enables/disables following HTTP redirects for the newly created and returned request.
*
* @param follow {@code true} for enabling redirects, {@code false} to disable.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> followRedirects(boolean follow);
/**
* Updates the HTTP method of the request and creates a new {@link HttpClientRequest} instance.
*
* @param method New HTTP method to use.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setMethod(HttpMethod method);
/**
* Updates the URI of the request and creates a new {@link HttpClientRequest} instance.
*
* @param newUri New URI to use.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setUri(String newUri);
/**
* Adds an HTTP header with the passed {@code name} and {@code value} to this request.
*
* @param name Name of the header.
* @param value Value for the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addHeader(CharSequence name, Object value);
/**
* Adds the HTTP headers from the passed {@code headers} to this request.
*
* @param headers Map of the headers.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addHeaders(Map<? extends CharSequence, ? extends Iterable<Object>> headers);
/**
* Adds the passed {@code cookie} to this request.
*
* @param cookie Cookie to add.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addCookie(Cookie cookie);
/**
* Adds the passed header as a date value to this request. The date is formatted using netty's {@link
* HttpHeaders#addDateHeader(HttpMessage, CharSequence, Date)} which formats the date as per the <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">HTTP specifications</a> into the format:
* <p/>
* <PRE>"E, dd MMM yyyy HH:mm:ss z"</PRE>
*
* @param name Name of the header.
* @param value Value of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addDateHeader(CharSequence name, Date value);
/**
* Adds multiple date values for the passed header name to this request. The date values are formatted using netty's
* {@link HttpHeaders#addDateHeader(HttpMessage, CharSequence, Date)} which formats the date as per the <a
* href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">HTTP specifications</a> into the format:
* <p/>
* <PRE>"E, dd MMM yyyy HH:mm:ss z"</PRE>
*
* @param name Name of the header.
* @param values Values for the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addDateHeader(CharSequence name, Iterable<Date> values);
/**
* Adds an HTTP header with the passed {@code name} and {@code values} to this request.
*
* @param name Name of the header.
* @param values Values for the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> addHeaderValues(CharSequence name, Iterable<Object> values);
/**
* Overwrites the current value, if any, of the passed header to the passed date value for this request. The date is
* formatted using netty's {@link HttpHeaders#addDateHeader(HttpMessage, CharSequence, Date)} which formats the date
* as per the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">HTTP specifications</a> into
* the format:
* <p/>
* <PRE>"E, dd MMM yyyy HH:mm:ss z"</PRE>
*
* @param name Name of the header.
* @param value Value of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setDateHeader(CharSequence name, Date value);
/**
* Overwrites the current value, if any, of the passed header to the passed value for this request.
*
* @param name Name of the header.
* @param value Value of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setHeader(CharSequence name, Object value);
/**
* Overwrites the current values, if any, of the passed headers for this request.
*
* @param headers Map of the headers.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setHeaders(Map<? extends CharSequence, ? extends Iterable<Object>> headers);
/**
* Overwrites the current value, if any, of the passed header to the passed date values for this request. The date
* is formatted using netty's {@link HttpHeaders#addDateHeader(HttpMessage, CharSequence, Date)} which formats the
* date as per the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1">HTTP specifications</a>
* into the format:
* <p/>
* <PRE>"E, dd MMM yyyy HH:mm:ss z"</PRE>
*
* @param name Name of the header.
* @param values Values of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setDateHeader(CharSequence name, Iterable<Date> values);
/**
* Overwrites the current value, if any, of the passed header to the passed values for this request.
*
* @param name Name of the header.
* @param values Values of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setHeaderValues(CharSequence name, Iterable<Object> values);
/**
* Removes the passed header from this request.
*
* @param name Name of the header.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> removeHeader(CharSequence name);
/**
* Sets HTTP Connection header to the appropriate value for HTTP keep-alive. This delegates to {@link
* HttpHeaders#setKeepAlive(HttpMessage, boolean)}
*
* @param keepAlive {@code true} to enable keep alive.
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setKeepAlive(boolean keepAlive);
/**
* Sets the HTTP transfer encoding to chunked for this request. This delegates to {@link
* HttpHeaders#setTransferEncodingChunked(HttpMessage)}
*
* @return A new instance of the {@link HttpClientRequest} sharing all existing state from this request.
*/
public abstract HttpClientRequest<I, O> setTransferEncodingChunked();
/**
* Creates a new {@code HttpClientRequest} instance modifying the content type using the passed {@code transformer}.
*
* @param transformer Transformer to transform the content stream.
*
* @param <II> New type of the content.
*
* @return A new instance of {@link HttpClientRequest} with the transformed content stream.
*/
public abstract <II> HttpClientRequest<II, O> transformContent(AllocatingTransformer<II, I> transformer);
/**
* Creates a new {@code HttpClientRequest} instance modifying the content type of the response using the
* passed {@code transformer}.
*
* @param transformer Transformer to transform the content stream.
*
* @param <OO> New type of the content.
*
* @return A new instance of {@link HttpClientRequest} with the transformed response content stream.
*/
public abstract <OO> HttpClientRequest<I, OO> transformResponseContent(Transformer<O, OO> transformer);
/**
* Creates a new {@link WebSocketRequest}, inheriting all configurations from this request, that will request an
* upgrade to websockets from the server.
*
* @return A new {@link WebSocketRequest}.
*/
public abstract WebSocketRequest<O> requestWebSocketUpgrade();
/**
* Checks whether a header with the passed name exists for this request.
*
* @param name Header name.
*
* @return {@code true} if the header exists.
*/
public abstract boolean containsHeader(CharSequence name);
/**
* Checks whether a header with the passed name and value exists for this request.
*
* @param name Header name.
* @param value Value to check.
* @param caseInsensitiveValueMatch If the value has to be matched ignoring case.
*
* @return {@code true} if the header with the passed value exists.
*/
public abstract boolean containsHeaderWithValue(CharSequence name, CharSequence value,
boolean caseInsensitiveValueMatch);
/**
* Fetches the value of a header, if exists, for this request.
*
* @param name Name of the header.
*
* @return The value of the header, if it exists, {@code null} otherwise. If there are multiple values for this
* header, the first value is returned.
*/
public abstract String getHeader(CharSequence name);
/**
* Fetches all values of a header, if exists, for this request.
*
* @param name Name of the header.
*
* @return All values of the header, if it exists, {@code null} otherwise.
*/
public abstract List<String> getAllHeaders(CharSequence name);
/**
* Returns an iterator over the header entries. Multiple values for the same header appear as separate entries in
* the returned iterator.
*
* @return An iterator over the header entries
*/
public abstract Iterator<Entry<CharSequence, CharSequence>> headerIterator();
/**
* Returns a new {@link Set} that contains the names of all headers in this request. Note that modifying the
* returned {@link Set} will not affect the state of this response.
*/
public abstract Set<String> getHeaderNames();
/**
* Returns the HTTP version of this request.
*
* @return The HTTP version of this request.
*/
public abstract HttpVersion getHttpVersion();
/**
* Returns the HTTP method for this request.
*
* @return The HTTP method for this request.
*/
public abstract HttpMethod getMethod();
/**
* Returns the URI for this request. The returned URI does <em>not</em> contain the scheme, host and port portion of
* the URI.
*
* @return The URI for this request.
*/
public abstract String getUri();
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.DynamicClassLoader;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.bytecode.expression.BytecodeExpression;
import com.facebook.presto.bytecode.expression.BytecodeExpressions;
import com.facebook.presto.operator.GroupByIdBlock;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.function.AccumulatorStateFactory;
import com.facebook.presto.spi.function.AccumulatorStateSerializer;
import com.facebook.presto.spi.function.WindowIndex;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.gen.Binding;
import com.facebook.presto.sql.gen.CallSiteBinder;
import com.facebook.presto.sql.gen.CompilerOperations;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import java.lang.invoke.MethodHandle;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.CompilerUtils.defineClass;
import static com.facebook.presto.bytecode.CompilerUtils.makeClassName;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantString;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeDynamic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.not;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.countInputChannels;
import static com.facebook.presto.sql.gen.Bootstrap.BOOTSTRAP_METHOD;
import static com.facebook.presto.sql.gen.BytecodeUtils.invoke;
import static com.facebook.presto.sql.gen.SqlTypeBytecodeExpression.constantType;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
public class AccumulatorCompiler
{
private AccumulatorCompiler()
{
}
public static GenericAccumulatorFactoryBinder generateAccumulatorFactoryBinder(AggregationMetadata metadata, DynamicClassLoader classLoader)
{
Class<? extends Accumulator> accumulatorClass = generateAccumulatorClass(
Accumulator.class,
metadata,
classLoader);
Class<? extends GroupedAccumulator> groupedAccumulatorClass = generateAccumulatorClass(
GroupedAccumulator.class,
metadata,
classLoader);
return new GenericAccumulatorFactoryBinder(
metadata.getStateSerializer(),
metadata.getStateFactory(),
accumulatorClass,
groupedAccumulatorClass);
}
private static <T> Class<? extends T> generateAccumulatorClass(
Class<T> accumulatorInterface,
AggregationMetadata metadata,
DynamicClassLoader classLoader)
{
boolean grouped = accumulatorInterface == GroupedAccumulator.class;
ClassDefinition definition = new ClassDefinition(
a(PUBLIC, FINAL),
makeClassName(metadata.getName() + accumulatorInterface.getSimpleName()),
type(Object.class),
type(accumulatorInterface));
CallSiteBinder callSiteBinder = new CallSiteBinder();
AccumulatorStateSerializer<?> stateSerializer = metadata.getStateSerializer();
AccumulatorStateFactory<?> stateFactory = metadata.getStateFactory();
FieldDefinition stateSerializerField = definition.declareField(a(PRIVATE, FINAL), "stateSerializer", AccumulatorStateSerializer.class);
FieldDefinition stateFactoryField = definition.declareField(a(PRIVATE, FINAL), "stateFactory", AccumulatorStateFactory.class);
FieldDefinition inputChannelsField = definition.declareField(a(PRIVATE, FINAL), "inputChannels", type(List.class, Integer.class));
FieldDefinition maskChannelField = definition.declareField(a(PRIVATE, FINAL), "maskChannel", type(Optional.class, Integer.class));
FieldDefinition stateField = definition.declareField(a(PRIVATE, FINAL), "state", grouped ? stateFactory.getGroupedStateClass() : stateFactory.getSingleStateClass());
// Generate constructor
generateConstructor(
definition,
stateSerializerField,
stateFactoryField,
inputChannelsField,
maskChannelField,
stateField,
grouped);
// Generate methods
generateAddInput(definition, stateField, inputChannelsField, maskChannelField, metadata.getInputMetadata(), metadata.getInputFunction(), callSiteBinder, grouped);
generateAddInputWindowIndex(definition, stateField, metadata.getInputMetadata(), metadata.getInputFunction(), callSiteBinder);
generateGetEstimatedSize(definition, stateField);
generateGetIntermediateType(definition, callSiteBinder, stateSerializer.getSerializedType());
generateGetFinalType(definition, callSiteBinder, metadata.getOutputType());
generateAddIntermediateAsCombine(definition, stateField, stateSerializerField, stateFactoryField, metadata.getCombineFunction(), stateFactory.getSingleStateClass(), callSiteBinder, grouped);
if (grouped) {
generateGroupedEvaluateIntermediate(definition, stateSerializerField, stateField);
}
else {
generateEvaluateIntermediate(definition, stateSerializerField, stateField);
}
if (grouped) {
generateGroupedEvaluateFinal(definition, stateField, metadata.getOutputFunction(), callSiteBinder);
}
else {
generateEvaluateFinal(definition, stateField, metadata.getOutputFunction(), callSiteBinder);
}
return defineClass(definition, accumulatorInterface, callSiteBinder.getBindings(), classLoader);
}
private static MethodDefinition generateGetIntermediateType(ClassDefinition definition, CallSiteBinder callSiteBinder, Type type)
{
MethodDefinition methodDefinition = definition.declareMethod(a(PUBLIC), "getIntermediateType", type(Type.class));
methodDefinition.getBody()
.append(constantType(callSiteBinder, type))
.retObject();
return methodDefinition;
}
private static MethodDefinition generateGetFinalType(ClassDefinition definition, CallSiteBinder callSiteBinder, Type type)
{
MethodDefinition methodDefinition = definition.declareMethod(a(PUBLIC), "getFinalType", type(Type.class));
methodDefinition.getBody()
.append(constantType(callSiteBinder, type))
.retObject();
return methodDefinition;
}
private static void generateGetEstimatedSize(ClassDefinition definition, FieldDefinition stateField)
{
MethodDefinition method = definition.declareMethod(a(PUBLIC), "getEstimatedSize", type(long.class));
BytecodeExpression state = method.getThis().getField(stateField);
method.getBody()
.append(state.invoke("getEstimatedSize", long.class).ret());
}
private static void generateAddInput(
ClassDefinition definition,
FieldDefinition stateField,
FieldDefinition inputChannelsField,
FieldDefinition maskChannelField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CallSiteBinder callSiteBinder,
boolean grouped)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
if (grouped) {
parameters.add(arg("groupIdsBlock", GroupByIdBlock.class));
}
Parameter page = arg("page", Page.class);
parameters.add(page);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "addInput", type(void.class), parameters.build());
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
if (grouped) {
generateEnsureCapacity(scope, stateField, body);
}
List<Variable> parameterVariables = new ArrayList<>();
for (int i = 0; i < countInputChannels(parameterMetadatas); i++) {
parameterVariables.add(scope.declareVariable(Block.class, "block" + i));
}
Variable masksBlock = scope.declareVariable(Block.class, "masksBlock");
body.comment("masksBlock = maskChannel.map(page.blockGetter()).orElse(null);")
.append(thisVariable.getField(maskChannelField))
.append(page)
.invokeStatic(type(AggregationUtils.class), "pageBlockGetter", type(Function.class, Integer.class, Block.class), type(Page.class))
.invokeVirtual(Optional.class, "map", Optional.class, Function.class)
.pushNull()
.invokeVirtual(Optional.class, "orElse", Object.class, Object.class)
.checkCast(Block.class)
.putVariable(masksBlock);
// Get all parameter blocks
for (int i = 0; i < countInputChannels(parameterMetadatas); i++) {
body.comment("%s = page.getBlock(inputChannels.get(%d));", parameterVariables.get(i).getName(), i)
.append(page)
.append(thisVariable.getField(inputChannelsField))
.push(i)
.invokeInterface(List.class, "get", Object.class, int.class)
.checkCast(Integer.class)
.invokeVirtual(Integer.class, "intValue", int.class)
.invokeVirtual(Page.class, "getBlock", Block.class, int.class)
.putVariable(parameterVariables.get(i));
}
BytecodeBlock block = generateInputForLoop(stateField, parameterMetadatas, inputFunction, scope, parameterVariables, masksBlock, callSiteBinder, grouped);
body.append(block);
body.ret();
}
private static void generateAddInputWindowIndex(
ClassDefinition definition,
FieldDefinition stateField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CallSiteBinder callSiteBinder)
{
// TODO: implement masking based on maskChannel field once Window Functions support DISTINCT arguments to the functions.
Parameter index = arg("index", WindowIndex.class);
Parameter channels = arg("channels", type(List.class, Integer.class));
Parameter startPosition = arg("startPosition", int.class);
Parameter endPosition = arg("endPosition", int.class);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "addInput", type(void.class), ImmutableList.of(index, channels, startPosition, endPosition));
Scope scope = method.getScope();
Variable position = scope.declareVariable(int.class, "position");
Binding binding = callSiteBinder.bind(inputFunction);
BytecodeExpression invokeInputFunction = invokeDynamic(
BOOTSTRAP_METHOD,
ImmutableList.of(binding.getBindingId()),
"input",
binding.getType(),
getInvokeFunctionOnWindowIndexParameters(
scope,
inputFunction.type().parameterArray(),
parameterMetadatas,
stateField,
index,
channels,
position));
method.getBody()
.append(new ForLoop()
.initialize(position.set(startPosition))
.condition(BytecodeExpressions.lessThanOrEqual(position, endPosition))
.update(position.increment())
.body(new IfStatement()
.condition(anyParametersAreNull(parameterMetadatas, index, channels, position))
.ifFalse(invokeInputFunction)))
.ret();
}
private static BytecodeExpression anyParametersAreNull(
List<ParameterMetadata> parameterMetadatas,
Variable index,
Variable channels,
Variable position)
{
int inputChannel = 0;
BytecodeExpression isNull = constantFalse();
for (ParameterMetadata parameterMetadata : parameterMetadatas) {
switch (parameterMetadata.getParameterType()) {
case BLOCK_INPUT_CHANNEL:
case INPUT_CHANNEL:
BytecodeExpression getChannel = channels.invoke("get", Object.class, constantInt(inputChannel)).cast(int.class);
isNull = BytecodeExpressions.or(isNull, index.invoke("isNull", boolean.class, getChannel, position));
inputChannel++;
break;
case NULLABLE_BLOCK_INPUT_CHANNEL:
inputChannel++;
break;
}
}
return isNull;
}
private static List<BytecodeExpression> getInvokeFunctionOnWindowIndexParameters(
Scope scope,
Class<?>[] parameterTypes,
List<ParameterMetadata> parameterMetadatas,
FieldDefinition stateField,
Variable index,
Variable channels,
Variable position)
{
int inputChannel = 0;
List<BytecodeExpression> expressions = new ArrayList<>();
for (int i = 0; i < parameterTypes.length; i++) {
ParameterMetadata parameterMetadata = parameterMetadatas.get(i);
Class<?> parameterType = parameterTypes[i];
BytecodeExpression getChannel = channels.invoke("get", Object.class, constantInt(inputChannel)).cast(int.class);
switch (parameterMetadata.getParameterType()) {
case STATE:
expressions.add(scope.getThis().getField(stateField));
break;
case BLOCK_INDEX:
expressions.add(constantInt(0)); // index.getSingleValueBlock(channel, position) generates always a page with only one position
break;
case BLOCK_INPUT_CHANNEL:
case NULLABLE_BLOCK_INPUT_CHANNEL:
expressions.add(index.invoke(
"getSingleValueBlock",
Block.class,
getChannel,
position));
inputChannel++;
break;
case INPUT_CHANNEL:
if (parameterType == long.class) {
expressions.add(index.invoke("getLong", long.class, getChannel, position));
}
else if (parameterType == double.class) {
expressions.add(index.invoke("getDouble", double.class, getChannel, position));
}
else if (parameterType == boolean.class) {
expressions.add(index.invoke("getBoolean", boolean.class, getChannel, position));
}
else if (parameterType == Slice.class) {
expressions.add(index.invoke("getSlice", Slice.class, getChannel, position));
}
else if (parameterType == Block.class) {
expressions.add(index.invoke("getObject", Block.class, getChannel, position));
}
else {
throw new IllegalArgumentException(format("Unsupported parameter type: %s", parameterType));
}
inputChannel++;
break;
}
}
return expressions;
}
private static BytecodeBlock generateInputForLoop(
FieldDefinition stateField,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
Scope scope,
List<Variable> parameterVariables,
Variable masksBlock,
CallSiteBinder callSiteBinder,
boolean grouped)
{
// For-loop over rows
Variable page = scope.getVariable("page");
Variable positionVariable = scope.declareVariable(int.class, "position");
Variable rowsVariable = scope.declareVariable(int.class, "rows");
BytecodeBlock block = new BytecodeBlock()
.append(page)
.invokeVirtual(Page.class, "getPositionCount", int.class)
.putVariable(rowsVariable)
.initializeVariable(positionVariable);
BytecodeNode loopBody = generateInvokeInputFunction(scope, stateField, positionVariable, parameterVariables, parameterMetadatas, inputFunction, callSiteBinder, grouped);
// Wrap with null checks
List<Boolean> nullable = new ArrayList<>();
for (ParameterMetadata metadata : parameterMetadatas) {
switch (metadata.getParameterType()) {
case INPUT_CHANNEL:
case BLOCK_INPUT_CHANNEL:
nullable.add(false);
break;
case NULLABLE_BLOCK_INPUT_CHANNEL:
nullable.add(true);
break;
default: // do nothing
}
}
checkState(nullable.size() == parameterVariables.size(), "Number of parameters does not match");
for (int i = 0; i < parameterVariables.size(); i++) {
if (!nullable.get(i)) {
Variable variableDefinition = parameterVariables.get(i);
loopBody = new IfStatement("if(!%s.isNull(position))", variableDefinition.getName())
.condition(new BytecodeBlock()
.getVariable(variableDefinition)
.getVariable(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class))
.ifFalse(loopBody);
}
}
loopBody = new IfStatement("if(testMask(%s, position))", masksBlock.getName())
.condition(new BytecodeBlock()
.getVariable(masksBlock)
.getVariable(positionVariable)
.invokeStatic(CompilerOperations.class, "testMask", boolean.class, Block.class, int.class))
.ifTrue(loopBody);
block.append(new ForLoop()
.initialize(new BytecodeBlock().putVariable(positionVariable, 0))
.condition(new BytecodeBlock()
.getVariable(positionVariable)
.getVariable(rowsVariable)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class))
.update(new BytecodeBlock().incrementVariable(positionVariable, (byte) 1))
.body(loopBody));
return block;
}
private static BytecodeBlock generateInvokeInputFunction(
Scope scope,
FieldDefinition stateField,
Variable position,
List<Variable> parameterVariables,
List<ParameterMetadata> parameterMetadatas,
MethodHandle inputFunction,
CallSiteBinder callSiteBinder,
boolean grouped)
{
BytecodeBlock block = new BytecodeBlock();
if (grouped) {
generateSetGroupIdFromGroupIdsBlock(scope, stateField, block);
}
block.comment("Call input function with unpacked Block arguments");
Class<?>[] parameters = inputFunction.type().parameterArray();
int inputChannel = 0;
for (int i = 0; i < parameters.length; i++) {
ParameterMetadata parameterMetadata = parameterMetadatas.get(i);
switch (parameterMetadata.getParameterType()) {
case STATE:
block.append(scope.getThis().getField(stateField));
break;
case BLOCK_INDEX:
block.getVariable(position);
break;
case BLOCK_INPUT_CHANNEL:
case NULLABLE_BLOCK_INPUT_CHANNEL:
block.getVariable(parameterVariables.get(inputChannel));
inputChannel++;
break;
case INPUT_CHANNEL:
BytecodeBlock getBlockBytecode = new BytecodeBlock()
.getVariable(parameterVariables.get(inputChannel));
pushStackType(scope, block, parameterMetadata.getSqlType(), getBlockBytecode, parameters[i], callSiteBinder);
inputChannel++;
break;
default:
throw new IllegalArgumentException("Unsupported parameter type: " + parameterMetadata.getParameterType());
}
}
block.append(invoke(callSiteBinder.bind(inputFunction), "input"));
return block;
}
// Assumes that there is a variable named 'position' in the block, which is the current index
private static void pushStackType(Scope scope, BytecodeBlock block, Type sqlType, BytecodeBlock getBlockBytecode, Class<?> parameter, CallSiteBinder callSiteBinder)
{
Variable position = scope.getVariable("position");
if (parameter == long.class) {
block.comment("%s.getLong(block, position)", sqlType.getTypeSignature())
.append(constantType(callSiteBinder, sqlType))
.append(getBlockBytecode)
.append(position)
.invokeInterface(Type.class, "getLong", long.class, Block.class, int.class);
}
else if (parameter == double.class) {
block.comment("%s.getDouble(block, position)", sqlType.getTypeSignature())
.append(constantType(callSiteBinder, sqlType))
.append(getBlockBytecode)
.append(position)
.invokeInterface(Type.class, "getDouble", double.class, Block.class, int.class);
}
else if (parameter == boolean.class) {
block.comment("%s.getBoolean(block, position)", sqlType.getTypeSignature())
.append(constantType(callSiteBinder, sqlType))
.append(getBlockBytecode)
.append(position)
.invokeInterface(Type.class, "getBoolean", boolean.class, Block.class, int.class);
}
else if (parameter == Slice.class) {
block.comment("%s.getSlice(block, position)", sqlType.getTypeSignature())
.append(constantType(callSiteBinder, sqlType))
.append(getBlockBytecode)
.append(position)
.invokeInterface(Type.class, "getSlice", Slice.class, Block.class, int.class);
}
else {
block.comment("%s.getObject(block, position)", sqlType.getTypeSignature())
.append(constantType(callSiteBinder, sqlType))
.append(getBlockBytecode)
.append(position)
.invokeInterface(Type.class, "getObject", Object.class, Block.class, int.class);
}
}
private static void generateAddIntermediateAsCombine(
ClassDefinition definition,
FieldDefinition stateField,
FieldDefinition stateSerializerField,
FieldDefinition stateFactoryField,
MethodHandle combineFunction,
Class<?> singleStateClass,
CallSiteBinder callSiteBinder,
boolean grouped)
{
MethodDefinition method = declareAddIntermediate(definition, grouped);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
Variable block = scope.getVariable("block");
Variable scratchState = scope.declareVariable(singleStateClass, "scratchState");
Variable position = scope.declareVariable(int.class, "position");
body.comment("scratchState = stateFactory.createSingleState();")
.append(thisVariable.getField(stateFactoryField))
.invokeInterface(AccumulatorStateFactory.class, "createSingleState", Object.class)
.checkCast(scratchState.getType())
.putVariable(scratchState);
if (grouped) {
generateEnsureCapacity(scope, stateField, body);
}
BytecodeBlock loopBody = new BytecodeBlock();
if (grouped) {
Variable groupIdsBlock = scope.getVariable("groupIdsBlock");
loopBody.append(thisVariable.getField(stateField).invoke("setGroupId", void.class, groupIdsBlock.invoke("getGroupId", long.class, position)));
}
loopBody.append(thisVariable.getField(stateSerializerField).invoke("deserialize", void.class, block, position, scratchState.cast(Object.class)));
loopBody.comment("combine(state, scratchState)")
.append(thisVariable.getField(stateField))
.append(scratchState)
.append(invoke(callSiteBinder.bind(combineFunction), "combine"));
if (grouped) {
// skip rows with null group id
IfStatement ifStatement = new IfStatement("if (!groupIdsBlock.isNull(position))")
.condition(not(scope.getVariable("groupIdsBlock").invoke("isNull", boolean.class, position)))
.ifTrue(loopBody);
loopBody = new BytecodeBlock().append(ifStatement);
}
body.append(generateBlockNonNullPositionForLoop(scope, position, loopBody))
.ret();
}
private static void generateSetGroupIdFromGroupIdsBlock(Scope scope, FieldDefinition stateField, BytecodeBlock block)
{
Variable groupIdsBlock = scope.getVariable("groupIdsBlock");
Variable position = scope.getVariable("position");
BytecodeExpression state = scope.getThis().getField(stateField);
block.append(state.invoke("setGroupId", void.class, groupIdsBlock.invoke("getGroupId", long.class, position)));
}
private static void generateEnsureCapacity(Scope scope, FieldDefinition stateField, BytecodeBlock block)
{
Variable groupIdsBlock = scope.getVariable("groupIdsBlock");
BytecodeExpression state = scope.getThis().getField(stateField);
block.append(state.invoke("ensureCapacity", void.class, groupIdsBlock.invoke("getGroupCount", long.class)));
}
private static MethodDefinition declareAddIntermediate(ClassDefinition definition, boolean grouped)
{
ImmutableList.Builder<Parameter> parameters = ImmutableList.builder();
if (grouped) {
parameters.add(arg("groupIdsBlock", GroupByIdBlock.class));
}
parameters.add(arg("block", Block.class));
return definition.declareMethod(
a(PUBLIC),
"addIntermediate",
type(void.class),
parameters.build());
}
// Generates a for-loop with a local variable named "position" defined, with the current position in the block,
// loopBody will only be executed for non-null positions in the Block
private static BytecodeBlock generateBlockNonNullPositionForLoop(Scope scope, Variable positionVariable, BytecodeBlock loopBody)
{
Variable rowsVariable = scope.declareVariable(int.class, "rows");
Variable blockVariable = scope.getVariable("block");
BytecodeBlock block = new BytecodeBlock()
.append(blockVariable)
.invokeInterface(Block.class, "getPositionCount", int.class)
.putVariable(rowsVariable);
IfStatement ifStatement = new IfStatement("if(!block.isNull(position))")
.condition(new BytecodeBlock()
.append(blockVariable)
.append(positionVariable)
.invokeInterface(Block.class, "isNull", boolean.class, int.class))
.ifFalse(loopBody);
block.append(new ForLoop()
.initialize(positionVariable.set(constantInt(0)))
.condition(new BytecodeBlock()
.append(positionVariable)
.append(rowsVariable)
.invokeStatic(CompilerOperations.class, "lessThan", boolean.class, int.class, int.class))
.update(new BytecodeBlock().incrementVariable(positionVariable, (byte) 1))
.body(ifStatement));
return block;
}
private static void generateGroupedEvaluateIntermediate(ClassDefinition definition, FieldDefinition stateSerializerField, FieldDefinition stateField)
{
Parameter groupId = arg("groupId", int.class);
Parameter out = arg("out", BlockBuilder.class);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "evaluateIntermediate", type(void.class), groupId, out);
Variable thisVariable = method.getThis();
BytecodeExpression state = thisVariable.getField(stateField);
BytecodeExpression stateSerializer = thisVariable.getField(stateSerializerField);
method.getBody()
.append(state.invoke("setGroupId", void.class, groupId.cast(long.class)))
.append(stateSerializer.invoke("serialize", void.class, state.cast(Object.class), out))
.ret();
}
private static void generateEvaluateIntermediate(ClassDefinition definition, FieldDefinition stateSerializerField, FieldDefinition stateField)
{
Parameter out = arg("out", BlockBuilder.class);
MethodDefinition method = definition.declareMethod(
a(PUBLIC),
"evaluateIntermediate",
type(void.class),
out);
Variable thisVariable = method.getThis();
BytecodeExpression stateSerializer = thisVariable.getField(stateSerializerField);
BytecodeExpression state = thisVariable.getField(stateField);
method.getBody()
.append(stateSerializer.invoke("serialize", void.class, state.cast(Object.class), out))
.ret();
}
private static void generateGroupedEvaluateFinal(
ClassDefinition definition,
FieldDefinition stateField,
MethodHandle outputFunction,
CallSiteBinder callSiteBinder)
{
Parameter groupId = arg("groupId", int.class);
Parameter out = arg("out", BlockBuilder.class);
MethodDefinition method = definition.declareMethod(a(PUBLIC), "evaluateFinal", type(void.class), groupId, out);
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
BytecodeExpression state = thisVariable.getField(stateField);
body.append(state.invoke("setGroupId", void.class, groupId.cast(long.class)));
body.comment("output(state, out)");
body.append(state);
body.append(out);
body.append(invoke(callSiteBinder.bind(outputFunction), "output"));
body.ret();
}
private static void generateEvaluateFinal(
ClassDefinition definition,
FieldDefinition stateField,
MethodHandle outputFunction,
CallSiteBinder callSiteBinder)
{
Parameter out = arg("out", BlockBuilder.class);
MethodDefinition method = definition.declareMethod(
a(PUBLIC),
"evaluateFinal",
type(void.class),
out);
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
BytecodeExpression state = thisVariable.getField(stateField);
body.comment("output(state, out)");
body.append(state);
body.append(out);
body.append(invoke(callSiteBinder.bind(outputFunction), "output"));
body.ret();
}
private static void generateConstructor(
ClassDefinition definition,
FieldDefinition stateSerializerField,
FieldDefinition stateFactoryField,
FieldDefinition inputChannelsField,
FieldDefinition maskChannelField,
FieldDefinition stateField,
boolean grouped)
{
Parameter stateSerializer = arg("stateSerializer", AccumulatorStateSerializer.class);
Parameter stateFactory = arg("stateFactory", AccumulatorStateFactory.class);
Parameter inputChannels = arg("inputChannels", type(List.class, Integer.class));
Parameter maskChannel = arg("maskChannel", type(Optional.class, Integer.class));
MethodDefinition method = definition.declareConstructor(
a(PUBLIC),
stateSerializer,
stateFactory,
inputChannels,
maskChannel);
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class);
body.append(thisVariable.setField(stateSerializerField, generateRequireNotNull(stateSerializer)));
body.append(thisVariable.setField(stateFactoryField, generateRequireNotNull(stateFactory)));
body.append(thisVariable.setField(inputChannelsField, generateRequireNotNull(inputChannels)));
body.append(thisVariable.setField(maskChannelField, generateRequireNotNull(maskChannel)));
String createState;
if (grouped) {
createState = "createGroupedState";
}
else {
createState = "createSingleState";
}
body.append(thisVariable.setField(stateField, stateFactory.invoke(createState, Object.class).cast(stateField.getType())));
body.ret();
}
private static BytecodeExpression generateRequireNotNull(Variable variable)
{
return invokeStatic(Objects.class, "requireNonNull", Object.class, variable.cast(Object.class), constantString(variable.getName() + " is null"))
.cast(variable.getType());
}
}
| |
package ca.uwaterloo.joos.reachability;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import ca.uwaterloo.joos.Main;
import ca.uwaterloo.joos.ast.ASTNode;
import ca.uwaterloo.joos.ast.ASTNode.ChildTypeUnmatchException;
import ca.uwaterloo.joos.ast.FileUnit;
import ca.uwaterloo.joos.ast.decl.ConstructorDeclaration;
import ca.uwaterloo.joos.ast.decl.FieldDeclaration;
import ca.uwaterloo.joos.ast.decl.LocalVariableDeclaration;
import ca.uwaterloo.joos.ast.decl.MethodDeclaration;
import ca.uwaterloo.joos.ast.decl.ParameterDeclaration;
import ca.uwaterloo.joos.ast.expr.AssignmentExpression;
import ca.uwaterloo.joos.ast.expr.Expression;
import ca.uwaterloo.joos.ast.expr.InfixExpression;
import ca.uwaterloo.joos.ast.expr.InfixExpression.InfixOperator;
import ca.uwaterloo.joos.ast.expr.name.SimpleName;
import ca.uwaterloo.joos.ast.expr.primary.ArrayAccess;
import ca.uwaterloo.joos.ast.expr.primary.ExpressionPrimary;
import ca.uwaterloo.joos.ast.expr.primary.LiteralPrimary;
import ca.uwaterloo.joos.ast.statement.Block;
import ca.uwaterloo.joos.ast.statement.ForStatement;
import ca.uwaterloo.joos.ast.statement.IfStatement;
import ca.uwaterloo.joos.ast.statement.ReturnStatement;
import ca.uwaterloo.joos.ast.statement.WhileStatement;
import ca.uwaterloo.joos.symboltable.SemanticsVisitor;
import ca.uwaterloo.joos.symboltable.SymbolTable;
public class ReachabilityVisitor extends SemanticsVisitor{
public static final Logger logger = Main.getLogger(ReachabilityVisitor.class);
//Current reachable status. Switches to false once a return
//statement is found. Set to true at the end of a return statement.
private List<String> inits = new ArrayList<String>();
private String currentDecl = null;
public boolean reachable = true;
public boolean isVoid =false; //Tracks if the current method should return void
public int always = 0;
// static int DEBUG_Numbers = 0; //Trach the number of existing Reachability Visitors
public ReachabilityVisitor(SymbolTable table) {
super(table);
// DEBUG_Numbers ++;
// TODO Might not need table...
// logger.setLevel(Level.FINER);
}
private void setInits(Collection<String> inits) {
this.inits = new ArrayList<String>(inits);
}
private void addInit(String var) {
logger.fine("Adding init " + var);
this.inits.add(var);
}
private void removeInit(String var) {
logger.fine("Removing init " + var);
this.inits.remove(var);
}
private void clearInits() {
logger.fine("Clearing inits");
this.inits.clear();
}
@Override
public void willVisit(ASTNode node) throws Exception{
if (!reachable){
throw new Exception ("UNREACHABLE CODE");
}
//What to do on first encountering a node
//Consider root method and constructor blocks reachable
//Initially consider all blocks as terminating normally
// Set a block to normal termination and reassess on didVisit
if (node instanceof ConstructorDeclaration){
isVoid = true;
}
else if (node instanceof MethodDeclaration){
if (((MethodDeclaration)node).getType()==null){
isVoid = true;
}
else isVoid = false;
}
if (node instanceof FieldDeclaration){
currentDecl = ((FieldDeclaration)node).getName().getName();
InitalizedChecker ic = new InitalizedChecker(currentDecl, inits);
Expression initial = ((FieldDeclaration) node).getInitial();
if (initial != null){
initial.accept(ic);
this.addInit(currentDecl);
}
currentDecl = null;
}
if (node instanceof ParameterDeclaration){
currentDecl = ((ParameterDeclaration)node).getName().getName();
this.addInit(currentDecl);
currentDecl = null;
}
if (node instanceof LocalVariableDeclaration){
currentDecl = ((LocalVariableDeclaration)node).getName().getName();
if (inits.contains(currentDecl)) this.removeInit(currentDecl);
InitalizedChecker ic = new InitalizedChecker(currentDecl, inits);
Expression initial = ((LocalVariableDeclaration) node).getInitial();
if (initial != null){
initial.accept(ic);
this.addInit(currentDecl);
}
currentDecl = null;
}
if (node instanceof AssignmentExpression){
//Check here if the assignment is valid and so
AssignmentExpression ANode = (AssignmentExpression) node;
ASTNode LH = (ASTNode) ANode.getLeftHand();
if (LH instanceof SimpleName){
if (!inits.contains(((SimpleName) LH).getName())){
InitalizedChecker ic = new InitalizedChecker(((SimpleName) LH).getName(), inits);
ANode.getExpression().accept(ic);
this.addInit(((SimpleName) LH).getName());
}
}
}
if (node instanceof SimpleName){
ASTNode parent = ((SimpleName)node).getParent();
if (parent instanceof InfixExpression ||
parent instanceof ArrayAccess ||
parent instanceof ReturnStatement ||
parent instanceof AssignmentExpression){
if (!inits.contains(((SimpleName)node).getName())){
logger.fine("Current init: " + this.inits);
throw new Exception ("Variable " + ((SimpleName)node).getName() + " used before initalization");
}
}
}
if (node instanceof ReturnStatement){
//Check that we return nothing if void
if (isVoid && ((ReturnStatement)node).getExpression()!= null){
throw new Exception ("Non Null Return statement in void method");
}
}
if (node instanceof IfStatement){
reachable = true;
always = condCheck(node);
ReachabilityVisitor innerrv = new ReachabilityVisitor(this.table);
IfStatement Inode = (IfStatement) node;
innerrv.setInits(this.inits);
//Run separate checks on the if else subtrees
Inode.getIfStatement().accept(innerrv);
//An If statement must end with a return statement
//Thus, the new visitor has reachable set to false. Reset it
reachable = innerrv.reachable;
innerrv = new ReachabilityVisitor(this.table);
innerrv.setInits(this.inits);
if (Inode.getElseStatement() != null){
if (!(Inode.getElseStatement() instanceof IfStatement)){
//In this case, we have an else statement
innerrv.always = 1;
}
//if (always == 1) throw new Exception ("Else block after always returning if");
Inode.getElseStatement().accept(innerrv);
reachable = innerrv.reachable;
always = innerrv.always;
}
if (always == 0) reachable = true;
// reachable = true; //...??? Ignoring unreachable if blocks
}
if (node instanceof ForStatement){
always = condCheck(node);
if (always == 0) throw new Exception ("Constant false for conditional");
if (always == 2) {//Evaluate the condition to see if it ALWAYS returns false
List<Expression> operands = ((InfixExpression)((ForStatement)node).getForCondition()).getOperands();
Integer RH = eval(operands.get(1));
Integer LH = eval(operands.get(0));
if (RH != null && LH != null){
if(!isTrue(RH,LH, ((InfixExpression)((ForStatement)node).getForCondition()).getOperator())){
throw new Exception("Constant FALSE for Conditional");
}
}
}
}
if (node instanceof WhileStatement){
always = condCheck(node);
if (always == 0) throw new Exception ("Unreachable While Block");
}
}
private boolean isTrue(Integer rh, Integer lh, InfixOperator operator) {
//Returns true if the condition evaluates to true
if (operator == InfixOperator.EQ){
return (rh == lh);
}
else if (operator == InfixOperator.LT){
return (rh < lh);
}
else if (operator == InfixOperator.LEQ){
return (rh <= lh);
}
else if (operator == InfixOperator.GT){
return (rh > lh);
}
else if (operator == InfixOperator.GEQ){
return (rh >= lh);
}
return false;
}
private Integer eval(ASTNode expr) throws ChildTypeUnmatchException {
// Returns the boolean evaluation of the for test if it is constant
//Returns the value of an operation..........
//The node represents an equation to be evaled. Either the operand is a literal
//or it is not...
if (expr instanceof SimpleName){
return null;
} else if (expr instanceof LiteralPrimary){
return Integer.parseInt(((LiteralPrimary)expr).getValue());
} else if (expr instanceof ExpressionPrimary){
ExpressionPrimary ENode = (ExpressionPrimary)expr;
return eval(ENode.getExpression());
} else if (expr instanceof AssignmentExpression) {
return eval(((AssignmentExpression) expr).getExpression());
} else if (expr instanceof InfixExpression){
InfixExpression ENode = (InfixExpression)expr;
InfixOperator operator = ENode.getOperator();
List<Expression> operands = ENode.getOperands();
Integer LH = eval(operands.get(0));
Integer RH = eval(operands.get(1));
if (LH == null || RH == null){
return null;
}
if (operator == InfixExpression.InfixOperator.PLUS){
return LH + RH;
}
if (operator == InfixExpression.InfixOperator.MINUS){
return LH - RH;
}
if (operator == InfixExpression.InfixOperator.STAR){
return LH * RH;
}
if (operator == InfixExpression.InfixOperator.SLASH){
return LH / RH;
}
}
return 0;
}
public boolean visit(ASTNode node) throws Exception{
if (node instanceof FileUnit){
FileUnit FNode = (FileUnit) node;
// System.out.println(FNode.getIdentifier());
if (FNode.getIdentifier().equals("Byte.java")) return false;
if (FNode.getIdentifier().equals("Character.java")) return false;
if (FNode.getIdentifier().equals("Integer.java")) return false;
if (FNode.getIdentifier().equals("Number.java")) return false;
if (FNode.getIdentifier().equals("Object.java")) return false;
if (FNode.getIdentifier().equals("Short.java")) return false;
if (FNode.getIdentifier().equals("String.java")) return false;
if (FNode.getIdentifier().equals("OutputStream.java")) return false;
}
if (node instanceof IfStatement){
return false;
}
if (node instanceof LocalVariableDeclaration){
return false;
}
return true;
}
@Override
public void didVisit(ASTNode node) throws Exception{
if (node instanceof IfStatement ||
node instanceof ForStatement) {
// if (always == 1 && reachable == true) throw new Exception ("Non Terminating constant true condition block");
if (always == 0) reachable = true;
if (always == 2) reachable = true;
// reachable = true;
}
// if (node instanceof IfStatement){
// if (always != 1)reachable = true;
// }
//
if (node instanceof WhileStatement){
if (always == 1) {//While is always true, no code below is reachable
reachable = false;
}
else if (always == 2 || always == 0) reachable = true;
}
if (node instanceof MethodDeclaration){
if ((!isVoid )&& reachable) throw new Exception ("Non-Void method with no return value");
reachable = true;
}
if (node instanceof ReturnStatement){
reachable = false;
}
if (node instanceof Block){
//reachable = true;// TODO do Return statements get own block?
}
if (node instanceof MethodDeclaration ||
node instanceof ConstructorDeclaration){
//Don't need per block recording as we cannot have overlapping scope
//and use before declaration is covered
//Refresh the init list at the end of each method and constructor
this.clearInits();
}
}
protected void reset(){
this.reachable = true;
}
public int condCheck(ASTNode node) throws Exception{
//TODO: Check the condition for each control loop
// If the condition comes from a variable, ensure it is initalized...
// If the condition is a literal, it needs to be BOOLEAN from A3.
// If the constant is FALSE, throw exception
// If the constant is TRUE
// FOR/WHILE: no other code must exist within the same block
// IF: Dead code exists AFTER the if block if it contains a return
/*If the node parameter is not a control statement, then it
* is an operand of an infix expression and this method was called
* recursively.
*/
if (node instanceof LiteralPrimary){
if (((LiteralPrimary)node).getValue().equals("true")){
return 1;
}
else if (((LiteralPrimary)node).getValue().equals("false")){
return 0;
}
}
if (node instanceof Expression){
//Need to add another check for infix expression...
return 2;
}
/*
* Otherwise, the method was called from the visitor and was passed a control statement
*/
/* Extract Conditional */
ASTNode CNode = null;
if (node instanceof WhileStatement){
CNode = ((WhileStatement)node).getWhileCondition();
}
if (node instanceof IfStatement){
CNode = ((IfStatement)node).getIfCondition();
}
if (node instanceof ForStatement){
CNode = ((ForStatement)node).getForCondition();
}
/* Now check extracted conditional */
if(CNode instanceof LiteralPrimary){
//Conditional is a constant.
//Get the value of the constant as a string and compare
String value = ((LiteralPrimary) CNode).getValue();
if (value.equals("true")){
return 1;
}
else {
//An if block with a constant false conditional is an automatic exception
// throw new Exception("Constant FALSE used for if conditional");
return 0;
}
}
if (CNode instanceof InfixExpression){
//We have multiple conditionals
List<Expression> operands = (((InfixExpression)CNode).getOperands());
//Run condCheck on both sides of the infix expression
int LH = condCheck(operands.get(0));
int RH = condCheck(operands.get(1));
//Get the operator of the infix expression
InfixExpression.InfixOperator operator = ((InfixExpression)CNode).getOperator();
if (LH == 2 || RH == 2) return 2;
if (operator == InfixExpression.InfixOperator.AND){
return LH & RH;
}
else if (operator == InfixExpression.InfixOperator.OR){
return LH | RH;
}
}
if (CNode instanceof Expression){
//We can ignore the expression as long as the variable is definitely
//assigned at this point (check elsewhere)
//TODO This MAY not be true if the condition contains an assignment
// In such a case, we already know a boolean is assigned, so
// we treat it as a constant.
// (j = false || i = true) => a constant of TRUE...?
//IF InfxExpression, get result of CondChecker on both sides...
}
return 0;
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisfirehose.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Describes an update for a destination in Amazon Redshift.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/firehose-2015-08-04/RedshiftDestinationUpdate" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RedshiftDestinationUpdate implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)
* and AWS Service Namespaces</a>.
* </p>
*/
private String roleARN;
/**
* <p>
* The database connection string.
* </p>
*/
private String clusterJDBCURL;
/**
* <p>
* The <code>COPY</code> command.
* </p>
*/
private CopyCommand copyCommand;
/**
* <p>
* The name of the user.
* </p>
*/
private String username;
/**
* <p>
* The user password.
* </p>
*/
private String password;
/**
* <p>
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift. Default value
* is 3600 (60 minutes).
* </p>
*/
private RedshiftRetryOptions retryOptions;
/**
* <p>
* The Amazon S3 destination.
* </p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation that
* reads from the S3 bucket doesn't support these compression formats.
* </p>
*/
private S3DestinationUpdate s3Update;
/**
* <p>
* The data processing configuration.
* </p>
*/
private ProcessingConfiguration processingConfiguration;
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*/
private String s3BackupMode;
/**
* <p>
* The Amazon S3 destination for backup.
* </p>
*/
private S3DestinationUpdate s3BackupUpdate;
/**
* <p>
* The Amazon CloudWatch logging options for your delivery stream.
* </p>
*/
private CloudWatchLoggingOptions cloudWatchLoggingOptions;
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)
* and AWS Service Namespaces</a>.
* </p>
*
* @param roleARN
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names
* (ARNs) and AWS Service Namespaces</a>.
*/
public void setRoleARN(String roleARN) {
this.roleARN = roleARN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)
* and AWS Service Namespaces</a>.
* </p>
*
* @return The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names
* (ARNs) and AWS Service Namespaces</a>.
*/
public String getRoleARN() {
return this.roleARN;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)
* and AWS Service Namespaces</a>.
* </p>
*
* @param roleARN
* The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
* href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names
* (ARNs) and AWS Service Namespaces</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withRoleARN(String roleARN) {
setRoleARN(roleARN);
return this;
}
/**
* <p>
* The database connection string.
* </p>
*
* @param clusterJDBCURL
* The database connection string.
*/
public void setClusterJDBCURL(String clusterJDBCURL) {
this.clusterJDBCURL = clusterJDBCURL;
}
/**
* <p>
* The database connection string.
* </p>
*
* @return The database connection string.
*/
public String getClusterJDBCURL() {
return this.clusterJDBCURL;
}
/**
* <p>
* The database connection string.
* </p>
*
* @param clusterJDBCURL
* The database connection string.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withClusterJDBCURL(String clusterJDBCURL) {
setClusterJDBCURL(clusterJDBCURL);
return this;
}
/**
* <p>
* The <code>COPY</code> command.
* </p>
*
* @param copyCommand
* The <code>COPY</code> command.
*/
public void setCopyCommand(CopyCommand copyCommand) {
this.copyCommand = copyCommand;
}
/**
* <p>
* The <code>COPY</code> command.
* </p>
*
* @return The <code>COPY</code> command.
*/
public CopyCommand getCopyCommand() {
return this.copyCommand;
}
/**
* <p>
* The <code>COPY</code> command.
* </p>
*
* @param copyCommand
* The <code>COPY</code> command.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withCopyCommand(CopyCommand copyCommand) {
setCopyCommand(copyCommand);
return this;
}
/**
* <p>
* The name of the user.
* </p>
*
* @param username
* The name of the user.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* <p>
* The name of the user.
* </p>
*
* @return The name of the user.
*/
public String getUsername() {
return this.username;
}
/**
* <p>
* The name of the user.
* </p>
*
* @param username
* The name of the user.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withUsername(String username) {
setUsername(username);
return this;
}
/**
* <p>
* The user password.
* </p>
*
* @param password
* The user password.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* <p>
* The user password.
* </p>
*
* @return The user password.
*/
public String getPassword() {
return this.password;
}
/**
* <p>
* The user password.
* </p>
*
* @param password
* The user password.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withPassword(String password) {
setPassword(password);
return this;
}
/**
* <p>
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift. Default value
* is 3600 (60 minutes).
* </p>
*
* @param retryOptions
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift.
* Default value is 3600 (60 minutes).
*/
public void setRetryOptions(RedshiftRetryOptions retryOptions) {
this.retryOptions = retryOptions;
}
/**
* <p>
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift. Default value
* is 3600 (60 minutes).
* </p>
*
* @return The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift.
* Default value is 3600 (60 minutes).
*/
public RedshiftRetryOptions getRetryOptions() {
return this.retryOptions;
}
/**
* <p>
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift. Default value
* is 3600 (60 minutes).
* </p>
*
* @param retryOptions
* The retry behavior in case Kinesis Data Firehose is unable to deliver documents to Amazon Redshift.
* Default value is 3600 (60 minutes).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withRetryOptions(RedshiftRetryOptions retryOptions) {
setRetryOptions(retryOptions);
return this;
}
/**
* <p>
* The Amazon S3 destination.
* </p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation that
* reads from the S3 bucket doesn't support these compression formats.
* </p>
*
* @param s3Update
* The Amazon S3 destination.</p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation
* that reads from the S3 bucket doesn't support these compression formats.
*/
public void setS3Update(S3DestinationUpdate s3Update) {
this.s3Update = s3Update;
}
/**
* <p>
* The Amazon S3 destination.
* </p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation that
* reads from the S3 bucket doesn't support these compression formats.
* </p>
*
* @return The Amazon S3 destination.</p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation
* that reads from the S3 bucket doesn't support these compression formats.
*/
public S3DestinationUpdate getS3Update() {
return this.s3Update;
}
/**
* <p>
* The Amazon S3 destination.
* </p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation that
* reads from the S3 bucket doesn't support these compression formats.
* </p>
*
* @param s3Update
* The Amazon S3 destination.</p>
* <p>
* The compression formats <code>SNAPPY</code> or <code>ZIP</code> cannot be specified in
* <code>RedshiftDestinationUpdate.S3Update</code> because the Amazon Redshift <code>COPY</code> operation
* that reads from the S3 bucket doesn't support these compression formats.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withS3Update(S3DestinationUpdate s3Update) {
setS3Update(s3Update);
return this;
}
/**
* <p>
* The data processing configuration.
* </p>
*
* @param processingConfiguration
* The data processing configuration.
*/
public void setProcessingConfiguration(ProcessingConfiguration processingConfiguration) {
this.processingConfiguration = processingConfiguration;
}
/**
* <p>
* The data processing configuration.
* </p>
*
* @return The data processing configuration.
*/
public ProcessingConfiguration getProcessingConfiguration() {
return this.processingConfiguration;
}
/**
* <p>
* The data processing configuration.
* </p>
*
* @param processingConfiguration
* The data processing configuration.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withProcessingConfiguration(ProcessingConfiguration processingConfiguration) {
setProcessingConfiguration(processingConfiguration);
return this;
}
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*
* @param s3BackupMode
* The Amazon S3 backup mode.
* @see RedshiftS3BackupMode
*/
public void setS3BackupMode(String s3BackupMode) {
this.s3BackupMode = s3BackupMode;
}
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*
* @return The Amazon S3 backup mode.
* @see RedshiftS3BackupMode
*/
public String getS3BackupMode() {
return this.s3BackupMode;
}
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*
* @param s3BackupMode
* The Amazon S3 backup mode.
* @return Returns a reference to this object so that method calls can be chained together.
* @see RedshiftS3BackupMode
*/
public RedshiftDestinationUpdate withS3BackupMode(String s3BackupMode) {
setS3BackupMode(s3BackupMode);
return this;
}
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*
* @param s3BackupMode
* The Amazon S3 backup mode.
* @see RedshiftS3BackupMode
*/
public void setS3BackupMode(RedshiftS3BackupMode s3BackupMode) {
withS3BackupMode(s3BackupMode);
}
/**
* <p>
* The Amazon S3 backup mode.
* </p>
*
* @param s3BackupMode
* The Amazon S3 backup mode.
* @return Returns a reference to this object so that method calls can be chained together.
* @see RedshiftS3BackupMode
*/
public RedshiftDestinationUpdate withS3BackupMode(RedshiftS3BackupMode s3BackupMode) {
this.s3BackupMode = s3BackupMode.toString();
return this;
}
/**
* <p>
* The Amazon S3 destination for backup.
* </p>
*
* @param s3BackupUpdate
* The Amazon S3 destination for backup.
*/
public void setS3BackupUpdate(S3DestinationUpdate s3BackupUpdate) {
this.s3BackupUpdate = s3BackupUpdate;
}
/**
* <p>
* The Amazon S3 destination for backup.
* </p>
*
* @return The Amazon S3 destination for backup.
*/
public S3DestinationUpdate getS3BackupUpdate() {
return this.s3BackupUpdate;
}
/**
* <p>
* The Amazon S3 destination for backup.
* </p>
*
* @param s3BackupUpdate
* The Amazon S3 destination for backup.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withS3BackupUpdate(S3DestinationUpdate s3BackupUpdate) {
setS3BackupUpdate(s3BackupUpdate);
return this;
}
/**
* <p>
* The Amazon CloudWatch logging options for your delivery stream.
* </p>
*
* @param cloudWatchLoggingOptions
* The Amazon CloudWatch logging options for your delivery stream.
*/
public void setCloudWatchLoggingOptions(CloudWatchLoggingOptions cloudWatchLoggingOptions) {
this.cloudWatchLoggingOptions = cloudWatchLoggingOptions;
}
/**
* <p>
* The Amazon CloudWatch logging options for your delivery stream.
* </p>
*
* @return The Amazon CloudWatch logging options for your delivery stream.
*/
public CloudWatchLoggingOptions getCloudWatchLoggingOptions() {
return this.cloudWatchLoggingOptions;
}
/**
* <p>
* The Amazon CloudWatch logging options for your delivery stream.
* </p>
*
* @param cloudWatchLoggingOptions
* The Amazon CloudWatch logging options for your delivery stream.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RedshiftDestinationUpdate withCloudWatchLoggingOptions(CloudWatchLoggingOptions cloudWatchLoggingOptions) {
setCloudWatchLoggingOptions(cloudWatchLoggingOptions);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getRoleARN() != null)
sb.append("RoleARN: ").append(getRoleARN()).append(",");
if (getClusterJDBCURL() != null)
sb.append("ClusterJDBCURL: ").append(getClusterJDBCURL()).append(",");
if (getCopyCommand() != null)
sb.append("CopyCommand: ").append(getCopyCommand()).append(",");
if (getUsername() != null)
sb.append("Username: ").append("***Sensitive Data Redacted***").append(",");
if (getPassword() != null)
sb.append("Password: ").append("***Sensitive Data Redacted***").append(",");
if (getRetryOptions() != null)
sb.append("RetryOptions: ").append(getRetryOptions()).append(",");
if (getS3Update() != null)
sb.append("S3Update: ").append(getS3Update()).append(",");
if (getProcessingConfiguration() != null)
sb.append("ProcessingConfiguration: ").append(getProcessingConfiguration()).append(",");
if (getS3BackupMode() != null)
sb.append("S3BackupMode: ").append(getS3BackupMode()).append(",");
if (getS3BackupUpdate() != null)
sb.append("S3BackupUpdate: ").append(getS3BackupUpdate()).append(",");
if (getCloudWatchLoggingOptions() != null)
sb.append("CloudWatchLoggingOptions: ").append(getCloudWatchLoggingOptions());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RedshiftDestinationUpdate == false)
return false;
RedshiftDestinationUpdate other = (RedshiftDestinationUpdate) obj;
if (other.getRoleARN() == null ^ this.getRoleARN() == null)
return false;
if (other.getRoleARN() != null && other.getRoleARN().equals(this.getRoleARN()) == false)
return false;
if (other.getClusterJDBCURL() == null ^ this.getClusterJDBCURL() == null)
return false;
if (other.getClusterJDBCURL() != null && other.getClusterJDBCURL().equals(this.getClusterJDBCURL()) == false)
return false;
if (other.getCopyCommand() == null ^ this.getCopyCommand() == null)
return false;
if (other.getCopyCommand() != null && other.getCopyCommand().equals(this.getCopyCommand()) == false)
return false;
if (other.getUsername() == null ^ this.getUsername() == null)
return false;
if (other.getUsername() != null && other.getUsername().equals(this.getUsername()) == false)
return false;
if (other.getPassword() == null ^ this.getPassword() == null)
return false;
if (other.getPassword() != null && other.getPassword().equals(this.getPassword()) == false)
return false;
if (other.getRetryOptions() == null ^ this.getRetryOptions() == null)
return false;
if (other.getRetryOptions() != null && other.getRetryOptions().equals(this.getRetryOptions()) == false)
return false;
if (other.getS3Update() == null ^ this.getS3Update() == null)
return false;
if (other.getS3Update() != null && other.getS3Update().equals(this.getS3Update()) == false)
return false;
if (other.getProcessingConfiguration() == null ^ this.getProcessingConfiguration() == null)
return false;
if (other.getProcessingConfiguration() != null && other.getProcessingConfiguration().equals(this.getProcessingConfiguration()) == false)
return false;
if (other.getS3BackupMode() == null ^ this.getS3BackupMode() == null)
return false;
if (other.getS3BackupMode() != null && other.getS3BackupMode().equals(this.getS3BackupMode()) == false)
return false;
if (other.getS3BackupUpdate() == null ^ this.getS3BackupUpdate() == null)
return false;
if (other.getS3BackupUpdate() != null && other.getS3BackupUpdate().equals(this.getS3BackupUpdate()) == false)
return false;
if (other.getCloudWatchLoggingOptions() == null ^ this.getCloudWatchLoggingOptions() == null)
return false;
if (other.getCloudWatchLoggingOptions() != null && other.getCloudWatchLoggingOptions().equals(this.getCloudWatchLoggingOptions()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getRoleARN() == null) ? 0 : getRoleARN().hashCode());
hashCode = prime * hashCode + ((getClusterJDBCURL() == null) ? 0 : getClusterJDBCURL().hashCode());
hashCode = prime * hashCode + ((getCopyCommand() == null) ? 0 : getCopyCommand().hashCode());
hashCode = prime * hashCode + ((getUsername() == null) ? 0 : getUsername().hashCode());
hashCode = prime * hashCode + ((getPassword() == null) ? 0 : getPassword().hashCode());
hashCode = prime * hashCode + ((getRetryOptions() == null) ? 0 : getRetryOptions().hashCode());
hashCode = prime * hashCode + ((getS3Update() == null) ? 0 : getS3Update().hashCode());
hashCode = prime * hashCode + ((getProcessingConfiguration() == null) ? 0 : getProcessingConfiguration().hashCode());
hashCode = prime * hashCode + ((getS3BackupMode() == null) ? 0 : getS3BackupMode().hashCode());
hashCode = prime * hashCode + ((getS3BackupUpdate() == null) ? 0 : getS3BackupUpdate().hashCode());
hashCode = prime * hashCode + ((getCloudWatchLoggingOptions() == null) ? 0 : getCloudWatchLoggingOptions().hashCode());
return hashCode;
}
@Override
public RedshiftDestinationUpdate clone() {
try {
return (RedshiftDestinationUpdate) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.kinesisfirehose.model.transform.RedshiftDestinationUpdateMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.route53.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Container for the parameters to the {@link com.amazonaws.services.route53.AmazonRoute53#listResourceRecordSets(ListResourceRecordSetsRequest) ListResourceRecordSets operation}.
* <p>
* Imagine all the resource record sets in a zone listed out in front of
* you. Imagine them sorted lexicographically first by DNS name (with the
* labels reversed, like "com.amazon.www" for example), and secondarily,
* lexicographically by record type. This operation retrieves at most
* MaxItems resource record sets from this list, in order, starting at a
* position specified by the Name and Type arguments:
* </p>
*
* <ul>
* <li>If both Name and Type are omitted, this means start the results
* at the first RRSET in the HostedZone.</li>
* <li>If Name is specified but Type is omitted, this means start the
* results at the first RRSET in the list whose name is greater than or
* equal to Name. </li>
* <li>If both Name and Type are specified, this means start the results
* at the first RRSET in the list whose name is greater than or equal to
* Name and whose type is greater than or equal to Type.</li>
* <li>It is an error to specify the Type but not the Name.</li>
*
* </ul>
* <p>
* Use ListResourceRecordSets to retrieve a single known record set by
* specifying the record set's name and type, and setting MaxItems = 1
* </p>
* <p>
* To retrieve all the records in a HostedZone, first pause any processes
* making calls to ChangeResourceRecordSets. Initially call
* ListResourceRecordSets without a Name and Type to get the first page
* of record sets. For subsequent calls, set Name and Type to the
* NextName and NextType values returned by the previous response.
* </p>
* <p>
* In the presence of concurrent ChangeResourceRecordSets calls, there is
* no consistency of results across calls to ListResourceRecordSets. The
* only way to get a consistent multi-page snapshot of all RRSETs in a
* zone is to stop making changes while pagination is in progress.
* </p>
* <p>
* However, the results from ListResourceRecordSets are consistent within
* a page. If MakeChange calls are taking place concurrently, the result
* of each one will either be completely visible in your results or not
* at all. You will not see partial changes, or changes that do not
* ultimately succeed. (This follows from the fact that MakeChange is
* atomic)
* </p>
* <p>
* The results from ListResourceRecordSets are strongly consistent with
* ChangeResourceRecordSets. To be precise, if a single process makes a
* call to ChangeResourceRecordSets and receives a successful response,
* the effects of that change will be visible in a subsequent call to
* ListResourceRecordSets by that process.
* </p>
*
* @see com.amazonaws.services.route53.AmazonRoute53#listResourceRecordSets(ListResourceRecordSetsRequest)
*/
public class ListResourceRecordSetsRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* The ID of the hosted zone that contains the resource record sets that
* you want to get.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 32<br/>
*/
private String hostedZoneId;
/**
* The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 1024<br/>
*/
private String startRecordName;
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*/
private String startRecordType;
/**
* <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
*/
private String startRecordIdentifier;
/**
* The maximum number of records you want in the response body.
*/
private String maxItems;
/**
* Default constructor for a new ListResourceRecordSetsRequest object. Callers should use the
* setter or fluent setter (with...) methods to initialize this object after creating it.
*/
public ListResourceRecordSetsRequest() {}
/**
* Constructs a new ListResourceRecordSetsRequest object.
* Callers should use the setter or fluent setter (with...) methods to
* initialize any additional object members.
*
* @param hostedZoneId The ID of the hosted zone that contains the
* resource record sets that you want to get.
*/
public ListResourceRecordSetsRequest(String hostedZoneId) {
setHostedZoneId(hostedZoneId);
}
/**
* The ID of the hosted zone that contains the resource record sets that
* you want to get.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 32<br/>
*
* @return The ID of the hosted zone that contains the resource record sets that
* you want to get.
*/
public String getHostedZoneId() {
return hostedZoneId;
}
/**
* The ID of the hosted zone that contains the resource record sets that
* you want to get.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 32<br/>
*
* @param hostedZoneId The ID of the hosted zone that contains the resource record sets that
* you want to get.
*/
public void setHostedZoneId(String hostedZoneId) {
this.hostedZoneId = hostedZoneId;
}
/**
* The ID of the hosted zone that contains the resource record sets that
* you want to get.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 32<br/>
*
* @param hostedZoneId The ID of the hosted zone that contains the resource record sets that
* you want to get.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ListResourceRecordSetsRequest withHostedZoneId(String hostedZoneId) {
this.hostedZoneId = hostedZoneId;
return this;
}
/**
* The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 1024<br/>
*
* @return The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
*/
public String getStartRecordName() {
return startRecordName;
}
/**
* The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 1024<br/>
*
* @param startRecordName The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
*/
public void setStartRecordName(String startRecordName) {
this.startRecordName = startRecordName;
}
/**
* The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>0 - 1024<br/>
*
* @param startRecordName The first name in the lexicographic ordering of domain names that you
* want the <code>ListResourceRecordSets</code> request to list.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ListResourceRecordSetsRequest withStartRecordName(String startRecordName) {
this.startRecordName = startRecordName;
return this;
}
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*
* @return The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
*
* @see RRType
*/
public String getStartRecordType() {
return startRecordType;
}
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*
* @param startRecordType The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
*
* @see RRType
*/
public void setStartRecordType(String startRecordType) {
this.startRecordType = startRecordType;
}
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*
* @param startRecordType The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see RRType
*/
public ListResourceRecordSetsRequest withStartRecordType(String startRecordType) {
this.startRecordType = startRecordType;
return this;
}
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*
* @param startRecordType The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
*
* @see RRType
*/
public void setStartRecordType(RRType startRecordType) {
this.startRecordType = startRecordType.toString();
}
/**
* The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>SOA, A, TXT, NS, CNAME, MX, PTR, SRV, SPF, AAAA
*
* @param startRecordType The DNS type at which to begin the listing of resource record sets.
* <p>Valid values: <code>A</code> | <code>AAAA</code> |
* <code>CNAME</code> | <code>MX</code> | <code>NS</code> |
* <code>PTR</code> | <code>SOA</code> | <code>SPF</code> |
* <code>SRV</code> | <code>TXT</code> <p>Values for Weighted Resource
* Record Sets: <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p> Values for Regional Resource Record Sets:
* <code>A</code> | <code>AAAA</code> | <code>CNAME</code> |
* <code>TXT</code> <p>Values for Alias Resource Record Sets:
* <code>A</code> | <code>AAAA</code> <p>Constraint: Specifying
* <code>type</code> without specifying <code>name</code> returns an
* <a>InvalidInput</a> error.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see RRType
*/
public ListResourceRecordSetsRequest withStartRecordType(RRType startRecordType) {
this.startRecordType = startRecordType.toString();
return this;
}
/**
* <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
*
* @return <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
*/
public String getStartRecordIdentifier() {
return startRecordIdentifier;
}
/**
* <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
*
* @param startRecordIdentifier <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
*/
public void setStartRecordIdentifier(String startRecordIdentifier) {
this.startRecordIdentifier = startRecordIdentifier;
}
/**
* <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>1 - 128<br/>
*
* @param startRecordIdentifier <i>Weighted resource record sets only:</i> If results were truncated
* for a given DNS name and type, specify the value of
* <code>ListResourceRecordSetsResponse$NextRecordIdentifier</code> from
* the previous response to get the next resource record set that has the
* current DNS name and type.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ListResourceRecordSetsRequest withStartRecordIdentifier(String startRecordIdentifier) {
this.startRecordIdentifier = startRecordIdentifier;
return this;
}
/**
* The maximum number of records you want in the response body.
*
* @return The maximum number of records you want in the response body.
*/
public String getMaxItems() {
return maxItems;
}
/**
* The maximum number of records you want in the response body.
*
* @param maxItems The maximum number of records you want in the response body.
*/
public void setMaxItems(String maxItems) {
this.maxItems = maxItems;
}
/**
* The maximum number of records you want in the response body.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param maxItems The maximum number of records you want in the response body.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public ListResourceRecordSetsRequest withMaxItems(String maxItems) {
this.maxItems = maxItems;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHostedZoneId() != null) sb.append("HostedZoneId: " + getHostedZoneId() + ",");
if (getStartRecordName() != null) sb.append("StartRecordName: " + getStartRecordName() + ",");
if (getStartRecordType() != null) sb.append("StartRecordType: " + getStartRecordType() + ",");
if (getStartRecordIdentifier() != null) sb.append("StartRecordIdentifier: " + getStartRecordIdentifier() + ",");
if (getMaxItems() != null) sb.append("MaxItems: " + getMaxItems() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getHostedZoneId() == null) ? 0 : getHostedZoneId().hashCode());
hashCode = prime * hashCode + ((getStartRecordName() == null) ? 0 : getStartRecordName().hashCode());
hashCode = prime * hashCode + ((getStartRecordType() == null) ? 0 : getStartRecordType().hashCode());
hashCode = prime * hashCode + ((getStartRecordIdentifier() == null) ? 0 : getStartRecordIdentifier().hashCode());
hashCode = prime * hashCode + ((getMaxItems() == null) ? 0 : getMaxItems().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof ListResourceRecordSetsRequest == false) return false;
ListResourceRecordSetsRequest other = (ListResourceRecordSetsRequest)obj;
if (other.getHostedZoneId() == null ^ this.getHostedZoneId() == null) return false;
if (other.getHostedZoneId() != null && other.getHostedZoneId().equals(this.getHostedZoneId()) == false) return false;
if (other.getStartRecordName() == null ^ this.getStartRecordName() == null) return false;
if (other.getStartRecordName() != null && other.getStartRecordName().equals(this.getStartRecordName()) == false) return false;
if (other.getStartRecordType() == null ^ this.getStartRecordType() == null) return false;
if (other.getStartRecordType() != null && other.getStartRecordType().equals(this.getStartRecordType()) == false) return false;
if (other.getStartRecordIdentifier() == null ^ this.getStartRecordIdentifier() == null) return false;
if (other.getStartRecordIdentifier() != null && other.getStartRecordIdentifier().equals(this.getStartRecordIdentifier()) == false) return false;
if (other.getMaxItems() == null ^ this.getMaxItems() == null) return false;
if (other.getMaxItems() != null && other.getMaxItems().equals(this.getMaxItems()) == false) return false;
return true;
}
@Override
public ListResourceRecordSetsRequest clone() {
return (ListResourceRecordSetsRequest) super.clone();
}
}
| |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.driver.internal.http;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.rules.RuleChain.outerRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.ExpectedException;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.k3po.driver.internal.test.utils.K3poTestRule;
import org.kaazing.k3po.driver.internal.test.utils.TestSpecification;
public class HttpIT {
private final K3poTestRule k3po = new K3poTestRule();
private final TestRule timeout = new DisableOnDebug(new Timeout(5, SECONDS));
private final ExpectedException expectedExceptions = ExpectedException.none();
@Rule
public final TestRule chain = outerRule(expectedExceptions).around(k3po).around(timeout);
@Test
@TestSpecification({
"http.accept.header.missing",
"http.connect.header.missing"
})
public void shouldNotAcceptHeaderWhenExpectedMissing() throws Exception {
k3po.finish();
expectedExceptions.expect(AssertionError.class);
}
@Test
@TestSpecification({
"http.echo.long.request.payload/request",
"http.echo.long.request.payload/response"
})
public void shouldEchoLongRequestPayload() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.header.with.multiple.tokens",
"tcp.connect.header.with.multiple.tokens" })
public void shouldAcceptHeaderWithMultipleTokens() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.header.with.multiple.tokens.comma.separated",
"tcp.connect.header.with.multiple.tokens.comma.separated" })
@Ignore("#306 reading a list header expressed as a single header with comma separate values does not work")
public void shouldAcceptHeaderWithMultipleTokensCommaSeparated() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.websocket.handshake.then.client.hard.close",
"http.connect.websocket.handshake.then.client.hard.close" })
public void shouldAcceptWebsocketHandshakeThenClientHardClose() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.read.parameter.with.multiple.tokens",
"tcp.connect.write.parameter.with.multiple.tokens" })
public void shouldAcceptReadParameterWithMultipleTokens() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.write.parameter.with.multiple.tokens",
"tcp.accept.read.parameter.with.multiple.tokens" })
public void shouldAcceptWriteParameterWithMultipleTokens() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.with.parameter.write.parameter",
"tcp.accept.read.two.parameters" })
public void shouldAcceptWriteParameterOnConnectWithParameter() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.get.request.with.no.content.on.response",
"tcp.connect.get.request.with.no.content.on.response" })
public void shouldReceiveGetRequestAndProvideResponse() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.get.request.with.content.on.response",
"tcp.connect.get.request.with.content.on.response" })
public void shouldReceiveGetRequestAndProvideResponseWithContent() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.get.request.with.no.content.on.response",
"tcp.accept.get.request.with.no.content.on.response" })
public void shouldSendGetRequestAndReceiveResponseWithNoContent() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.get.request.with.content.on.response",
"tcp.accept.get.request.with.content.on.response" })
public void shouldSendGetRequestAndReceiveResponseWithContent() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.websocket.handshake",
"tcp.connect.websocket.handshake" })
public void shouldAcceptWebsocketHandshake() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.websocket.handshake.then.server.close",
"http.connect.websocket.handshake.then.server.close" })
public void shouldAcceptWebsocketHandshakeThenServerClose() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.websocket.handshake",
"tcp.accept.websocket.handshake" })
public void shouldConnectWebsocketHandshake() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.post.with.chunking",
"tcp.connect.post.with.chunking" })
public void shouldAcceptPostMessageWithChunking() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.post.with.chunking",
"tcp.accept.post.with.chunking" })
public void shouldConnectPostMessageWithChunking() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.response.with.chunking",
"tcp.connect.response.with.chunking" })
public void shouldAcceptResponseWithChunking() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.response.with.chunking",
"tcp.accept.response.with.chunking" })
public void shouldConnectResponseWithChunking() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.connect.connection.close.response",
"tcp.accept.connection.close.response" })
public void shouldConnectConnectionCloseResponse() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.connection.close.response",
"tcp.connect.connection.close.response" })
public void shouldAcceptConnectionCloseResponse() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.two.http.200",
"tcp.connect.two.http.200.on.different.streams" })
public void shouldAcceptMultipleHttpOnDifferentTcp() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.accept.two.http.200",
"tcp.connect.two.http.200.on.same.streams" })
public void shouldAcceptMultipleHttpOnSameTcp() throws Exception {
k3po.finish();
}
@Test
@Ignore("k3po#256")
@TestSpecification({
"server.closes.abruptly.client.closed" })
public void closedShouldWorkOrBeRejected() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"specify.only.part.of.http.response/request",
"specify.only.part.of.http.response/response" })
public void specifyOnlyPartOfHttpResponse() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"read.content.length.via.regex/request",
"read.content.length.via.regex/response" })
public void readContentLengthViaAVariable() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.server.channel.abort/request",
"http.server.channel.abort/response"
})
public void httpServerChannelAbort() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.server.channel.aborted/request",
"http.server.channel.aborted/response"
})
public void httpServerChannelAborted() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.client.channel.abort/request",
"http.client.channel.abort/response"
})
public void httpClientChannelAbort() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"http.client.channel.aborted/request",
"http.client.channel.aborted/response"
})
public void httpClientChannelAborted() throws Exception {
k3po.finish();
}
@Test
// The extensions part of this test has been commented out due to
// https://github.com/k3po/k3po/issues/313
@TestSpecification({
"http.client.post.chunking.with.trailer.and.extensions/request",
"http.client.post.chunking.with.trailer.and.extensions/response"
})
public void httpClientPostChunkingWithTrailerAndExtensions() throws Exception {
k3po.finish();
}
@Test
// The extensions part of this test has been commented out due to
// https://github.com/k3po/k3po/issues/313
@TestSpecification({
"http.server.post.chunking.with.trailer.and.extensions/request",
"http.server.post.chunking.with.trailer.and.extensions/response"
})
public void httpServerPostChunkingWithTrailerAndExtensions() throws Exception {
k3po.finish();
}
@Test
@TestSpecification({
"response.transfer.encoding.chunked.with.trailer/request",
"response.transfer.encoding.chunked.with.trailer/response"
})
public void httpResponseWithEncodingChunked() throws Exception {
k3po.finish();
}
}
| |
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.ashley.systems;
import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.SortedIteratingSystem;
import com.badlogic.ashley.utils.ImmutableArray;
import java.util.Comparator;
import java.util.LinkedList;
import static org.junit.Assert.*;
import org.junit.Test;
public class SortedIteratingSystemTest {
private static final ComponentMapper<OrderComponent> orderMapper = ComponentMapper.getFor(OrderComponent.class);
private static final OrderComparator comparator = new OrderComparator();
private static final float deltaTime = 0.16f;
private static class ComponentB implements Component {
}
private static class ComponentC implements Component {
}
private static class SortedIteratingSystemMock extends SortedIteratingSystem {
public LinkedList<String> expectedNames = new LinkedList<String>();
public SortedIteratingSystemMock (Family family) {
super(family, comparator);
}
@Override
public void update (float deltaTime) {
super.update(deltaTime);
assertTrue(expectedNames.isEmpty());
}
@Override
public void processEntity (Entity entity, float deltaTime) {
OrderComponent component = orderMapper.get(entity);
assertNotNull(component);
assertFalse(expectedNames.isEmpty());
assertEquals(expectedNames.poll(), component.name);
}
}
public static class OrderComponent implements Component {
public String name;
public int zLayer;
public OrderComponent (String name, int zLayer) {
this.name = name;
this.zLayer = zLayer;
}
}
private static class SpyComponent implements Component {
public int updates = 0;
}
private static class IndexComponent implements Component {
public int index = 0;
}
private static class IteratingComponentRemovalSystem extends SortedIteratingSystem {
private ComponentMapper<SpyComponent> sm;
private ComponentMapper<IndexComponent> im;
public IteratingComponentRemovalSystem () {
super(Family.all(SpyComponent.class, IndexComponent.class).get(), comparator);
sm = ComponentMapper.getFor(SpyComponent.class);
im = ComponentMapper.getFor(IndexComponent.class);
}
@Override
public void processEntity (Entity entity, float deltaTime) {
int index = im.get(entity).index;
if (index % 2 == 0) {
entity.remove(SpyComponent.class);
entity.remove(IndexComponent.class);
} else {
sm.get(entity).updates++;
}
}
}
private static class IteratingRemovalSystem extends SortedIteratingSystem {
private Engine engine;
private ComponentMapper<SpyComponent> sm;
private ComponentMapper<IndexComponent> im;
public IteratingRemovalSystem () {
super(Family.all(SpyComponent.class, IndexComponent.class).get(), comparator);
sm = ComponentMapper.getFor(SpyComponent.class);
im = ComponentMapper.getFor(IndexComponent.class);
}
@Override
public void addedToEngine (Engine engine) {
super.addedToEngine(engine);
this.engine = engine;
}
@Override
public void processEntity (Entity entity, float deltaTime) {
int index = im.get(entity).index;
if (index % 2 == 0) {
engine.removeEntity(entity);
} else {
sm.get(entity).updates++;
}
}
}
@Test
@SuppressWarnings("unchecked")
public void shouldIterateEntitiesWithCorrectFamily () {
final Engine engine = new Engine();
final Family family = Family.all(OrderComponent.class, ComponentB.class).get();
final SortedIteratingSystemMock system = new SortedIteratingSystemMock(family);
final Entity e = new Entity();
engine.addSystem(system);
engine.addEntity(e);
// When entity has OrderComponent
e.add(new OrderComponent("A", 0));
engine.update(deltaTime);
// When entity has OrderComponent and ComponentB
e.add(new ComponentB());
system.expectedNames.addLast("A");
engine.update(deltaTime);
// When entity has OrderComponent, ComponentB and ComponentC
e.add(new ComponentC());
system.expectedNames.addLast("A");
engine.update(deltaTime);
// When entity has ComponentB and ComponentC
e.remove(OrderComponent.class);
e.add(new ComponentC());
engine.update(deltaTime);
}
@Test
public void entityRemovalWhileIterating () {
Engine engine = new Engine();
ImmutableArray<Entity> entities = engine.getEntitiesFor(Family.all(SpyComponent.class, IndexComponent.class).get());
ComponentMapper<SpyComponent> sm = ComponentMapper.getFor(SpyComponent.class);
engine.addSystem(new IteratingRemovalSystem());
final int numEntities = 10;
for (int i = 0; i < numEntities; ++i) {
Entity e = new Entity();
e.add(new SpyComponent());
e.add(new OrderComponent("" + i, i));
IndexComponent in = new IndexComponent();
in.index = i + 1;
e.add(in);
engine.addEntity(e);
}
engine.update(deltaTime);
assertEquals(numEntities / 2, entities.size());
for (int i = 0; i < entities.size(); ++i) {
Entity e = entities.get(i);
assertEquals(1, sm.get(e).updates);
}
}
@Test
public void componentRemovalWhileIterating () {
Engine engine = new Engine();
ImmutableArray<Entity> entities = engine.getEntitiesFor(Family.all(SpyComponent.class, IndexComponent.class).get());
ComponentMapper<SpyComponent> sm = ComponentMapper.getFor(SpyComponent.class);
engine.addSystem(new IteratingComponentRemovalSystem());
final int numEntities = 10;
for (int i = 0; i < numEntities; ++i) {
Entity e = new Entity();
e.add(new SpyComponent());
e.add(new OrderComponent("" + i, i));
IndexComponent in = new IndexComponent();
in.index = i + 1;
e.add(in);
engine.addEntity(e);
}
engine.update(deltaTime);
assertEquals(numEntities / 2, entities.size());
for (int i = 0; i < entities.size(); ++i) {
Entity e = entities.get(i);
assertEquals(1, sm.get(e).updates);
}
}
private static Entity createOrderEntity (String name, int zLayer) {
Entity entity = new Entity();
entity.add(new OrderComponent(name, zLayer));
return entity;
}
@Test
public void entityOrder () {
Engine engine = new Engine();
final Family family = Family.all(OrderComponent.class).get();
final SortedIteratingSystemMock system = new SortedIteratingSystemMock(family);
engine.addSystem(system);
Entity a = createOrderEntity("A", 0);
Entity b = createOrderEntity("B", 1);
Entity c = createOrderEntity("C", 3);
Entity d = createOrderEntity("D", 2);
engine.addEntity(a);
engine.addEntity(b);
engine.addEntity(c);
system.expectedNames.addLast("A");
system.expectedNames.addLast("B");
system.expectedNames.addLast("C");
engine.update(0);
engine.addEntity(d);
system.expectedNames.addLast("A");
system.expectedNames.addLast("B");
system.expectedNames.addLast("D");
system.expectedNames.addLast("C");
engine.update(0);
orderMapper.get(a).zLayer = 3;
orderMapper.get(b).zLayer = 2;
orderMapper.get(c).zLayer = 1;
orderMapper.get(d).zLayer = 0;
system.forceSort();
system.expectedNames.addLast("D");
system.expectedNames.addLast("C");
system.expectedNames.addLast("B");
system.expectedNames.addLast("A");
engine.update(0);
}
private static class OrderComparator implements Comparator<Entity> {
@Override
public int compare (Entity a, Entity b) {
OrderComponent ac = orderMapper.get(a);
OrderComponent bc = orderMapper.get(b);
return ac.zLayer > bc.zLayer ? 1 : (ac.zLayer == bc.zLayer) ? 0 : -1;
}
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.wm.impl;
import com.intellij.diagnostic.IdeMessagePanel;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.ide.DataManager;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.notification.impl.IdeNotificationArea;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.MnemonicHelper;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
import com.intellij.openapi.actionSystem.impl.MouseGestureManager;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.IdeRootPaneNorthExtension;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.openapi.wm.ex.IdeFrameEx;
import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt;
import com.intellij.openapi.wm.ex.StatusBarEx;
import com.intellij.openapi.wm.impl.status.*;
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame;
import com.intellij.ui.*;
import com.intellij.ui.mac.MacMainFrameDecorator;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.PowerSupplyKit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public class IdeFrameImpl extends JFrame implements IdeFrameEx, DataProvider {
public static final Key<Boolean> SHOULD_OPEN_IN_FULL_SCREEN = Key.create("should.open.in.full.screen");
private static final String FULL_SCREEN = "FullScreen";
private static boolean myUpdatingTitle;
private String myTitle;
private String myFileTitle;
private File myCurrentFile;
private Project myProject;
private IdeRootPane myRootPane;
private final BalloonLayout myBalloonLayout;
private IdeFrameDecorator myFrameDecorator;
private PropertyChangeListener myWindowsBorderUpdater = null;
private boolean myRestoreFullScreen;
public IdeFrameImpl(ApplicationInfoEx applicationInfoEx,
ActionManagerEx actionManager,
DataManager dataManager,
Application application) {
super(applicationInfoEx.getFullApplicationName());
myRootPane = createRootPane(actionManager, UISettings.getInstance(), dataManager, application);
setRootPane(myRootPane);
setBackground(UIUtil.getPanelBackground());
AppUIUtil.updateWindowIcon(this);
final Dimension size = ScreenUtil.getMainScreenBounds().getSize();
size.width = Math.min(1400, size.width - 20);
size.height= Math.min(1000, size.height - 40);
setSize(size);
setLocationRelativeTo(null);
LayoutFocusTraversalPolicyExt layoutFocusTraversalPolicy = new LayoutFocusTraversalPolicyExt();
setFocusTraversalPolicy(layoutFocusTraversalPolicy);
setupCloseAction();
MnemonicHelper.init(this);
myBalloonLayout = new BalloonLayoutImpl(myRootPane, new Insets(8, 8, 8, 8));
// to show window thumbnail under Macs
// http://lists.apple.com/archives/java-dev/2009/Dec/msg00240.html
if (SystemInfo.isMac) setIconImage(null);
MouseGestureManager.getInstance().add(this);
myFrameDecorator = IdeFrameDecorator.decorate(this);
addWindowStateListener(new WindowAdapter() {
@Override
public void windowStateChanged(WindowEvent e) {
updateBorder();
}
});
if (SystemInfo.isWindows) {
myWindowsBorderUpdater = new PropertyChangeListener() {
@Override
public void propertyChange(@NotNull PropertyChangeEvent evt) {
updateBorder();
}
};
Toolkit.getDefaultToolkit().addPropertyChangeListener("win.xpstyle.themeActive", myWindowsBorderUpdater);
}
IdeMenuBar.installAppMenuIfNeeded(this);
// UIUtil.suppressFocusStealing();
}
@Override
public void addNotify() {
super.addNotify();
PowerSupplyKit.checkPowerSupply();
}
private void updateBorder() {
int state = getExtendedState();
if (!WindowManager.getInstance().isFullScreenSupportedInCurrentOS() || !SystemInfo.isWindows || myRootPane == null) {
return;
}
myRootPane.setBorder(null);
boolean isNotClassic = Boolean.parseBoolean(String.valueOf(Toolkit.getDefaultToolkit().getDesktopProperty("win.xpstyle.themeActive")));
if (isNotClassic && (state & MAXIMIZED_BOTH) != 0) {
IdeFrame[] projectFrames = WindowManager.getInstance().getAllProjectFrames();
GraphicsDevice device = ScreenUtil.getScreenDevice(getBounds());
for (IdeFrame frame : projectFrames) {
if (frame == this) continue;
if (((IdeFrameImpl)frame).isInFullScreen() && ScreenUtil.getScreenDevice(((IdeFrameImpl)frame).getBounds()) == device) {
Insets insets = ScreenUtil.getScreenInsets(device.getDefaultConfiguration());
int mask = SideBorder.NONE;
if (insets.top != 0) mask |= SideBorder.TOP;
if (insets.left != 0) mask |= SideBorder.LEFT;
if (insets.bottom != 0) mask |= SideBorder.BOTTOM;
if (insets.right != 0) mask |= SideBorder.RIGHT;
myRootPane.setBorder(new SideBorder(JBColor.BLACK, mask, 3));
break;
}
}
}
}
protected IdeRootPane createRootPane(ActionManagerEx actionManager,
UISettings uiSettings,
DataManager dataManager,
Application application) {
return new IdeRootPane(actionManager, uiSettings, dataManager, application, this);
}
@NotNull
@Override
public Insets getInsets() {
if (SystemInfo.isMac && isInFullScreen()) {
return new Insets(0, 0, 0, 0);
}
return super.getInsets();
}
@Override
public JComponent getComponent() {
return getRootPane();
}
@Nullable
public static Window getActiveFrame() {
for (Frame frame : getFrames()) {
if (frame.isActive()) return frame;
}
return null;
}
@SuppressWarnings({"deprecation", "SSBasedInspection"})
@Override
public void show() {
super.show();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
setFocusableWindowState(true);
}
});
}
/**
* This is overridden to get rid of strange Alloy LaF customization of frames. For unknown reason it sets the maxBounds rectangle
* and it does it plain wrong. Setting bounds to <code>null</code> means default value should be taken from the underlying OS.
*/
public synchronized void setMaximizedBounds(Rectangle bounds) {
super.setMaximizedBounds(null);
}
private void setupCloseAction() {
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(
new WindowAdapter() {
public void windowClosing(@NotNull final WindowEvent e) {
if (isTemporaryDisposed())
return;
final Application app = ApplicationManager.getApplication();
app.invokeLater(new DumbAwareRunnable() {
public void run() {
if (app.isDisposed()) {
ApplicationManagerEx.getApplicationEx().exit();
return;
}
final Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
if (openProjects.length > 1 || (openProjects.length == 1 && SystemInfo.isMacSystemMenu)) {
if (myProject != null && myProject.isOpen()) {
ProjectUtil.closeAndDispose(myProject);
}
app.getMessageBus().syncPublisher(AppLifecycleListener.TOPIC).projectFrameClosed();
WelcomeFrame.showIfNoProjectOpened();
}
else {
ApplicationManagerEx.getApplicationEx().exit();
}
}
}, ModalityState.NON_MODAL);
}
}
);
}
public StatusBar getStatusBar() {
return myRootPane == null ? null : myRootPane.getStatusBar();
}
public void setTitle(final String title) {
if (myUpdatingTitle) {
super.setTitle(title);
} else {
myTitle = title;
}
updateTitle();
}
public void setFrameTitle(final String text) {
super.setTitle(text);
}
public void setFileTitle(final String fileTitle) {
setFileTitle(fileTitle, null);
}
public void setFileTitle(@Nullable final String fileTitle, @Nullable File file) {
myFileTitle = fileTitle;
myCurrentFile = file;
updateTitle();
}
@Override
public IdeRootPaneNorthExtension getNorthExtension(String key) {
return myRootPane.findByName(key);
}
private void updateTitle() {
updateTitle(this, myTitle, myFileTitle, myCurrentFile);
}
public static void updateTitle(JFrame frame, final String title, final String fileTitle, final File currentFile) {
if (myUpdatingTitle) return;
try {
myUpdatingTitle = true;
frame.getRootPane().putClientProperty("Window.documentFile", currentFile);
final String applicationName = ((ApplicationInfoEx)ApplicationInfo.getInstance()).getFullApplicationName();
final Builder builder = new Builder();
if (SystemInfo.isMac) {
boolean addAppName = StringUtil.isEmpty(title) ||
ProjectManager.getInstance().getOpenProjects().length == 0 ||
((ApplicationInfoEx)ApplicationInfo.getInstance()).isEAP() && !applicationName.endsWith("SNAPSHOT");
builder.append(fileTitle).append(title).append(addAppName ? applicationName : null);
} else {
builder.append(title).append(fileTitle).append(applicationName);
}
frame.setTitle(builder.sb.toString());
}
finally {
myUpdatingTitle = false;
}
}
public void updateView() {
((IdeRootPane)getRootPane()).updateToolbar();
((IdeRootPane)getRootPane()).updateMainMenuActions();
((IdeRootPane)getRootPane()).updateNorthComponents();
}
private static final class Builder {
public StringBuilder sb = new StringBuilder();
public Builder append(@Nullable final String s) {
if (s == null || s.length() == 0) return this;
if (sb.length() > 0) sb.append(" - ");
sb.append(s);
return this;
}
}
public Object getData(final String dataId) {
if (CommonDataKeys.PROJECT.is(dataId)) {
if (myProject != null) {
return myProject.isInitialized() ? myProject : null;
}
}
if (IdeFrame.KEY.getName().equals(dataId)) {
return this;
}
return null;
}
public void setProject(final Project project) {
if (WindowManager.getInstance().isFullScreenSupportedInCurrentOS() && myProject != project && project != null) {
myRestoreFullScreen = myProject == null && shouldRestoreFullScreen(project);
if (myProject != null) {
storeFullScreenStateIfNeeded(false); // disable for old project
}
}
myProject = project;
if (project != null) {
ProjectFrameBounds.getInstance(project); // make sure the service is initialized and its state will be saved
if (myRootPane != null) {
myRootPane.installNorthComponents(project);
project.getMessageBus().connect().subscribe(StatusBar.Info.TOPIC, myRootPane.getStatusBar());
}
installDefaultProjectStatusBarWidgets(myProject);
}
else {
if (myRootPane != null) { //already disposed
myRootPane.deinstallNorthComponents();
}
}
if (project == null) {
FocusTrackback.release(this);
}
if (isVisible() && myRestoreFullScreen) {
toggleFullScreen(true);
myRestoreFullScreen = false;
}
}
@SuppressWarnings("SSBasedInspection")
@Override
public void setVisible(boolean b) {
super.setVisible(b);
if (b && myRestoreFullScreen) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
toggleFullScreen(true);
if (SystemInfo.isMacOSLion) {
setBounds(ScreenUtil.getScreenRectangle(getLocationOnScreen()));
}
myRestoreFullScreen = false;
}
});
}
}
private void installDefaultProjectStatusBarWidgets(@NotNull final Project project) {
final StatusBar statusBar = getStatusBar();
final PositionPanel positionPanel = new PositionPanel(project);
statusBar.addWidget(positionPanel, "before " + IdeMessagePanel.FATAL_ERROR);
final IdeNotificationArea notificationArea = new IdeNotificationArea();
statusBar.addWidget(notificationArea, "before " + IdeMessagePanel.FATAL_ERROR);
final EncodingPanel encodingPanel = new EncodingPanel(project);
statusBar.addWidget(encodingPanel, "after Position");
final LineSeparatorPanel lineSeparatorPanel = new LineSeparatorPanel(project);
statusBar.addWidget(lineSeparatorPanel, "before " + encodingPanel.ID());
final ToggleReadOnlyAttributePanel readOnlyAttributePanel = new ToggleReadOnlyAttributePanel(project);
final InsertOverwritePanel insertOverwritePanel = new InsertOverwritePanel(project);
statusBar.addWidget(insertOverwritePanel, "after Encoding");
statusBar.addWidget(readOnlyAttributePanel, "after InsertOverwrite");
Disposer.register(project, new Disposable() {
public void dispose() {
statusBar.removeWidget(encodingPanel.ID());
statusBar.removeWidget(lineSeparatorPanel.ID());
statusBar.removeWidget(positionPanel.ID());
statusBar.removeWidget(notificationArea.ID());
statusBar.removeWidget(readOnlyAttributePanel.ID());
statusBar.removeWidget(insertOverwritePanel.ID());
((StatusBarEx)statusBar).removeCustomIndicationComponents();
}
});
}
public Project getProject() {
return myProject;
}
public void dispose() {
if (SystemInfo.isMac && isInFullScreen()) {
((MacMainFrameDecorator)myFrameDecorator).exitFullScreenAndDispose();
}
else {
disposeImpl();
}
}
public void disposeImpl() {
if (isTemporaryDisposed()) {
super.dispose();
return;
}
MouseGestureManager.getInstance().remove(this);
WelcomeFrame.notifyFrameClosed(this);
// clear both our and swing hard refs
if (myRootPane != null) {
myRootPane = null;
setRootPane(new JRootPane());
}
if (myFrameDecorator != null) {
Disposer.dispose(myFrameDecorator);
myFrameDecorator = null;
}
if (myWindowsBorderUpdater != null) {
Toolkit.getDefaultToolkit().removePropertyChangeListener("win.xpstyle.themeActive", myWindowsBorderUpdater);
myWindowsBorderUpdater = null;
}
FocusTrackback.release(this);
super.dispose();
}
private boolean isTemporaryDisposed() {
return myRootPane != null && myRootPane.getClientProperty(ScreenUtil.DISPOSE_TEMPORARY) != null;
}
public void storeFullScreenStateIfNeeded() {
if (myFrameDecorator != null) {
storeFullScreenStateIfNeeded(myFrameDecorator.isInFullScreen());
}
}
public void storeFullScreenStateIfNeeded(boolean state) {
if (!WindowManager.getInstance().isFullScreenSupportedInCurrentOS()) return;
if (myProject != null) {
PropertiesComponent.getInstance(myProject).setValue(FULL_SCREEN, String.valueOf(state));
doLayout();
}
}
public static boolean shouldRestoreFullScreen(@Nullable Project project) {
return WindowManager.getInstance().isFullScreenSupportedInCurrentOS() &&
project != null &&
(SHOULD_OPEN_IN_FULL_SCREEN.get(project) == Boolean.TRUE || PropertiesComponent.getInstance(project).getBoolean(FULL_SCREEN, false));
}
@Override
public void paint(@NotNull Graphics g) {
UIUtil.applyRenderingHints(g);
//noinspection Since15
super.paint(g);
}
public Rectangle suggestChildFrameBounds() {
//todo [kirillk] a dummy implementation
final Rectangle b = getBounds();
b.x += 100;
b.width -= 200;
b.y += 100;
b.height -= 200;
return b;
}
@Nullable
public static Component findNearestModalComponent(@NotNull Component c) {
Component eachParent = c;
while (eachParent != null) {
if (eachParent instanceof IdeFrame) return eachParent;
if (eachParent instanceof JDialog) {
if (((JDialog)eachParent).isModal()) return eachParent;
}
eachParent = eachParent.getParent();
}
return null;
}
public final BalloonLayout getBalloonLayout() {
return myBalloonLayout;
}
@Override
public boolean isInFullScreen() {
return myFrameDecorator != null && myFrameDecorator.isInFullScreen();
}
@NotNull
@Override
public ActionCallback toggleFullScreen(boolean state) {
if (myFrameDecorator != null) {
return myFrameDecorator.toggleFullScreen(state);
}
IdeFrame[] frames = WindowManager.getInstance().getAllProjectFrames();
for (IdeFrame frame : frames) {
((IdeFrameImpl)frame).updateBorder();
}
return ActionCallback.DONE;
}
@Override
public void toFront() {
super.toFront();
}
@Override
public void toBack() {
super.toBack();
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.packaging.test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.fluent.Request;
import org.elasticsearch.common.CheckedRunnable;
import org.elasticsearch.packaging.util.ServerUtils;
import org.elasticsearch.packaging.util.Shell;
import org.junit.After;
import org.junit.BeforeClass;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import static org.elasticsearch.packaging.util.Distribution.Platform.WINDOWS;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.not;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
/**
* Check that the quota-aware filesystem plugin can be installed, and that it operates as expected.
*/
public class QuotaAwareFsTests extends PackagingTestCase {
// private static final String QUOTA_AWARE_FS_PLUGIN_NAME = "quota-aware-fs";
private static final Path QUOTA_AWARE_FS_PLUGIN;
static {
// Re-read before each test so the plugin path can be manipulated within tests.
// Corresponds to DistroTestPlugin#QUOTA_AWARE_FS_PLUGIN_SYSPROP
QUOTA_AWARE_FS_PLUGIN = Paths.get(System.getProperty("tests.quota-aware-fs-plugin"));
}
@BeforeClass
public static void filterDistros() {
assumeTrue("only archives", distribution.isArchive());
assumeFalse("not on windows", distribution.platform == WINDOWS);
}
@After
public void teardown() throws Exception {
super.teardown();
cleanup();
}
/**
* Check that when the plugin is installed but the system property for passing the location of the related
* properties file is omitted, then Elasticsearch exits with the expected error message.
*/
public void test10ElasticsearchRequiresSystemPropertyToBeSet() throws Exception {
install();
installation.executables().pluginTool.run("install --batch \"" + QUOTA_AWARE_FS_PLUGIN.toUri() + "\"");
// Without setting the `es.fs.quota.file` property, ES should exit with a failure code.
final Shell.Result result = runElasticsearchStartCommand(null, false, false);
assertThat("Elasticsearch should have terminated unsuccessfully", result.isSuccess(), equalTo(false));
assertThat(
result.stderr,
containsString("Property es.fs.quota.file must be set to a URI in order to use the quota filesystem provider")
);
}
/**
* Check that when the plugin is installed but the system property for passing the location of the related
* properties file contains a non-existent URI, then Elasticsearch exits with the expected error message.
*/
public void test20ElasticsearchRejectsNonExistentPropertiesLocation() throws Exception {
install();
installation.executables().pluginTool.run("install --batch \"" + QUOTA_AWARE_FS_PLUGIN.toUri() + "\"");
sh.getEnv().put("ES_JAVA_OPTS", "-Des.fs.quota.file=file:///this/does/not/exist.properties");
final Shell.Result result = runElasticsearchStartCommand(null, false, false);
// Generate a Path for this location so that the platform-specific line-endings will be used.
final String platformPath = Path.of("/this/does/not/exist.properties").toString();
assertThat("Elasticsearch should have terminated unsuccessfully", result.isSuccess(), equalTo(false));
assertThat(result.stderr, containsString("NoSuchFileException: " + platformPath));
}
/**
* Check that Elasticsearch can load the plugin and apply the quota limits in the properties file. Also check that
* Elasticsearch polls the file for changes.
*/
public void test30ElasticsearchStartsWhenSystemPropertySet() throws Exception {
install();
int total = 20 * 1024 * 1024;
int available = 10 * 1024 * 1024;
installation.executables().pluginTool.run("install --batch \"" + QUOTA_AWARE_FS_PLUGIN.toUri() + "\"");
final Path quotaPath = getRootTempDir().resolve("quota.properties");
Files.writeString(quotaPath, String.format(Locale.ROOT, "total=%d\nremaining=%d\n", total, available));
sh.getEnv().put("ES_JAVA_OPTS", "-Des.fs.quota.file=" + quotaPath.toUri());
startElasticsearchAndThen(() -> {
final Totals actualTotals = fetchFilesystemTotals();
assertThat(actualTotals.totalInBytes, equalTo(total));
assertThat(actualTotals.availableInBytes, equalTo(available));
int updatedTotal = total * 3;
int updatedAvailable = available * 3;
// Check that ES is polling the properties file for changes by modifying the properties file
// and waiting for ES to pick up the changes.
Files.writeString(quotaPath, String.format(Locale.ROOT, "total=%d\nremaining=%d\n", updatedTotal, updatedAvailable));
// The check interval is 1000ms, but give ourselves some leeway.
Thread.sleep(2000);
final Totals updatedActualTotals = fetchFilesystemTotals();
assertThat(updatedActualTotals.totalInBytes, equalTo(updatedTotal));
assertThat(updatedActualTotals.availableInBytes, equalTo(updatedAvailable));
});
}
/**
* Check that the _cat API can list the plugin correctly.
*/
public void test40CatApiFiltersPlugin() throws Exception {
install();
int total = 20 * 1024 * 1024;
int available = 10 * 1024 * 1024;
installation.executables().pluginTool.run("install --batch \"" + QUOTA_AWARE_FS_PLUGIN.toUri() + "\"");
final Path quotaPath = getRootTempDir().resolve("quota.properties");
Files.writeString(quotaPath, String.format(Locale.ROOT, "total=%d\nremaining=%d\n", total, available));
sh.getEnv().put("ES_JAVA_OPTS", "-Des.fs.quota.file=" + quotaPath.toUri());
startElasticsearchAndThen(() -> {
final String uri = "http://localhost:9200/_cat/plugins?include_bootstrap=true&h=component,type";
String response = ServerUtils.makeRequest(Request.Get(uri)).trim();
assertThat(response, not(emptyString()));
List<String> lines = response.lines().collect(Collectors.toList());
assertThat(lines, hasSize(1));
final String[] fields = lines.get(0).split(" ");
assertThat(fields, arrayContaining("quota-aware-fs", "bootstrap"));
});
}
private void startElasticsearchAndThen(CheckedRunnable<Exception> runnable) throws Exception {
boolean started = false;
try {
startElasticsearch();
started = true;
runnable.run();
} finally {
if (started) {
stopElasticsearch();
}
}
}
private static class Totals {
int totalInBytes;
int availableInBytes;
Totals(int totalInBytes, int availableInBytes) {
this.totalInBytes = totalInBytes;
this.availableInBytes = availableInBytes;
}
}
private Totals fetchFilesystemTotals() {
try {
final String response = ServerUtils.makeRequest(Request.Get("http://localhost:9200/_nodes/stats"));
final ObjectMapper mapper = new ObjectMapper();
final JsonNode rootNode = mapper.readTree(response);
assertThat("Some nodes failed", rootNode.at("/_nodes/failed").intValue(), equalTo(0));
final String nodeId = rootNode.get("nodes").fieldNames().next();
final JsonNode fsNode = rootNode.at("/nodes/" + nodeId + "/fs/total");
return new Totals(fsNode.get("total_in_bytes").intValue(), fsNode.get("available_in_bytes").intValue());
} catch (Exception e) {
throw new RuntimeException("Failed to fetch filesystem totals: " + e.getMessage(), e);
}
}
}
| |
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.impl.definitions;
import graphql.language.FieldDefinition;
import graphql.language.ObjectTypeDefinition;
import graphql.language.TypeDefinition;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import io.swagger.models.Swagger;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.entity.ContentType;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.registry.api.Registry;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.session.UserRegistry;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException;
public class GraphQLSchemaDefinition {
protected Log log = LogFactory.getLog(getClass());
/**
* Extract GraphQL Operations from given schema
* @param schema graphQL Schema
* @return the arrayList of APIOperationsDTOextractGraphQLOperationList
*
*/
public List<URITemplate> extractGraphQLOperationList(String schema, String type) {
List<URITemplate> operationArray = new ArrayList<>();
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) ||
entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION)
|| entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
if (type == null) {
addOperations(entry, operationArray);
} else if (type.equals(entry.getValue().getName().toUpperCase())) {
addOperations(entry, operationArray);
}
}
}
return operationArray;
}
/**
*
* @param entry Entry
* @param operationArray operationArray
*/
private void addOperations(Map.Entry<String, TypeDefinition> entry, List<URITemplate> operationArray) {
for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
URITemplate operation = new URITemplate();
operation.setHTTPVerb(entry.getKey());
operation.setUriTemplate(fieldDef.getName());
operationArray.add(operation);
}
}
/**
* build schema with scopes and roles
*
* @param api api object
* @return schemaDefinition
*/
public String buildSchemaWithScopesAndRoles(API api) {
Swagger swagger = null;
Map<String, String> scopeRoleMap = new HashMap<>();
Map<String, String> operationScopeMap = new HashMap<>();
Map<String, String> operationAuthSchemeMap = new HashMap<>();
Map<String, String> operationThrottlingMap = new HashMap<>();
String operationScopeType;
StringBuilder schemaDefinitionBuilder = new StringBuilder(api.getGraphQLSchema());
StringBuilder operationScopeMappingBuilder = new StringBuilder();
StringBuilder scopeRoleMappingBuilder = new StringBuilder();
StringBuilder operationAuthSchemeMappingBuilder = new StringBuilder();
StringBuilder operationThrottlingMappingBuilder = new StringBuilder();
String swaggerDef = api.getSwaggerDefinition();
OpenAPI openAPI = null;
LinkedHashMap<String, Object> scopeBindings = null;
if (swaggerDef != null) {
OpenAPIParser parser = new OpenAPIParser();
openAPI = parser.readContents(swaggerDef, null, null).getOpenAPI();
}
Map<String, Object> extensions = null;
if (openAPI != null) {
extensions = openAPI.getComponents().getSecuritySchemes().get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).
getFlows().getImplicit().getExtensions();
}
if (extensions != null) {
scopeBindings = (LinkedHashMap<String, Object>) openAPI.getComponents().getSecuritySchemes().
get(APIConstants.SWAGGER_APIM_DEFAULT_SECURITY).getFlows().getImplicit().getExtensions().
get(APIConstants.SWAGGER_X_SCOPES_BINDINGS);
}
if (swaggerDef != null) {
for (URITemplate template : api.getUriTemplates()) {
String scopeInURITemplate = template.getScope() != null ? template.getScope().getKey() : null;
if (scopeInURITemplate != null) {
operationScopeMap.put(template.getUriTemplate(), scopeInURITemplate);
if (!scopeRoleMap.containsKey(scopeInURITemplate)) {
if (scopeBindings != null) {
scopeRoleMap.put(scopeInURITemplate, scopeBindings.get(scopeInURITemplate).toString());
}
}
}
}
for (URITemplate template : api.getUriTemplates()) {
operationThrottlingMap.put(template.getUriTemplate(), template.getThrottlingTier());
operationAuthSchemeMap.put(template.getUriTemplate(), template.getAuthType());
}
if (operationScopeMap.size() > 0) {
String base64EncodedURLOperationKey;
String base64EncodedURLScope;
for (Map.Entry<String, String> entry : operationScopeMap.entrySet()) {
base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
base64EncodedURLScope = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
operationScopeType = "type ScopeOperationMapping_" +
base64EncodedURLOperationKey + "{\n" + base64EncodedURLScope + ": String\n}\n";
operationScopeMappingBuilder.append(operationScopeType);
}
schemaDefinitionBuilder.append(operationScopeMappingBuilder.toString());
}
if (scopeRoleMap.size() > 0) {
List<String> scopeRoles = new ArrayList<>();
String[] roleList;
String scopeType;
String base64EncodedURLScopeKey;
String scopeRoleMappingType;
String base64EncodedURLRole;
String roleField;
for (Map.Entry<String, String> entry : scopeRoleMap.entrySet()) {
base64EncodedURLScopeKey = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
scopeType = "type ScopeRoleMapping_" + base64EncodedURLScopeKey + "{\n";
StringBuilder scopeRoleBuilder = new StringBuilder(scopeType);
roleList = entry.getValue().split(",");
for (String role : roleList) {
if (!role.equals("") && !scopeRoles.contains(role)) {
base64EncodedURLRole = Base64.getUrlEncoder().withoutPadding().
encodeToString(role.getBytes(Charset.defaultCharset()));
roleField = base64EncodedURLRole + ": String\n";
scopeRoleBuilder.append(roleField);
scopeRoles.add(role);
}
}
if (scopeRoles.size() > 0 && !StringUtils.isEmpty(scopeRoleBuilder.toString())) {
scopeRoleMappingType = scopeRoleBuilder.toString() + "}\n";
scopeRoleMappingBuilder.append(scopeRoleMappingType);
}
}
schemaDefinitionBuilder.append(scopeRoleMappingBuilder.toString());
}
if (operationThrottlingMap.size() > 0) {
String operationThrottlingType;
for (Map.Entry<String, String> entry : operationThrottlingMap.entrySet()) {
String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
String base64EncodedURLThrottilingTier = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getValue().getBytes(Charset.defaultCharset()));
operationThrottlingType = "type OperationThrottlingMapping_" +
base64EncodedURLOperationKey + "{\n" + base64EncodedURLThrottilingTier + ": String\n}\n";
operationThrottlingMappingBuilder.append(operationThrottlingType);
}
schemaDefinitionBuilder.append(operationThrottlingMappingBuilder.toString());
}
if (operationAuthSchemeMap.size() > 0) {
String operationAuthSchemeType;
String isSecurityEnabled;
for (Map.Entry<String, String> entry : operationAuthSchemeMap.entrySet()) {
String base64EncodedURLOperationKey = Base64.getUrlEncoder().withoutPadding().
encodeToString(entry.getKey().getBytes(Charset.defaultCharset()));
if (entry.getValue().equalsIgnoreCase(APIConstants.AUTH_NO_AUTHENTICATION)) {
isSecurityEnabled = APIConstants.OPERATION_SECURITY_DISABLED;
} else {
isSecurityEnabled = APIConstants.OPERATION_SECURITY_ENABLED;
}
operationAuthSchemeType = "type OperationAuthSchemeMapping_" +
base64EncodedURLOperationKey + "{\n" + isSecurityEnabled + ": String\n}\n";
operationAuthSchemeMappingBuilder.append(operationAuthSchemeType);
}
schemaDefinitionBuilder.append(operationAuthSchemeMappingBuilder.toString());
}
}
return schemaDefinitionBuilder.toString();
}
/**
* This method saves schema definition of GraphQL APIs in the registry
*
* @param api API to be saved
* @param schemaDefinition Graphql API definition as String
* @param registry user registry
* @throws APIManagementException
*/
public void saveGraphQLSchemaDefinition(API api, String schemaDefinition, Registry registry)
throws APIManagementException {
String apiName = api.getId().getApiName();
String apiVersion = api.getId().getVersion();
String apiProviderName = api.getId().getProviderName();
String resourcePath = APIUtil.getGraphqlDefinitionFilePath(apiName, apiVersion, apiProviderName);
try {
String saveResourcePath = resourcePath + apiProviderName + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR +
apiName + apiVersion + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION;
Resource resource;
if (!registry.resourceExists(saveResourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(saveResourcePath);
}
resource.setContent(schemaDefinition);
resource.setMediaType(String.valueOf(ContentType.TEXT_PLAIN));
registry.put(saveResourcePath, resource);
if (log.isDebugEnabled()) {
log.debug("Successfully imported the schema: " + schemaDefinition );
}
String[] visibleRoles = null;
if (api.getVisibleRoles() != null) {
visibleRoles = api.getVisibleRoles().split(",");
}
//Need to set anonymous if the visibility is public
APIUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), visibleRoles, resourcePath);
} catch (RegistryException e) {
String errorMessage = "Error while adding Graphql Definition for " + apiName + '-' + apiVersion;
log.error(errorMessage, e);
handleException(errorMessage, e);
}
}
/**
* Returns the graphQL content in registry specified by the wsdl name
*
* @param apiId Api Identifier
* @return graphQL content matching name if exist else null
*/
public String getGraphqlSchemaDefinition(APIIdentifier apiId, Registry registry) throws APIManagementException {
String apiName = apiId.getApiName();
String apiVersion = apiId.getVersion();
String apiProviderName = apiId.getProviderName();
String resourcePath = APIUtil.getGraphqlDefinitionFilePath(apiName, apiVersion, apiProviderName);
String schemaDoc = null;
String schemaName = apiId.getProviderName() + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR +
apiId.getApiName() + apiId.getVersion() + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION;
String schemaResourePath = resourcePath + schemaName;
try {
if (registry.resourceExists(schemaResourePath)) {
Resource schemaResource = registry.get(schemaResourePath);
schemaDoc = IOUtils.toString(schemaResource.getContentStream(),
RegistryConstants.DEFAULT_CHARSET_ENCODING);
}
} catch (RegistryException e) {
String msg = "Error while getting schema file from the registry " + schemaResourePath;
log.error(msg, e);
throw new APIManagementException(msg, e);
} catch (IOException e) {
String error = "Error occurred while getting the content of schema: " + schemaName;
log.error(error);
throw new APIManagementException(error, e);
}
return schemaDoc;
}
}
| |
/*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.kernel.modeshape.observer;
import static com.google.common.base.MoreObjects.toStringHelper;
import static org.fcrepo.kernel.api.observer.EventType.RESOURCE_CREATION;
import static org.fcrepo.kernel.api.observer.EventType.RESOURCE_DELETION;
import static org.fcrepo.kernel.api.observer.EventType.RESOURCE_MODIFICATION;
import static org.fcrepo.kernel.api.observer.EventType.RESOURCE_RELOCATION;
import static org.fcrepo.kernel.api.observer.OptionalValues.BASE_URL;
import static org.fcrepo.kernel.api.observer.OptionalValues.USER_AGENT;
import static javax.jcr.observation.Event.NODE_ADDED;
import static javax.jcr.observation.Event.NODE_MOVED;
import static javax.jcr.observation.Event.NODE_REMOVED;
import static javax.jcr.observation.Event.PROPERTY_ADDED;
import static javax.jcr.observation.Event.PROPERTY_CHANGED;
import static javax.jcr.observation.Event.PROPERTY_REMOVED;
import static org.modeshape.jcr.api.JcrConstants.JCR_CONTENT;
import static org.slf4j.LoggerFactory.getLogger;
import static java.time.Instant.ofEpochMilli;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton;
import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;
import static java.util.UUID.randomUUID;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;
import static java.util.stream.Stream.empty;
import java.io.IOException;
import java.net.URI;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import javax.jcr.RepositoryException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.observation.Event;
import org.fcrepo.kernel.api.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.api.observer.EventType;
import org.fcrepo.kernel.api.observer.FedoraEvent;
import org.fcrepo.kernel.modeshape.identifiers.HashConverter;
import org.fcrepo.kernel.modeshape.utils.FedoraSessionUserUtil;
import org.slf4j.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableMap;
/**
* A very simple abstraction to prevent event-driven machinery downstream from the repository from relying directly
* on a JCR interface {@link Event}. Can represent either a single JCR event or several.
*
* @author ajs6f
* @since Feb 19, 2013
*/
public class FedoraEventImpl implements FedoraEvent {
private final static ObjectMapper MAPPER = new ObjectMapper();
private final static Logger LOGGER = getLogger(FedoraEventImpl.class);
private final String path;
private final String userID;
private final URI userURI;
private final Instant date;
private final Map<String, String> info;
private final String eventID;
private final Set<String> eventResourceTypes;
private final Set<EventType> eventTypes = new HashSet<>();
private static final List<Integer> PROPERTY_TYPES = asList(Event.PROPERTY_ADDED,
Event.PROPERTY_CHANGED, Event.PROPERTY_REMOVED);
/**
* Create a new FedoraEvent
* @param type the Fedora EventType
* @param path the node path corresponding to this event
* @param resourceTypes the rdf types of the corresponding resource
* @param userID the acting user for this event
* @param userURI the uri of the acting user for this event
* @param date the timestamp for this event
* @param info supplementary information
*/
public FedoraEventImpl(final EventType type, final String path, final Set<String> resourceTypes,
final String userID, final URI userURI, final Instant date, final Map<String, String> info) {
this(singleton(type), path, resourceTypes, userID, userURI, date, info);
}
/**
* Create a new FedoraEvent
* @param types a collection of Fedora EventTypes
* @param path the node path corresponding to this event
* @param resourceTypes the rdf types of the corresponding resource
* @param userID the acting user for this event
* @param userURI the uri of the acting user for this event
* @param date the timestamp for this event
* @param info supplementary information
*/
public FedoraEventImpl(final Collection<EventType> types, final String path, final Set<String> resourceTypes,
final String userID, final URI userURI, final Instant date, final Map<String, String> info) {
requireNonNull(types, "FedoraEvent requires a non-null event type");
requireNonNull(path, "FedoraEvent requires a non-null path");
this.eventTypes.addAll(types);
this.path = path;
this.eventResourceTypes = resourceTypes;
this.userID = userID;
this.userURI = userURI;
this.date = date;
this.info = isNull(info) ? emptyMap() : info;
this.eventID = "urn:uuid:" + randomUUID().toString();
}
/**
* @return the event types of the underlying JCR {@link Event}s
*/
@Override
public Set<EventType> getTypes() {
return eventTypes;
}
/**
* @return the RDF types of the underlying Fedora Resource
**/
@Override
public Set<String> getResourceTypes() {
return eventResourceTypes;
}
/**
* @return the path of the underlying JCR {@link Event}s
*/
@Override
public String getPath() {
return path;
}
/**
* @return the user ID of the underlying JCR {@link Event}s
*/
@Override
public String getUserID() {
return userID;
}
/**
* @return the user URI of the underlying JCR {@link Event}s
*/
@Override
public URI getUserURI() {
return userURI;
}
/**
* @return the date of the FedoraEvent
*/
@Override
public Instant getDate() {
return date;
}
/**
* Get the event ID.
* @return Event identifier to use for building event URIs (e.g., in an external triplestore).
**/
@Override
public String getEventID() {
return eventID;
}
/**
* Return a Map with any additional information about the event.
* @return a Map of additional information.
*/
@Override
public Map<String, String> getInfo() {
return info;
}
@Override
public String toString() {
return toStringHelper(this)
.add("Event types:", getTypes().stream()
.map(EventType::getName)
.collect(joining(", ")))
.add("Event resource types:", String.join(",", eventResourceTypes))
.add("Path:", getPath())
.add("Date: ", getDate()).toString();
}
private static final Map<Integer, EventType> translation = ImmutableMap.<Integer, EventType>builder()
.put(NODE_ADDED, RESOURCE_CREATION)
.put(NODE_REMOVED, RESOURCE_DELETION)
.put(PROPERTY_ADDED, RESOURCE_MODIFICATION)
.put(PROPERTY_REMOVED, RESOURCE_MODIFICATION)
.put(PROPERTY_CHANGED, RESOURCE_MODIFICATION)
.put(NODE_MOVED, RESOURCE_RELOCATION).build();
/**
* Get the Fedora event type for a JCR type
*
* @param i the integer value of a JCR type
* @return EventType
*/
public static EventType valueOf(final Integer i) {
final EventType type = translation.get(i);
if (isNull(type)) {
throw new IllegalArgumentException("Invalid event type: " + i);
}
return type;
}
/**
* Convert a JCR Event to a FedoraEvent
* @param event the JCR Event
* @return a FedoraEvent
*/
public static FedoraEvent from(final Event event) {
requireNonNull(event);
try {
@SuppressWarnings("unchecked")
final Map<String, String> info = new HashMap<>(event.getInfo());
final String userdata = event.getUserData();
try {
if (userdata != null && !userdata.isEmpty()) {
final JsonNode json = MAPPER.readTree(userdata);
if (json.has(BASE_URL)) {
String url = json.get(BASE_URL).asText();
while (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
info.put(BASE_URL, url);
}
if (json.has(USER_AGENT)) {
info.put(USER_AGENT, json.get(USER_AGENT).asText());
}
} else {
LOGGER.debug("Event UserData is empty!");
}
} catch (final IOException ex) {
LOGGER.warn("Error extracting user data: " + userdata, ex.getMessage());
}
final Set<String> resourceTypes = getResourceTypes(event).collect(toSet());
return new FedoraEventImpl(valueOf(event.getType()), cleanPath(event), resourceTypes,
event.getUserID(), FedoraSessionUserUtil.getUserURI(event.getUserID()), ofEpochMilli(event
.getDate()), info);
} catch (final RepositoryException ex) {
throw new RepositoryRuntimeException("Error converting JCR Event to FedoraEvent", ex);
}
}
/**
* Get the RDF Types of the resource corresponding to this JCR Event
* @param event the JCR event
* @return the types recorded on the resource associated to this event
*/
public static Stream<String> getResourceTypes(final Event event) {
if (event instanceof org.modeshape.jcr.api.observation.Event) {
try {
final org.modeshape.jcr.api.observation.Event modeEvent =
(org.modeshape.jcr.api.observation.Event) event;
final Stream.Builder<NodeType> types = Stream.builder();
for (final NodeType type : modeEvent.getMixinNodeTypes()) {
types.add(type);
}
types.add(modeEvent.getPrimaryNodeType());
return types.build().map(NodeType::getName);
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
}
return empty(); // wasn't a ModeShape event, so we have no access to resource types
}
/**
* The JCR-based Event::getPath contains some Modeshape artifacts that must be removed or modified in
* order to correspond to the public resource path. For example, JCR Events will contain a trailing
* /jcr:content for Binaries, a trailing /propName for properties, and /#/ notation for URI fragments.
*/
private static String cleanPath(final Event event) throws RepositoryException {
// remove any trailing data for property changes
final String path = PROPERTY_TYPES.contains(event.getType()) ?
event.getPath().substring(0, event.getPath().lastIndexOf("/")) : event.getPath();
// reformat any hash URIs and remove any trailing /jcr:content
final HashConverter converter = new HashConverter();
return converter.reverse().convert(path.replaceAll("/" + JCR_CONTENT, ""));
}
}
| |
package org.apache.solr.handler.component;
/*
* Licensed to OpenCommerceSearch under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. OpenCommerceSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import com.google.common.collect.Lists;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.params.*;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.SolrCore;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.request.SolrRequestHandler;
import org.apache.solr.response.ResultContext;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.search.DocSlice;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.RefCounted;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.opencommercesearch.FacetConstants;
import org.opencommercesearch.RuleConstants;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.CoreMatchers.hasItems;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
/**
* @author Javier Mendez
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({SolrCore.class})
@PowerMockIgnore("org.jacoco.agent.rt.*")
public class RuleManagerComponentTest {
enum TestSetType { empty, blockRules, boostRules, facetRules, facetRulesReplace, facetRulesAppend, rulesButNoContent, rankingRule }
FieldType defaultFieldType = new FieldType();
{
defaultFieldType.setStored(true);
}
@Mock private ResponseBuilder rb;
@Mock private SolrQueryRequest req;
@Mock private SolrQueryResponse rsp;
@Mock private CoreContainer coreContainer;
private SolrCore rulesCore;
@Mock private SearchHandler searchHandler;
@Mock private SolrIndexSearcher rulesIndexSearcher;
private SolrCore facetsCore;
@Mock private SolrIndexSearcher facetsIndexSearcher;
RuleManagerComponent component = new RuleManagerComponent();
ModifiableSolrParams params = new ModifiableSolrParams();
@Before
public void setUp() throws Exception {
initMocks(this);
rulesCore = PowerMockito.mock(SolrCore.class);
facetsCore = PowerMockito.mock(SolrCore.class);
rb.req = req;
rb.rsp = rsp;
component.rulesCoreName = "rulesCore";
component.facetsCoreName = "facetsCore";
component.coreContainer = coreContainer;
component.initSeasonMappings(null);
when(req.getParams()).thenReturn(params);
when(coreContainer.getCore("rulesCore")).thenReturn(rulesCore);
when(coreContainer.getCore("facetsCore")).thenReturn(facetsCore);
when(rulesCore.getRequestHandler("/select")).thenReturn(searchHandler);
when(facetsCore.getRequestHandler("/select")).thenReturn(searchHandler);
when(rulesCore.getSearcher()).thenReturn(new RefCounted<SolrIndexSearcher>(rulesIndexSearcher) {
@Override
protected void close() {
}
});
when(facetsCore.getSearcher()).thenReturn(new RefCounted<SolrIndexSearcher>(facetsIndexSearcher) {
@Override
protected void close() {}
});
}
@Test
public void testInitComponent() throws IOException {
NamedList<String> list = new NamedList<String>();
list.add("seasonMapping", "expA:1,2,3,4,5,6;expB:7,8,9,10,11,12");
component.init(list);
int i = 1;
for(String actualSeason: component.seasonMapper) {
if (i <= 6) {
assertEquals("expA", actualSeason);
} else {
assertEquals("expB", actualSeason);
}
i++;
}
}
@Test
public void testInitComponentIncorrectSeasonMapping() throws IOException {
NamedList<String> list = new NamedList<String>();
list.add("seasonMapping", "someIncorrectMapping");
component.init(list);
int i = 1;
for(String actualSeason: component.seasonMapper) {
assertEquals(RuleManagerComponent.DEFAULT_SEASON_MAPPER, actualSeason);
i++;
}
}
@Test
public void testInitComponentWithSomeDefaults() throws IOException {
NamedList<String> list = new NamedList<String>();
list.add("seasonMapping", "expA:1,2,3,4,5,6");
component.init(list);
int i = 1;
for(String actualSeason: component.seasonMapper) {
if (i <= 6) {
assertEquals("expA", actualSeason);
} else {
assertEquals(RuleManagerComponent.DEFAULT_SEASON_MAPPER, actualSeason);
}
i++;
}
}
@Test
public void testNoPageType() throws IOException {
//Should do nothing (no exceptions)
component.prepare(rb);
verify(req, never()).setParams(any(SolrParams.class));
}
@Test
public void testNoRules() throws IOException {
prepareRuleDocs(TestSetType.empty);
setBaseParams();
//Should set basic params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
assertEquals("category:0.paulcatalog", outParams.get(CommonParams.FQ));
}
@Test
public void testBlockRules() throws IOException {
prepareRuleDocs(TestSetType.blockRules);
setBaseParams();
//Should filter out specified products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
String[] filterQueries = outParams.getParams(CommonParams.FQ);
assertEquals(3, filterQueries.length);
assertEquals("-productId:product0", filterQueries[0]);
assertEquals("-productId:product1", filterQueries[1]);
assertEquals("category:0.paulcatalog", filterQueries[2]);
}
@Test
public void testBoostRules() throws IOException {
prepareRuleDocs(TestSetType.boostRules);
setBaseParams();
//Should set boost for given products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,fixedBoost(productId,'product2') asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testExcludeBoostRulesExperiment() throws IOException {
prepareRuleDocs(TestSetType.boostRules);
setBaseParams();
params.set("excludeRules", "0,1");
//Should set boost for given products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testIncludeBoostRulesExperiment() throws IOException {
prepareRuleDocs(TestSetType.boostRules);
setBaseParams();
params.set("includeRules", "1");
//Should set boost for given products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,fixedBoost(productId,'product3') asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testBoostRulesRuleCatPage() throws IOException {
prepareRuleDocs(TestSetType.boostRules);
setBaseParams();
params.set(RuleManagerParams.RULE_PAGE, "true");
params.set(RuleManagerParams.CATEGORY_FILTER, ClientUtils.escapeQueryChars("rule cat page"));
//Should set boost for given products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,fixedBoost(productId,'product3') asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testRankingRules() throws IOException {
prepareRuleDocs(TestSetType.rankingRule);
setBaseParams();
//Should set ranking rules for given products
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
Calendar calendar = Calendar.getInstance();
String expectedSeason = component.seasonMapper[calendar.get(Calendar.MONTH)];
String expectedYear = Integer.toString(calendar.get(Calendar.YEAR));
String expectedBoost = "if(exists(query({!lucene v='(season:" + expectedSeason + " OR year:" + expectedYear + " OR season:SS1)'})),0.5,1.0)";
assertEquals(expectedBoost, outParams.get("boost"));
}
@Test
public void testFacetRules() throws IOException {
//TODO: make a good test for testFacetRules
prepareRuleDocs(TestSetType.facetRules);
setBaseParams();
//Should set basic facet params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
String[] facetFields = outParams.getParams(FacetParams.FACET_FIELD);
assertEquals(2, facetFields.length);
assertEquals("{!ex=collapse}fieldName1", facetFields[0]);
assertEquals("{!ex=collapse}fieldName2", facetFields[1]);
assertEquals("true", outParams.get(FacetParams.FACET));
}
@Test
public void testLocaleFacetRules() throws IOException {
testLocaleFacetRules(null, null);
}
@Test
public void testLocaleFacetRulesWithCountry() throws IOException {
testLocaleFacetRules("US", null);
}
@Test
public void testLocaleFacetRulesWithNoDefaultCountry() throws IOException {
testLocaleFacetRules("CR", null);
}
@Test
public void testLocaleFacetRulesWithCountryAndSite() throws IOException {
testLocaleFacetRules("US", "paulcatalog");
}
@Test
public void testLocaleFacetRulesWithSite() throws IOException {
testLocaleFacetRules(null, "paulcatalog");
}
private void testLocaleFacetRules(String country, String site) throws IOException {
prepareRuleFacetDocs(country, site, true);
setBaseParams(country);
//Should set basic facet params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
String[] facetFields = outParams.getParams(FacetParams.FACET_FIELD);
assertEquals(2, facetFields.length);
assertEquals("{!ex=collapse}" + fieldName("fieldName1", country, site), facetFields[0]);
assertEquals("{!ex=collapse}" + fieldName("fieldName2", country, site), facetFields[1]);
String[] rangeFields = outParams.getParams(FacetParams.FACET_RANGE);
assertEquals(1, rangeFields.length);
String fieldName3 = fieldName("fieldName3", country, site);
assertEquals("{!ex=collapse}" + fieldName3, rangeFields[0]);
assertEquals(Integer.valueOf(0), outParams.getFieldInt(fieldName3, FacetParams.FACET_RANGE_START));
String[] queryFields = outParams.getParams(FacetParams.FACET_QUERY);
String fieldName4 = fieldName("fieldName4", country, site);
assertEquals("{!ex=collapse}" + fieldName4 + ":fq", queryFields[0]);
assertEquals("true", outParams.get(FacetParams.FACET));
}
private String fieldName(String name, String country, String site) {
if (country == null && site == null) {
return name;
}
if (country != null && !name.endsWith(country)) {
name += country;
}
if (site != null) {
name += site;
}
return name;
}
@Test
public void testFacetRulesReplace() throws IOException {
//TODO: make a good test for testFacetRules
prepareRuleDocs(TestSetType.facetRulesReplace);
setBaseParams();
//Should set basic facet params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
assertEquals("{!ex=collapse}fieldName3", outParams.get(FacetParams.FACET_FIELD));
assertEquals("true", outParams.get(FacetParams.FACET));
}
@Test
public void testFacetRulesAppend() throws IOException {
//TODO: make a good test for testFacetRules
prepareRuleDocs(TestSetType.facetRulesAppend);
setBaseParams();
//Should set basic facet params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
String[] facetFields = outParams.getParams(FacetParams.FACET_FIELD);
assertEquals(3, facetFields.length);
assertEquals("{!ex=collapse}fieldName1", facetFields[0]);
assertEquals("{!ex=collapse}fieldName2", facetFields[1]);
assertEquals("{!ex=collapse}fieldName3", facetFields[2]);
assertEquals("true", outParams.get(FacetParams.FACET));
}
@Test
public void testRulesNoContent() throws IOException {
prepareRuleDocs(TestSetType.rulesButNoContent);
setBaseParams();
//Should re-order sort values and ignore duplicates
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testQueryWithSorts() throws IOException {
prepareRuleDocs(TestSetType.rulesButNoContent);
setBaseParams();
params.set(CommonParams.SORT, "reviewAverage desc,reviews asc,reviews desc,score asc");
//Should do nothing (including not failing!)
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,reviewAverage desc,reviews asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testBoostRulesWithSorts() throws IOException {
prepareRuleDocs(TestSetType.boostRules);
setBaseParams();
params.set(CommonParams.SORT, "reviewAverage desc,reviews asc,reviews desc,score asc");
//Should ignore boost for given products and prefer the incoming sort options
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,reviewAverage desc,reviews asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
}
@Test
public void testRulesCategoryPage() throws IOException {
prepareRuleDocs(TestSetType.empty);
setBaseParams();
params.set(RuleManagerParams.PAGE_TYPE, "category");
params.set(RuleManagerParams.RULE_PAGE, "true");
params.add(CommonParams.FQ, "(someField:val OR season:$SEASON OR year:$YEAR)");
params.add(CommonParams.FQ, "otherFilter:val");
NamedList<String> list = new NamedList<String>();
list.add("seasonMapping", "expA:1,2,3,4,5,6;expB:7,8,9,10,11,12");
component.init(list);
//Should set basic params
component.prepare(rb);
ArgumentCaptor<MergedSolrParams> argumentCaptor = ArgumentCaptor.forClass(MergedSolrParams.class);
verify(req).setParams(argumentCaptor.capture());
SolrParams outParams = argumentCaptor.getValue();
assertEquals("isToos asc,score desc,_version_ desc", outParams.get(CommonParams.SORT));
assertEquals("1.paulcatalog.", outParams.get("f.category.facet.prefix"));
Calendar calendar = Calendar.getInstance();
String expectedSeason = component.seasonMapper[calendar.get(Calendar.MONTH)];
String expectedYear = Integer.toString(calendar.get(Calendar.YEAR));
List<String> fqList = Lists.newArrayList(outParams.getParams(CommonParams.FQ));
assertThat(fqList, hasItems("category:0.paulcatalog",
"otherFilter:val",
"(someField:val OR season:" + expectedSeason + " OR year:" + expectedYear + ")"));
}
private void setBaseParams() {
setBaseParams(null);
}
private void setBaseParams(String country) {
params.set(RuleManagerParams.RULE, "true");
params.set(RuleManagerParams.PAGE_TYPE, "search");
params.set(RuleManagerParams.CATALOG_ID, "paulcatalog");
params.set(CommonParams.Q, "some books");
params.set(FacetParams.FACET, true);
if (country != null) {
params.set(RuleManagerParams.COUNTRY_ID, country);
}
}
/**
* Helper method that associates test result sets based on the current test.
*/
private void prepareRuleDocs(TestSetType setType) throws IOException {
switch (setType) {
case empty: {
setIdsToResultContext(new int[]{}, rulesCore);
break;
}
case rankingRule: {
setIdsToResultContext(new int[]{0}, rulesCore);
Document rankRule = new Document();
rankRule.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
rankRule.add(new Field(RuleConstants.FIELD_BOOST_FUNCTION, "if(exists(query({!lucene v='(season:$SEASON OR year:$YEAR OR season:SS1)'})),0.5,1.0)", defaultFieldType));
rankRule.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.rankingRule.toString(), defaultFieldType));
when(rulesIndexSearcher.doc(0)).thenReturn(rankRule);
break;
}
case blockRules: {
setIdsToResultContext(new int[]{0, 1}, rulesCore);
Document blockRule1 = new Document();
blockRule1.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
blockRule1.add(new Field(RuleConstants.FIELD_BLOCKED_PRODUCTS, "product0", defaultFieldType));
blockRule1.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.blockRule.toString(), defaultFieldType));
Document blockRule2 = new Document();
blockRule2.add(new Field(RuleConstants.FIELD_ID, "1", defaultFieldType));
blockRule2.add(new Field(RuleConstants.FIELD_BLOCKED_PRODUCTS, "product1", defaultFieldType));
blockRule2.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.blockRule.toString(), defaultFieldType));
when(rulesIndexSearcher.doc(1)).thenReturn(blockRule2);
when(rulesIndexSearcher.doc(0)).thenReturn(blockRule1);
break;
}
case boostRules: {
setIdsToResultContext(new int[]{0, 1}, rulesCore);
Document boostRule1 = new Document();
boostRule1.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
boostRule1.add(new Field(RuleConstants.FIELD_CATEGORY, "_all_", defaultFieldType));
boostRule1.add(new Field(RuleConstants.FIELD_BOOSTED_PRODUCTS, "product2", defaultFieldType));
boostRule1.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.boostRule.toString(), defaultFieldType));
boostRule1.add(new Field(RuleConstants.FIELD_EXPERIMENTAL, "true", defaultFieldType));
Document boostRule2 = new Document();
boostRule2.add(new Field(RuleConstants.FIELD_ID, "1", defaultFieldType));
boostRule2.add(new Field(RuleConstants.FIELD_CATEGORY, "_all_", defaultFieldType));
boostRule2.add(new Field(RuleConstants.FIELD_CATEGORY, "rule cat page", defaultFieldType));
boostRule2.add(new Field(RuleConstants.FIELD_BOOSTED_PRODUCTS, "product3", defaultFieldType));
boostRule2.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.boostRule.toString(), defaultFieldType));
boostRule2.add(new Field(RuleConstants.FIELD_EXPERIMENTAL, "true", defaultFieldType));
when(rulesIndexSearcher.doc(0)).thenReturn(boostRule1);
when(rulesIndexSearcher.doc(1)).thenReturn(boostRule2);
break;
}
case facetRules: {
prepareRuleFacetDocs(null, null, true);
break;
}
case facetRulesReplace:
case facetRulesAppend: {
String combineMode = RuleConstants.COMBINE_MODE_REPLACE;
if(setType == TestSetType.facetRulesAppend) {
combineMode = RuleConstants.COMBINE_MODE_APPEND;
}
setIdsToResultContext(new int[]{0, 1}, rulesCore);
Document facetRule1 = new Document();
facetRule1.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
facetRule1.add(new Field(RuleConstants.FIELD_FACET_ID, "facet1", defaultFieldType));
facetRule1.add(new Field(RuleConstants.FIELD_FACET_ID, "facet2", defaultFieldType));
facetRule1.add(new Field(RuleConstants.FIELD_COMBINE_MODE, combineMode, defaultFieldType));
facetRule1.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.facetRule.toString(), defaultFieldType));
Document facetRule2 = new Document();
facetRule2.add(new Field(RuleConstants.FIELD_ID, "1", defaultFieldType));
facetRule2.add(new Field(RuleConstants.FIELD_FACET_ID, "facet3", defaultFieldType));
facetRule2.add(new Field(RuleConstants.FIELD_COMBINE_MODE, combineMode, defaultFieldType));
facetRule2.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.facetRule.toString(), defaultFieldType));
when(rulesIndexSearcher.doc(0)).thenReturn(facetRule1);
when(rulesIndexSearcher.doc(1)).thenReturn(facetRule2);
setIdsToResultContext(new int[]{0, 1}, new int[]{2}, facetsCore);
Document facet1 = new Document();
facet1.add(new Field(FacetConstants.FIELD_ID, "facet1", defaultFieldType));
facet1.add(new Field(FacetConstants.FIELD_FIELD_NAME, "fieldName1", defaultFieldType));
facet1.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_FIELD, defaultFieldType));
Document facet2= new Document();
facet2.add(new Field(FacetConstants.FIELD_ID, "facet2", defaultFieldType));
facet2.add(new Field(FacetConstants.FIELD_FIELD_NAME, "fieldName2", defaultFieldType));
facet2.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_FIELD, defaultFieldType));
Document facet3= new Document();
facet3.add(new Field(FacetConstants.FIELD_ID, "facet3", defaultFieldType));
facet3.add(new Field(FacetConstants.FIELD_FIELD_NAME, "fieldName3", defaultFieldType));
facet3.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_FIELD, defaultFieldType));
when(facetsIndexSearcher.doc(0)).thenReturn(facet1);
when(facetsIndexSearcher.doc(1)).thenReturn(facet2);
when(facetsIndexSearcher.doc(2)).thenReturn(facet3);
break;
}
case rulesButNoContent: {
setIdsToResultContext(new int[]{0, 1, 2}, rulesCore);
Document facetRule = new Document();
facetRule.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_COMBINE_MODE, RuleConstants.COMBINE_MODE_REPLACE, defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.facetRule.toString(), defaultFieldType));
Document boostRule = new Document();
boostRule.add(new Field(RuleConstants.FIELD_ID, "1", defaultFieldType));
boostRule.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.boostRule.toString(), defaultFieldType));
Document blockRule = new Document();
blockRule.add(new Field(RuleConstants.FIELD_ID, "2", defaultFieldType));
blockRule.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.blockRule.toString(), defaultFieldType));
when(rulesIndexSearcher.doc(0)).thenReturn(facetRule);
when(rulesIndexSearcher.doc(1)).thenReturn(boostRule);
when(rulesIndexSearcher.doc(2)).thenReturn(blockRule);
break;
}
}
}
private void prepareRuleFacetDocs(String country, String site, boolean allTypes) throws IOException {
setIdsToResultContext(new int[]{0}, rulesCore);
Document facetRule = new Document();
facetRule.add(new Field(RuleConstants.FIELD_ID, "0", defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_FACET_ID, "facet1", defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_FACET_ID, "facet2", defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_COMBINE_MODE, RuleConstants.COMBINE_MODE_REPLACE, defaultFieldType));
facetRule.add(new Field(RuleConstants.FIELD_RULE_TYPE, RuleManagerComponent.RuleType.facetRule.toString(), defaultFieldType));
when(rulesIndexSearcher.doc(0)).thenReturn(facetRule);
if (allTypes) {
setIdsToResultContext(new int[]{0, 1, 2, 3}, facetsCore);
} else {
setIdsToResultContext(new int[]{0, 1}, facetsCore);
}
Document facet1 = new Document();
String field1 = "fieldName1";
facet1.add(new Field(FacetConstants.FIELD_ID, "facet1", defaultFieldType));
facet1.add(new Field(FacetConstants.FIELD_FIELD_NAME, field1, defaultFieldType));
facet1.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_FIELD, defaultFieldType));
setCountryAndSiteFields(country, site, facet1);
Document facet2= new Document();
String field2 = "fieldName2";
if (country != null) {
// test backwards compatibility
field2 += country;
}
facet2.add(new Field(FacetConstants.FIELD_ID, "facet2", defaultFieldType));
facet2.add(new Field(FacetConstants.FIELD_FIELD_NAME, field2, defaultFieldType));
facet2.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_FIELD, defaultFieldType));
setCountryAndSiteFields(country, site, facet2);
when(facetsIndexSearcher.doc(0)).thenReturn(facet1);
when(facetsIndexSearcher.doc(1)).thenReturn(facet2);
if (allTypes) {
Document rangeFacet = new Document();
String field3 = "fieldName3";
rangeFacet.add(new Field(FacetConstants.FIELD_ID, "facet3", defaultFieldType));
rangeFacet.add(new Field(FacetConstants.FIELD_FIELD_NAME, field3, defaultFieldType));
rangeFacet.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_RANGE, defaultFieldType));
setCountryAndSiteFields(country, site, rangeFacet);
when(facetsIndexSearcher.doc(2)).thenReturn(rangeFacet);
Document queryFacet = new Document();
String field4 = "fieldName4";
queryFacet.add(new Field(FacetConstants.FIELD_ID, "facet3", defaultFieldType));
queryFacet.add(new Field(FacetConstants.FIELD_FIELD_NAME, field4, defaultFieldType));
queryFacet.add(new Field(FacetConstants.FIELD_TYPE, FacetConstants.FACET_TYPE_QUERY, defaultFieldType));
queryFacet.add(new Field(FacetConstants.FIELD_QUERIES, "fq", defaultFieldType));
setCountryAndSiteFields(country, site, queryFacet);
when(facetsIndexSearcher.doc(3)).thenReturn(queryFacet);
}
}
private void setCountryAndSiteFields(String country, String site, Document facet) {
if (country != null) {
facet.add(new Field(FacetConstants.FIELD_BY_COUNTRY, "true", defaultFieldType));
}
if (site != null) {
facet.add(new Field(FacetConstants.FIELD_BY_SITE, "true", defaultFieldType));
}
}
/**
* Sets IDs to a result context and associates it with rulesCore.execute method.
* @param ids Ids to set.
*/
private void setIdsToResultContext(int[] ids, SolrCore core) {
setIdsToResultContext(ids, null, core);
}
/**
* Sets IDs to a result context and associates it with rulesCore.execute method.
* @param ids1 Ids to set.
* @param ids2 Second set of ids to return. If null, only one set is returned.
*/
private void setIdsToResultContext(int[] ids1, int[]ids2, SolrCore core) {
final ResultContext result = new ResultContext();
result.docs = new DocSlice(0, ids1.length, ids1, null, 0, ids1.length);
if(ids2 == null) {
doAnswer(new ResponseSetterAnswer(result)).when(core).execute((SolrRequestHandler) anyObject(), (SolrQueryRequest) anyObject(), (SolrQueryResponse) anyObject());
}
else {
final ResultContext secondResult = new ResultContext();
secondResult.docs = new DocSlice(0, ids2.length, ids2, null, 0, ids2.length);
doAnswer(new ResponseSetterAnswer(result, secondResult)).when(core).execute((SolrRequestHandler) anyObject(), (SolrQueryRequest) anyObject(), (SolrQueryResponse) anyObject());
}
}
/**
* Helper answer class to set the response context on SolrCore.execute calls.
*/
class ResponseSetterAnswer implements Answer<Object> {
ResultContext result;
ResultContext secondResult;
int callCounter = 0;
public ResponseSetterAnswer(ResultContext result) {
this.result = result;
}
public ResponseSetterAnswer(ResultContext result, ResultContext secondResult) {
this.result = result;
this.secondResult = secondResult;
}
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
SolrQueryResponse response = (SolrQueryResponse) invocationOnMock.getArguments()[2];
if(callCounter == 0 || secondResult == null) {
response.add("response", result);
}
else {
response.add("response", secondResult);
}
callCounter++;
return null;
}
}
@Test
public void testLoadRulesVerifyQueryWithCategory() throws IOException {
String category = "My super duper favorite Men's category";
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add(CommonParams.Q, "fantastic jackets");
requestParams.set(FacetParams.FACET, true);
requestParams.add(RuleManagerParams.CATEGORY_FILTER, category);
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
RuleManagerComponent mgr = new RuleManagerComponent();
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND ((fantastic jackets)^2 OR query:__all__)", filters.get(0));
assertEquals("category:__all__ OR category:" + category, filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesVerifyQueryWithWildCardStartColonStar() throws IOException {
String category = "My super duper favorite Men's category";
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add(CommonParams.Q, "*:*");
requestParams.set(FacetParams.FACET, true);
requestParams.add(RuleManagerParams.CATEGORY_FILTER, category);
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
RuleManagerComponent mgr = new RuleManagerComponent();
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND (query:__all__)", filters.get(0));
assertEquals("category:__all__ OR category:" + category, filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesVerifyQueryWithWildCardStar() throws IOException {
String category = "My super duper favorite Men's category";
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add(CommonParams.Q, "*");
requestParams.set(FacetParams.FACET, true);
requestParams.add(RuleManagerParams.CATEGORY_FILTER, category);
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
RuleManagerComponent mgr = new RuleManagerComponent();
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND (query:__all__)", filters.get(0));
assertEquals("category:__all__ OR category:" + category, filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesForCategoryPage() throws IOException {
String category = "My category";
RuleManagerComponent mgr = new RuleManagerComponent();
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.set(FacetParams.FACET, true);
requestParams.add(RuleManagerParams.CATEGORY_FILTER, category);
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.category);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("target:allpages OR target:categorypages", filters.get(0));
assertEquals("category:__all__ OR category:" + category, filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesVerifyQueryWithoutCategory() throws IOException {
RuleManagerComponent mgr = new RuleManagerComponent();
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.set(FacetParams.FACET, true);
requestParams.add(CommonParams.Q, "fantastic jackets");
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND ((fantastic jackets)^2 OR query:__all__)", filters.get(0));
assertEquals("category:__all__", filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesVerifyQueryWithBrandId() throws IOException {
RuleManagerComponent mgr = new RuleManagerComponent();
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add(CommonParams.Q, "fantastic jackets");
requestParams.set(FacetParams.FACET, true);
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
requestParams.add(RuleManagerParams.BRAND_ID, "someBrand");
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND ((fantastic jackets)^2 OR query:__all__)", filters.get(0));
assertEquals("category:__all__", filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__ OR brandId:someBrand", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Retail", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesVerifyQueryWithCloseout() throws IOException {
RuleManagerComponent mgr = new RuleManagerComponent();
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.set(FacetParams.FACET, true);
requestParams.add(CommonParams.Q, "fantastic jackets");
requestParams.add(RuleManagerParams.CATALOG_ID, "cata:alpha");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
requestParams.add(RuleManagerParams.BRAND_ID, "someBrand");
requestParams.add(CommonParams.FQ, "isCloseout:true");
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
List<String> filters = Arrays.asList(rulesQuery.getFilterQueries());
assertEquals(7, filters.size());
assertEquals("*:*", rulesQuery.getQuery());
assertEquals("(target:allpages OR target:searchpages) AND ((fantastic jackets)^2 OR query:__all__)", filters.get(0));
assertEquals("category:__all__", filters.get(1));
assertEquals("siteId:__all__ OR siteId:site:alpha", filters.get(2));
assertEquals("brandId:__all__ OR brandId:someBrand", filters.get(3));
assertEquals("subTarget:__all__ OR subTarget:Outlet", filters.get(4));
assertEquals("catalogId:__all__ OR catalogId:cata:alpha", filters.get(5));
assertEquals("-(((startDate:[* TO *]) AND -(startDate:[* TO NOW/DAY+1DAY])) OR (endDate:[* TO *] AND -endDate:[NOW/DAY+1DAY TO *]))", filters.get(6));
}
@Test
public void testLoadRulesNoCatalogId() throws IOException {
RuleManagerComponent mgr = new RuleManagerComponent();
ModifiableSolrParams requestParams = new ModifiableSolrParams();
requestParams.add(CommonParams.Q, "fantastic jackets");
requestParams.add(RuleManagerParams.SITE_IDS, "site:alpha");
SolrQuery rulesQuery = mgr.getRulesQuery(requestParams, RuleManagerComponent.PageType.search);
assertNull(rulesQuery);
}
}
| |
/**
* Copyright 2013-2016 Ronald W Hoffman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ScripterRon.BitcoinCore;
import java.io.EOFException;
import java.math.BigInteger;
import java.util.List;
/**
* BlockHeader contains the block header. It is used to validate transactions sent to us
* and to determine if a transaction has become unconfirmed because the block containing it
* is no longer on the block chain.
*
* <p>The block header has the following format:</p>
* <pre>
* Size Field Description
* ==== ===== ===========
* 4 bytes Version The block version number
* 32 bytes PrevBlockHash The hash of the preceding block in the chain
* 32 byte MerkleRoot The Merkle root for the transactions in the block
* 4 bytes Time The time the block was mined
* 4 bytes Difficulty The target difficulty
* 4 bytes Nonce The nonce used to generate the required hash
*</pre>
*/
public class BlockHeader implements ByteSerializable {
/** Block header length */
public static final int HEADER_SIZE = 80;
/** The number that is one greater than the largest representable SHA-256 hash */
public static final BigInteger LARGEST_HASH = BigInteger.ONE.shiftLeft(256);
/** Block version mask (BIP 9) */
public static final int VERSION_MASK = 0xe0000000;
/** BIP 9 version */
public static final int VERSION_BIP9 = 0x20000000;
/** Block version */
private final int version;
/** Block hash */
private final Sha256Hash blockHash;
/** Previous block hash */
private final Sha256Hash prevHash;
/** Time block was mined */
private final long blockTime;
/** Merkle root */
private final Sha256Hash merkleRoot;
/** Target difficulty */
private final long targetDifficulty;
/** Nonce */
private final int nonce;
/** Matched transactions */
private List<Sha256Hash> matches;
/**
* Create a new BlockHeader
*
* @param version Block version
* @param blockHash Block hash
* @param prevHash Previous block hash
* @param blockTime Time block was mined (seconds since Unix epoch)
* @param targetDifficulty Target difficulty
* @param merkleRoot Merkle root
* @param nonce Block nonce
*/
public BlockHeader(int version, Sha256Hash blockHash, Sha256Hash prevHash, long blockTime,
long targetDifficulty, Sha256Hash merkleRoot, int nonce) {
this.version = version;
this.blockHash = blockHash;
this.prevHash = prevHash;
this.blockTime = blockTime;
this.targetDifficulty = targetDifficulty;
this.merkleRoot = merkleRoot;
this.nonce = nonce;
}
/**
* Create a new BlockHeader
*
* @param version Block version
* @param blockHash Block hash
* @param prevHash Previous block hash
* @param blockTime Time block was mined (seconds since Unix epoch)
* @param targetDifficulty Target difficulty
* @param merkleRoot Merkle root
* @param nonce Block nonce
* @param matches Matching transactions
*/
public BlockHeader(int version, Sha256Hash blockHash, Sha256Hash prevHash, long blockTime,
long targetDifficulty, Sha256Hash merkleRoot, int nonce,
List<Sha256Hash> matches) {
this.version = version;
this.blockHash = blockHash;
this.prevHash = prevHash;
this.blockTime = blockTime;
this.targetDifficulty = targetDifficulty;
this.merkleRoot = merkleRoot;
this.nonce = nonce;
this.matches = matches;
}
/**
* Create a BlockHeader from the serialized block header
*
* @param bytes Serialized data
* @param doVerify TRUE to verify the block header structure
* @throws EOFException Serialized data is too short
* @throws VerificationException Block verification failed
*/
public BlockHeader(byte[] bytes, boolean doVerify) throws EOFException, VerificationException {
this(new SerializedBuffer(bytes), doVerify);
}
/**
* Create a BlockHeader from the serialized block header
*
* @param inBuffer Input buffer
* @param doVerify TRUE to verify the block header structure
* @throws EOFException Serialized data is too short
* @throws VerificationException Block verification failed
*/
public BlockHeader(SerializedBuffer inBuffer, boolean doVerify)
throws EOFException, VerificationException {
if (inBuffer.available() < HEADER_SIZE)
throw new EOFException("Header is too short");
//
// Compute the block hash from the serialized block header
//
int startPosition = inBuffer.getPosition();
blockHash = new Sha256Hash(Utils.reverseBytes(Utils.doubleDigest(inBuffer.getBytes(HEADER_SIZE))));
inBuffer.setPosition(startPosition);
//
// Parse the block header
//
version = inBuffer.getInt();
prevHash = new Sha256Hash(Utils.reverseBytes(inBuffer.getBytes(32)));
merkleRoot = new Sha256Hash(Utils.reverseBytes(inBuffer.getBytes(32)));
blockTime = inBuffer.getUnsignedInt();
targetDifficulty = inBuffer.getUnsignedInt();
nonce = inBuffer.getInt();
//
// Ensure this block does in fact represent real work done. If the difficulty is high enough,
// we can be fairly certain the work was done by the network.
//
// The block hash must be less than or equal to the target difficulty (the difficulty increases
// by requiring an increasing number of leading zeroes in the block hash). We will skip
// this test if the previous block hash is zero (used by unit tests)
//
if (doVerify) {
BigInteger target = Utils.decodeCompactBits(targetDifficulty);
if (target.signum() <= 0 || target.compareTo(NetParams.PROOF_OF_WORK_LIMIT) > 0)
throw new VerificationException("Target difficulty is not valid",
RejectMessage.REJECT_INVALID, blockHash);
BigInteger hash = blockHash.toBigInteger();
if (hash.compareTo(target) > 0 && !prevHash.equals(Sha256Hash.ZERO_HASH))
throw new VerificationException("Block hash is higher than target difficulty",
RejectMessage.REJECT_INVALID, blockHash);
//
// Verify the block timestamp
//
long currentTime = System.currentTimeMillis()/1000;
if (blockTime > currentTime+NetParams.ALLOWED_TIME_DRIFT)
throw new VerificationException("Block timestamp is too far in the future",
RejectMessage.REJECT_INVALID, blockHash);
}
}
/**
* Write the serialized block header to the output buffer
*
* @param outBuffer Output buffer
* @return Output buffer
*/
@Override
public SerializedBuffer getBytes(SerializedBuffer outBuffer) {
outBuffer.putInt(version)
.putBytes(Utils.reverseBytes(prevHash.getBytes()))
.putBytes(Utils.reverseBytes(merkleRoot.getBytes()))
.putUnsignedInt(blockTime)
.putUnsignedInt(targetDifficulty)
.putInt(nonce);
return outBuffer;
}
/**
* Return the serialized bytes
*
* @return Byte array
*/
@Override
public byte[] getBytes() {
return getBytes(new SerializedBuffer(HEADER_SIZE)).toByteArray();
}
/**
* Return the block version
*
* @return Block version
*/
public int getVersion() {
return version;
}
/**
* Returns the block hash
*
* @return Block hash
*/
public Sha256Hash getHash() {
return blockHash;
}
/**
* Returns the previous block hash
*
* @return Previous block hash
*/
public Sha256Hash getPrevHash() {
return prevHash;
}
/**
* Returns the block time
*
* @return Block time
*/
public long getBlockTime() {
return blockTime;
}
/**
* Returns the Merkle root
*
* @return Merkle root
*/
public Sha256Hash getMerkleRoot() {
return merkleRoot;
}
/**
* Returns the target difficulty
*
* @return Target difficulty
*/
public long getTargetDifficulty() {
return targetDifficulty;
}
/**
* Returns the block work
*
* @return Block work
*/
public BigInteger getBlockWork() {
BigInteger target = Utils.decodeCompactBits(targetDifficulty);
return LARGEST_HASH.divide(target.add(BigInteger.ONE));
}
/**
* Returns the block nonce
*
* @return Block nonce
*/
public int getNonce() {
return nonce;
}
/**
* Returns the list of matched transactions or null if there are no matched transactions
*
* @return List of matched transactions
*/
public List<Sha256Hash> getMatches() {
return matches;
}
/**
* Sets the list of matched transactions
*
* @param matches List of matched transactions or null if there are no matched transactions
*/
public void setMatches(List<Sha256Hash> matches) {
this.matches = matches;
}
}
| |
/*
* Copyright (c) 2016 by Gerrit Grunwald
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.hansolo.tilesfx;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.DoublePropertyBase;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.property.StringPropertyBase;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventTarget;
import javafx.event.EventType;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
/**
* Created by hansolo on 19.12.16.
*/
public class Section implements Comparable<Section> {
public final SectionEvent ENTERED_EVENT = new SectionEvent(this, null, SectionEvent.TILES_FX_SECTION_ENTERED);
public final SectionEvent LEFT_EVENT = new SectionEvent(this, null, SectionEvent.TILES_FX_SECTION_LEFT);
public final SectionEvent UPDATE_EVENT = new SectionEvent(this, null, SectionEvent.TILES_FX_SECTION_UPDATE);
private double _start;
private DoubleProperty start;
private double _stop;
private DoubleProperty stop;
private String _text;
private StringProperty text;
private Image _icon;
private ObjectProperty<Image> icon;
private Color _color;
private ObjectProperty<Color> color;
private Color _highlightColor;
private ObjectProperty<Color> highlightColor;
private Color _textColor;
private ObjectProperty<Color> textColor;
private double checkedValue;
private String styleClass;
// ******************** Constructors **************************************
/**
* Represents an area of a given range, defined by a start and stop value.
* This class is used for regions and areas in many gauges. It is possible
* to check a value against the defined range and fire events in case the
* value enters or leaves the defined region.
*/
public Section() {
this(-1, -1, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, "");
}
public Section(final double START, final double STOP) {
this(START, STOP, "", null, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, "");
}
public Section(final double START, final double STOP, final Color COLOR) {
this(START, STOP, "", null, COLOR, COLOR, Color.TRANSPARENT, "");
}
public Section(final double START, final double STOP, final Color COLOR, final Color HIGHLIGHT_COLOR) {
this(START, STOP, "", null, COLOR, HIGHLIGHT_COLOR, Color.TRANSPARENT, "");
}
public Section(final double START, final double STOP, final Image ICON, final Color COLOR) {
this(START, STOP, "", ICON, COLOR, COLOR, Color.WHITE, "");
}
public Section(final double START, final double STOP, final String TEXT, final Color COLOR) {
this(START, STOP, TEXT, null, COLOR, COLOR, Color.WHITE, "");
}
public Section(final double START, final double STOP, final String TEXT, final Color COLOR, final Color TEXT_COLOR) {
this(START, STOP, TEXT, null, COLOR, COLOR, TEXT_COLOR, "");
}
public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color TEXT_COLOR) {
this(START, STOP, TEXT, ICON, COLOR, COLOR, TEXT_COLOR, "");
}
public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR) {
this(START, STOP, TEXT, ICON, COLOR, HIGHLIGHT_COLOR, TEXT_COLOR, "");
}
public Section(final double START, final double STOP, final String TEXT, final Image ICON, final Color COLOR, final Color HIGHLIGHT_COLOR, final Color TEXT_COLOR, final String STYLE_CLASS) {
_start = START;
_stop = STOP;
_text = TEXT;
_icon = ICON;
_color = COLOR;
_highlightColor = HIGHLIGHT_COLOR;
_textColor = TEXT_COLOR;
checkedValue = -Double.MAX_VALUE;
styleClass = STYLE_CLASS;
}
// ******************** Methods *******************************************
/**
* Returns the value where the section begins.
* @return the value where the section begins
*/
public double getStart() { return null == start ? _start : start.get(); }
/**
* Defines the value where the section begins.
* @param START
*/
public void setStart(final double START) {
if (null == start) {
_start = START;
fireSectionEvent(UPDATE_EVENT);
} else {
start.set(START);
}
}
public DoubleProperty startProperty() {
if (null == start) {
start = new DoublePropertyBase(_start) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "start"; }
};
}
return start;
}
/**
* Returns the value where the section ends.
* @return the value where the section ends
*/
public double getStop() { return null == stop ? _stop : stop.get(); }
/**
* Defines the value where the section ends.
* @param STOP
*/
public void setStop(final double STOP) {
if (null == stop) {
_stop = STOP;
fireSectionEvent(UPDATE_EVENT);
} else {
stop.set(STOP);
}
}
public DoubleProperty stopProperty() {
if (null == stop) {
stop = new DoublePropertyBase(_stop) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "stop"; }
};
}
return stop;
}
/**
* Returns the text that was set for the section.
* @return the text that was set for the section
*/
public String getText() { return null == text ? _text : text.get(); }
/**
* Defines a text for the section.
* @param TEXT
*/
public void setText(final String TEXT) {
if (null == text) {
_text = TEXT;
fireSectionEvent(UPDATE_EVENT);
} else {
text.set(TEXT);
}
}
public StringProperty textProperty() {
if (null == text) {
text = new StringPropertyBase(_text) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "text"; }
};
}
return text;
}
/**
* Returns the image that was defined for the section.
* In some skins the image will be drawn (e.g. SimpleSkin).
* @return the image that was defined for the section
*/
public Image getImage() { return null == icon ? _icon : icon.get(); }
/**
* Defines an image for the section.
* In some skins the image will be drawn (e.g. SimpleSkin)
* @param IMAGE
*/
public void setIcon(final Image IMAGE) {
if (null == icon) {
_icon = IMAGE;
fireSectionEvent(UPDATE_EVENT);
} else {
icon.set(IMAGE);
}
}
public ObjectProperty<Image> iconProperty() {
if (null == icon) {
icon = new ObjectPropertyBase<Image>(_icon) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "icon"; }
};
}
return icon;
}
/**
* Returns the color that will be used to colorize the section in
* a gauge.
* @return the color that will be used to colorize the section
*/
public Color getColor() { return null == color ? _color : color.get(); }
/**
* Defines the color that will be used to colorize the section in
* a gauge.
* @param COLOR
*/
public void setColor(final Color COLOR) {
if (null == color) {
_color = COLOR;
fireSectionEvent(UPDATE_EVENT);
} else {
color.set(COLOR);
}
}
public ObjectProperty<Color> colorProperty() {
if (null == color) {
color = new ObjectPropertyBase<Color>(_color) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "color"; }
};
}
return color;
}
/**
* Returns the color that will be used to colorize the section in
* a gauge when it is highlighted.
* @return the color that will be used to colorize a highlighted section
*/
public Color getHighlightColor() { return null == highlightColor ? _highlightColor : highlightColor.get(); }
/**
* Defines the color that will be used to colorize a highlighted section
* @param COLOR
*/
public void setHighlightColor(final Color COLOR) {
if (null == highlightColor) {
_highlightColor = COLOR;
fireSectionEvent(UPDATE_EVENT);
} else {
highlightColor.set(COLOR);
}
}
public ObjectProperty<Color> highlightColorProperty() {
if (null == highlightColor) {
highlightColor = new ObjectPropertyBase<Color>(_highlightColor) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "highlightColor"; }
};
}
return highlightColor;
}
/**
* Returns the color that will be used to colorize the section text.
* @return the color that will be used to colorize the section text
*/
public Color getTextColor() { return null == textColor ? _textColor : textColor.get(); }
/**
* Defines the color that will be used to colorize the section text.
* @param COLOR
*/
public void setTextColor(final Color COLOR) {
if (null == textColor) {
_textColor = COLOR;
fireSectionEvent(UPDATE_EVENT);
} else {
textColor.set(COLOR);
}
}
public ObjectProperty<Color> textColorProperty() {
if (null == textColor) {
textColor = new ObjectPropertyBase<Color>(_textColor) {
@Override protected void invalidated() { fireSectionEvent(UPDATE_EVENT); }
@Override public Object getBean() { return Section.this; }
@Override public String getName() { return "textColor"; }
};
}
return textColor;
}
/**
* Returns the style class that can be used to colorize the section.
* This is not implemented in the current available skins.
* @return the style class that can be used to colorize the section
*/
public String getStyleClass() { return styleClass; }
/**
* Defines the style class that can be used to colorize the section.
* This is not implemented in the current available skins.
* @param STYLE_CLASS
*/
public void setStyleClass(final String STYLE_CLASS) { styleClass = STYLE_CLASS; }
/**
* Returns true if the given value is within the range between
* section.getStart() and section.getStop()
* @param VALUE
* @return true if the given value is within the range of the section
*/
public boolean contains(final double VALUE) {
return (Double.compare(VALUE, getStart()) >= 0 && Double.compare(VALUE, getStop()) <= 0);
}
/**
* Checks if the section contains the given value and fires an event
* in case the value "entered" or "left" the section. With this one
* can react if a value enters/leaves a specific region in a gauge.
* @param VALUE
*/
public void checkForValue(final double VALUE) {
boolean wasInSection = contains(checkedValue);
boolean isInSection = contains(VALUE);
if (!wasInSection && isInSection) {
fireSectionEvent(ENTERED_EVENT);
} else if (wasInSection && !isInSection) {
fireSectionEvent(LEFT_EVENT);
}
checkedValue = VALUE;
}
public boolean equals(final Section SECTION) {
return (Double.compare(SECTION.getStart(), getStart()) == 0 &&
Double.compare(SECTION.getStop(), getStop()) == 0 &&
SECTION.getText().equals(getText()));
}
@Override public int compareTo(final Section SECTION) {
if (Double.compare(getStart(), SECTION.getStart()) < 0) return -1;
if (Double.compare(getStart(), SECTION.getStart()) > 0) return 1;
return 0;
}
@Override public String toString() {
return new StringBuilder()
.append("{\n")
.append("\"text\":\"").append(getText()).append("\",\n")
.append("\"startValue\":").append(getStart()).append(",\n")
.append("\"stopValue\":").append(getStop()).append(",\n")
.append("\"color\":\"").append(getColor().toString().substring(0,8).replace("0x", "#")).append("\",\n")
.append("\"highlightColor\":\"").append(getHighlightColor().toString().substring(0,8).replace("0x", "#")).append("\",\n")
.append("\"textColor\":\"").append(getTextColor().toString().substring(0,8).replace("0x", "#")).append("\"\n")
.append("}")
.toString();
}
// ******************** Event handling ************************************
public final ObjectProperty<EventHandler<SectionEvent>> onSectionEnteredProperty() { return onSectionEntered; }
public final void setOnSectionEntered(EventHandler<SectionEvent> value) { onSectionEnteredProperty().set(value); }
public final EventHandler<SectionEvent> getOnSectionEntered() { return onSectionEnteredProperty().get(); }
private ObjectProperty<EventHandler<SectionEvent>> onSectionEntered = new SimpleObjectProperty<>(this, "onSectionEntered");
public final ObjectProperty<EventHandler<SectionEvent>> onSectionLeftProperty() { return onSectionLeft; }
public final void setOnSectionLeft(EventHandler<SectionEvent> value) { onSectionLeftProperty().set(value); }
public final EventHandler<SectionEvent> getOnSectionLeft() { return onSectionLeftProperty().get(); }
private ObjectProperty<EventHandler<SectionEvent>> onSectionLeft = new SimpleObjectProperty<>(this, "onSectionLeft");
public final ObjectProperty<EventHandler<SectionEvent>> onSectionUpdateProperty() { return onSectionUpdate; }
public final void setOnSectionUpdate(EventHandler<SectionEvent> value) { onSectionUpdateProperty().set(value); }
public final EventHandler<SectionEvent> getOnSectionUpdate() { return onSectionUpdateProperty().get(); }
private ObjectProperty<EventHandler<SectionEvent>> onSectionUpdate = new SimpleObjectProperty<>(this, "onSectionUpdate");
public void fireSectionEvent(final SectionEvent EVENT) {
final EventHandler<SectionEvent> HANDLER;
final EventType TYPE = EVENT.getEventType();
if (SectionEvent.TILES_FX_SECTION_ENTERED == TYPE) {
HANDLER = getOnSectionEntered();
} else if (SectionEvent.TILES_FX_SECTION_LEFT == TYPE) {
HANDLER = getOnSectionLeft();
} else if (SectionEvent.TILES_FX_SECTION_UPDATE == TYPE) {
HANDLER = getOnSectionUpdate();
} else {
HANDLER = null;
}
if (null == HANDLER) return;
HANDLER.handle(EVENT);
}
// ******************** Inner Classes *************************************
public static class SectionEvent extends Event {
public static final EventType<SectionEvent> TILES_FX_SECTION_ENTERED = new EventType<>(ANY, "TILES_FX_SECTION_ENTERED");
public static final EventType<SectionEvent> TILES_FX_SECTION_LEFT = new EventType<>(ANY, "TILES_FX_SECTION_LEFT");
public static final EventType<SectionEvent> TILES_FX_SECTION_UPDATE = new EventType<>(ANY, "TILES_FX_SECTION_UPDATE");
// ******************** Constructors **************************************
public SectionEvent(final Object SOURCE, final EventTarget TARGET, EventType<SectionEvent> TYPE) {
super(SOURCE, TARGET, TYPE);
}
}
}
| |
package edu.wkd.towave.memorycleaner.adapter.base;
import android.animation.Animator;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import edu.wkd.towave.memorycleaner.tools.ViewHelper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2016/5/2.
*/
public abstract class BaseRecyclerViewAdapter<E>
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected Context mContext;
private int mDuration = 300;
private Interpolator mInterpolator = new LinearInterpolator();
private int mLastPosition = -1;
private boolean isFirstOnly = true;
protected List<E> list;
private Map<Integer, onInternalClickListener<E>> canClickItem;
public BaseRecyclerViewAdapter(List<E> list) {
this(list, null);
}
public BaseRecyclerViewAdapter(List<E> list, Context context) {
this.list = list;
this.mContext = context;
}
public void add(E e) {
list.add(0, e);
notifyItemInserted(0);
}
public void update(E e, int fromPosition, int toPosition) {
list.remove(fromPosition);
list.add(toPosition, e);
if (fromPosition == toPosition) {
notifyItemChanged(fromPosition);
}
else {
notifyItemRemoved(fromPosition);
notifyItemInserted(toPosition);
}
//notifyItemRangeChanged(fromPosition, toPosition);
}
public void update(E e, int fromPosition) {
update(e, fromPosition, 0);
}
public void update(E e) {
int fromPosition = this.list.indexOf(e);
update(e, fromPosition, fromPosition);
}
public void remove(E e) {
int position = list.indexOf(e);
remove(position);
}
public void remove(int position) {
this.list.remove(position);
notifyItemRemoved(position);
}
public void setList(List<E> list) {
this.list.clear();
this.list.addAll(list);
//notifyDataSetChanged();
}
public List<E> getList() {
return list;
}
@Override public int getItemCount() {
return list.size();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder != null) {
addInternalClickListener(holder.itemView, position,
list.get(position));
}
}
@Override public int getItemViewType(int position) {
return 1;
}
private void addInternalClickListener(final View itemV, final Integer position, final E valuesMap) {
if (canClickItem != null) {
for (Integer key : canClickItem.keySet()) {
View inView = itemV.findViewById(key);
final onInternalClickListener<E> listener = canClickItem.get(
key);
if (inView != null && listener != null) {
inView.setOnClickListener(
(view) -> listener.OnClickListener(itemV, view,
position, valuesMap));
inView.setOnLongClickListener((view) -> {
listener.OnLongClickListener(itemV, view, position,
valuesMap);
return true;
});
}
}
}
}
public void setOnInViewClickListener(Integer key, onInternalClickListener<E> onClickListener) {
if (canClickItem == null) canClickItem = new HashMap<>();
canClickItem.put(key, onClickListener);
}
public interface onInternalClickListener<T> {
void OnClickListener(View parentV, View v, Integer position, T values);
void OnLongClickListener(View parentV, View v, Integer position, T values);
}
public static class onInternalClickListenerImpl<T>
implements onInternalClickListener<T> {
@Override
public void OnClickListener(View parentV, View v, Integer position, T values) {
}
@Override
public void OnLongClickListener(View parentV, View v, Integer position, T values) {
}
}
public void setDuration(int duration) {
mDuration = duration;
}
public void setInterpolator(Interpolator interpolator) {
mInterpolator = interpolator;
}
public void setStartPosition(int start) {
mLastPosition = start;
}
public void setFirstOnly(boolean firstOnly) {
isFirstOnly = firstOnly;
}
protected void animate(RecyclerView.ViewHolder holder, int position) {
if (!isFirstOnly || position > mLastPosition) {
for (Animator anim : getAnimators(holder.itemView)) {
anim.setDuration(mDuration).start();
anim.setInterpolator(mInterpolator);
}
mLastPosition = position;
}
else {
ViewHelper.clear(holder.itemView);
}
}
protected abstract Animator[] getAnimators(View view);
}
| |
package org.myrobotlab.net;
/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* http://blogs.sun.com/andreas/resource/InstallCert.java
* Use:
* java InstallCert hostname
* Example:
*% java InstallCert ecc.fedora.redhat.com
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.myrobotlab.logging.LoggerFactory;
import org.slf4j.Logger;
public class InstallCert {
public final static Logger log = LoggerFactory.getLogger(InstallCert.class);
private static class SavingTrustManager implements X509TrustManager {
private final X509TrustManager tm;
private X509Certificate[] chain;
SavingTrustManager(final X509TrustManager tm) {
this.tm = tm;
}
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
throw new UnsupportedOperationException();
}
@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
this.chain = chain;
this.tm.checkServerTrusted(chain, authType);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
// throw new UnsupportedOperationException();
}
}
private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
public static void main(final String[] args) throws KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
String host;
int port;
if ((args.length == 1) || (args.length == 2)) {
final String[] c = args[0].split(":");
host = c[0];
port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
final String pass = (args.length == 1) ? "changeit" : args[1];
install(host, port, pass);
} else {
log.error("Usage: java InstallCert <host>[:port] [passphrase]");
return;
}
}
public static void install(String urlstr) throws KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
install(urlstr, null);
}
public static void install(String urlstr, String pass) throws KeyManagementException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
URL url = new URL(urlstr);
install(url.getHost(), url.getPort(), pass);
}
public static void install(String host, String inport, String pass)
throws KeyManagementException, NumberFormatException, NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException {
String port = (inport != null) ? "443" : inport;
install(host, Integer.parseInt(port), pass);
}
public static void install(String host, Integer inport, String pass)
throws NoSuchAlgorithmException, IOException, CertificateException, KeyStoreException, KeyManagementException {
Integer port = (inport == null || inport == -1) ? 443 : inport;
char[] passphrase;
final String p = (pass == null) ? "changeit" : pass;
passphrase = p.toCharArray();
File file = new File("jssecacerts");
if (file.isFile() == false) {
final char SEP = File.separatorChar;
final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
log.info("Loading KeyStore " + file + "...");
final InputStream in = new FileInputStream(file);
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
final SSLContext context = SSLContext.getInstance("TLS");
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
final SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
final SSLSocketFactory factory = context.getSocketFactory();
log.info("Opening connection to " + host + ":" + port + "...");
final SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
log.info("Starting SSL handshake...");
socket.startHandshake();
socket.close();
log.info("No errors, certificate is already trusted");
} catch (final SSLException e) {
log.info("Exception: ", e);
}
final X509Certificate[] chain = tm.chain;
if (chain == null) {
log.info("Could not obtain server certificate chain");
return;
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
log.info("Server sent " + chain.length + " certificate(s):");
final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
final MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
final X509Certificate cert = chain[i];
log.info(" " + (i + 1) + " Subject " + cert.getSubjectDN());
log.info(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
log.info(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
log.info(" md5 " + toHexString(md5.digest()));
}
log.info("Enter certificate to add to trusted keystore" + " or 'q' to quit: [1]");
final String line = reader.readLine().trim();
int k;
try {
k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
} catch (final NumberFormatException e) {
log.info("KeyStore not changed");
return;
}
final X509Certificate cert = chain[k];
final String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
final OutputStream out = new FileOutputStream(file);
ks.store(out, passphrase);
out.close();
log.info("Cert: {}", cert);
log.info("Added certificate to keystore 'cacerts' using alias '" + alias + "'");
}
private static String toHexString(final byte[] bytes) {
final StringBuilder sb = new StringBuilder(bytes.length * 3);
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> 4]);
sb.append(HEXDIGITS[b & 15]);
sb.append(' ');
}
return sb.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.codec.textline;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import org.apache.mina.codec.ProtocolDecoder;
import org.apache.mina.codec.ProtocolDecoderException;
/**
* A {@link ProtocolDecoder} which decodes a text line into a string.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class TextLineDecoder implements ProtocolDecoder<ByteBuffer, String, TextLineDecoder.Context> {
private final Charset charset;
/** The delimiter used to determinate when a line has been fully decoded */
private final LineDelimiter delimiter;
/** An ByteBuffer containing the delimiter */
private ByteBuffer delimBuf;
/** The default maximum Line length. Default to 1024. */
private int maxLineLength = 1024;
/** The default maximum buffer length. Default to 128 chars. */
private int bufferLength = 128;
/**
* Creates a new instance with the current default {@link Charset} and
* {@link LineDelimiter#AUTO} delimiter.
*/
public TextLineDecoder() {
this(LineDelimiter.AUTO);
}
/**
* Creates a new instance with the current default {@link Charset} and the
* specified <tt>delimiter</tt>.
*/
public TextLineDecoder(String delimiter) {
this(new LineDelimiter(delimiter));
}
/**
* Creates a new instance with the current default {@link Charset} and the
* specified <tt>delimiter</tt>.
*/
public TextLineDecoder(LineDelimiter delimiter) {
this(Charset.defaultCharset(), delimiter);
}
/**
* Creates a new instance with the spcified <tt>charset</tt> and
* {@link LineDelimiter#AUTO} delimiter.
*/
public TextLineDecoder(Charset charset) {
this(charset, LineDelimiter.AUTO);
}
/**
* Creates a new instance with the spcified <tt>charset</tt> and the
* specified <tt>delimiter</tt>.
*/
public TextLineDecoder(Charset charset, String delimiter) {
this(charset, new LineDelimiter(delimiter));
}
/**
* Creates a new instance with the specified <tt>charset</tt> and the
* specified <tt>delimiter</tt>.
*/
public TextLineDecoder(Charset charset, LineDelimiter delimiter) {
if (charset == null) {
throw new IllegalArgumentException("charset parameter shuld not be null");
}
if (delimiter == null) {
throw new IllegalArgumentException("delimiter parameter should not be null");
}
this.charset = charset;
this.delimiter = delimiter;
// Convert delimiter to ByteBuffer if not done yet.
if (delimBuf == null) {
ByteBuffer tmp = charset.encode(CharBuffer.wrap(delimiter.getValue()));
tmp.rewind();
delimBuf = tmp;
}
}
/**
* Returns the allowed maximum size of the line to be decoded. If the size
* of the line to be decoded exceeds this value, the decoder will throw a
* {@link BufferDataException}. The default value is <tt>1024</tt> (1KB).
*/
public int getMaxLineLength() {
return maxLineLength;
}
/**
* Sets the allowed maximum size of the line to be decoded. If the size of
* the line to be decoded exceeds this value, the decoder will throw a
* {@link BufferDataException}. The default value is <tt>1024</tt> (1KB).
*/
public void setMaxLineLength(int maxLineLength) {
if (maxLineLength <= 0) {
throw new IllegalArgumentException("maxLineLength (" + maxLineLength + ") should be a positive value");
}
this.maxLineLength = maxLineLength;
}
/**
* Sets the default buffer size. This buffer is used in the Context to store
* the decoded line.
*
* @param bufferLength
* The default bufer size
*/
public void setBufferLength(int bufferLength) {
if (bufferLength <= 0) {
throw new IllegalArgumentException("bufferLength (" + maxLineLength + ") should be a positive value");
}
this.bufferLength = bufferLength;
}
/**
* Returns the allowed buffer size used to store the decoded line in the
* Context instance.
*/
public int getBufferLength() {
return bufferLength;
}
@Override
public Context createDecoderState() {
return new Context(bufferLength);
}
/**
* {@inheritDoc}
*/
@Override
public String decode(ByteBuffer in, Context ctx) {
if (LineDelimiter.AUTO.equals(delimiter)) {
return decodeAuto(ctx, in);
} else {
return decodeNormal(ctx, in);
}
}
/**
* {@inheritDoc}
*/
@Override
public void finishDecode(Context ctx) {
}
/**
* Decode a line using the default delimiter on the current system
*/
private String decodeAuto(Context ctx, ByteBuffer in) {
String decoded = null;
int matchCount = ctx.getMatchCount();
// Try to find a match
int oldPos = in.position();
int oldLimit = in.limit();
while (in.hasRemaining() && decoded == null) {
byte b = in.get();
boolean matched = false;
switch (b) {
case '\r':
// Might be Mac, but we don't auto-detect Mac EOL
// to avoid confusion.
matchCount++;
break;
case '\n':
// UNIX
matchCount++;
matched = true;
break;
default:
matchCount = 0;
}
if (matched) {
// Found a match.
int pos = in.position();
in.limit(pos);
in.position(oldPos);
ctx.append(in);
in.limit(oldLimit);
in.position(pos);
try {
if (ctx.getOverflowLength() == 0) {
ByteBuffer buf = ctx.getBuffer();
buf.flip();
buf.limit(buf.limit() - matchCount);
CharsetDecoder decoder = ctx.getDecoder();
CharBuffer buffer = decoder.decode(buf);
decoded = buffer.toString();
} else {
int overflowPosition = ctx.getOverflowLength();
throw new IllegalStateException("Line is too long: " + overflowPosition);
}
} catch (CharacterCodingException cce) {
throw new ProtocolDecoderException(cce);
} finally {
ctx.reset();
}
oldPos = pos;
matchCount = 0;
}
}
// Put remainder to buf.
in.position(oldPos);
ctx.append(in);
ctx.setMatchCount(matchCount);
return decoded;
}
/**
* Decode a line using the delimiter defined by the caller
*
* @return
*/
private String decodeNormal(Context ctx, ByteBuffer in) {
String decoded = null;
int matchCount = ctx.getMatchCount();
// Try to find a match
int oldPos = in.position();
int oldLimit = in.limit();
while (in.hasRemaining() && decoded == null) {
byte b = in.get();
if (delimBuf.get(matchCount) == b) {
matchCount++;
if (matchCount == delimBuf.limit()) {
// Found a match.
int pos = in.position();
in.limit(pos);
in.position(oldPos);
ctx.append(in);
in.limit(oldLimit);
in.position(pos);
try {
if (ctx.getOverflowLength() == 0) {
ByteBuffer buf = ctx.getBuffer();
buf.flip();
buf.limit(buf.limit() - matchCount);
CharsetDecoder decoder = ctx.getDecoder();
CharBuffer buffer = decoder.decode(buf);
decoded = new String(buffer.array());
} else {
int overflowLength = ctx.getOverflowLength();
throw new IllegalStateException("Line is too long: " + overflowLength);
}
} catch (CharacterCodingException cce) {
throw new ProtocolDecoderException(cce);
} finally {
ctx.reset();
}
oldPos = pos;
matchCount = 0;
}
} else {
// fix for DIRMINA-506 & DIRMINA-536
in.position(Math.max(0, in.position() - matchCount));
matchCount = 0;
}
}
// Put remainder to buf.
in.position(oldPos);
ctx.append(in);
ctx.setMatchCount(matchCount);
return decoded;
}
/**
* A Context used during the decoding of a lin. It stores the decoder, the
* temporary buffer containing the decoded line, and other status flags.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory
* Project</a>
* @version $Rev$, $Date$
*/
public class Context {
/** The decoder */
private final CharsetDecoder decoder;
/** The temporary buffer containing the decoded line */
private ByteBuffer buf;
/** The number of lines found so far */
private int matchCount = 0;
/**
* Overflow length
*/
private int overflowLength = 0;
/** Create a new Context object with a default buffer */
private Context(int bufferLength) {
decoder = charset.newDecoder();
buf = ByteBuffer.allocate(bufferLength);
}
public CharsetDecoder getDecoder() {
return decoder;
}
public ByteBuffer getBuffer() {
return buf;
}
public int getMatchCount() {
return matchCount;
}
public void setMatchCount(int matchCount) {
this.matchCount = matchCount;
}
public int getOverflowLength() {
return overflowLength;
}
public void reset() {
overflowLength = 0;
matchCount = 0;
decoder.reset();
buf.clear();
}
private void ensureSpace(int size) {
if (buf.position() + size > buf.capacity()) {
ByteBuffer b = ByteBuffer.allocate(buf.position() + size + bufferLength);
buf.flip();
b.put(buf);
buf = b;
}
}
public void append(ByteBuffer in) {
if (buf.position() > maxLineLength - in.remaining()) {
overflowLength = buf.position() + in.remaining();
buf.clear();
discard(in);
} else {
ensureSpace(in.remaining());
getBuffer().put(in);
}
}
private void discard(ByteBuffer in) {
in.position(in.limit());
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.rvesse.github.pr.stats;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.math3.stat.Frequency;
import org.apache.commons.math3.stat.descriptive.rank.Percentile;
import org.eclipse.egit.github.core.PullRequest;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.PullRequestService;
import org.eclipse.egit.github.core.service.UserService;
import com.github.rvesse.airline.HelpOption;
import com.github.rvesse.airline.SingleCommand;
import com.github.rvesse.airline.annotations.Arguments;
import com.github.rvesse.airline.annotations.Command;
import com.github.rvesse.airline.annotations.Option;
import com.github.rvesse.airline.annotations.Parser;
import com.github.rvesse.airline.annotations.restrictions.MutuallyExclusiveWith;
import com.github.rvesse.airline.annotations.restrictions.Required;
import com.github.rvesse.airline.help.Help;
import com.github.rvesse.airline.help.cli.CliCommandUsageGenerator;
import com.github.rvesse.airline.model.CommandMetadata;
import com.github.rvesse.airline.model.ParserMetadata;
import com.github.rvesse.airline.parser.ParseResult;
import com.github.rvesse.airline.parser.errors.ParseException;
import com.github.rvesse.airline.parser.errors.handlers.CollectAll;
import com.github.rvesse.github.pr.stats.collectors.AbstractPullRequestCollector;
import com.github.rvesse.github.pr.stats.collectors.AbstractUserPullRequestCollector;
import com.github.rvesse.github.pr.stats.collectors.LongStatsCollector;
import com.github.rvesse.github.pr.stats.collectors.MergingUserCollector;
import com.github.rvesse.github.pr.stats.collectors.PullRequestsCollector;
import com.github.rvesse.github.pr.stats.collectors.UserCollector;
import com.github.rvesse.github.pr.stats.comparators.UserComparator;
@Command(name = "pr-stats", description = "Generates Pull Request statistics for a GitHub repository")
@Parser(errorHandler = CollectAll.class)
public class PullRequestStats {
@Arguments(title = { "Owner", "Repository" }, description = "Sets the repository for which to generate statistics")
@Required
private List<String> repo = new ArrayList<String>();
@Option(name = { "-u", "--user",
"--username" }, title = "GitHubUsername", description = "Sets the GitHub username with which to authenticate, it is generally more secure to use OAuth2 tokens via the --oauth option. If omitted the application will prompt you for it.")
private String user;
@Option(name = { "-p", "--pwd",
"--password" }, title = "GitHubPassword", description = "Sets the GitHub password with which to authenticate, it is generally more secure to use OAuth2 tokens via the --oauth option. If omitted the application will prompt you for it.", hidden = true)
private String pwd;
@Option(name = {
"--oauth" }, title = "GitHubOAuth2Token", description = "Sets the GitHub OAuth2 Token to use for authentication")
@MutuallyExclusiveWith(tag = "OAuth")
private String oauthToken;
@Option(name = {
"--oauth-file" }, title = "GitHubOAuth2TokenFile", description = "Sets the file containing the GitHub OAuth2 Token to use for authentication")
@MutuallyExclusiveWith(tag = "OAuth")
private String oauthTokenFile;
@Option(name = { "--user-summary" }, description = "When set includes a user summary in the statistics")
private boolean userSummary = false;
@Option(name = { "--user-stats" }, description = "When set includes detailed user statistics")
private boolean userDetailedStats = false;
@Option(name = {
"--merge-summary" }, description = "When set includes a summary of merging users in the statistics i.e. details about who merges the pull requests")
private boolean mergeSummary = false;
@Option(name = {
"--merge-stats" }, description = "When set includes detailed merging user statistics i.e. details about who merges the pull requests")
private boolean mergeDetailedStats = false;
@Option(name = { "-a", "--all" }, description = "When set includes all available statistics in the output")
private boolean all = false;
@Inject
private HelpOption<PullRequestStats> help = new HelpOption<PullRequestStats>();
@Inject
private CommandMetadata metadata;
@Inject
private ParserMetadata<PullRequestStats> parserConfig;
public static void main(String[] args) throws MalformedURLException, IOException {
SingleCommand<PullRequestStats> parser = SingleCommand.singleCommand(PullRequestStats.class);
try {
ParseResult<PullRequestStats> results = parser.parseWithResult(args);
if (results.wasSuccessful()) {
// Run the command
results.getCommand().run();
} else {
// Display errors
int errNum = 1;
for (ParseException e : results.getErrors()) {
System.err.format("Error #%d: %s\n", errNum, e.getMessage());
errNum++;
}
System.err.println();
// Show help
Help.help(parser.getCommandMetadata(), System.out);
}
System.exit(0);
} catch (ParseException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (Throwable t) {
System.err.println(t.getMessage());
t.printStackTrace(System.err);
System.exit(2);
}
}
public void run() throws IOException {
if (help.showHelpIfRequested()) {
CliCommandUsageGenerator generator = new CliCommandUsageGenerator();
generator.usage(null, null, "pr-stats", this.metadata, this.parserConfig, System.out);
return;
}
GitHubClient client = new GitHubClient();
prepareCredentials(client);
client.setUserAgent("GitHub PR Stats Bot/0.1.0 (+http://github.com/rvesse/gh-pr-stats.git)");
// Get the user just to force us to make one request so we can get stats
// about the remaining requests
@SuppressWarnings("unused")
User user = new UserService(client).getUser();
System.out.println("You have " + client.getRemainingRequests() + " GitHub API requests of "
+ client.getRequestLimit() + " remaining");
long start = client.getRemainingRequests();
// Collect statistics for the pull requests
PullRequestService prService = new PullRequestService(client);
RepositoryId repoId = prepareRepositoryId();
List<PullRequest> prs = prService.getPullRequests(repoId, "all");
PullRequestsCollector collector = new PullRequestsCollector(
this.userSummary || this.userDetailedStats || this.all,
this.mergeSummary || this.mergeDetailedStats || this.all);
collector.start();
for (PullRequest pr : prs) {
System.out.println("Processing PR #" + pr.getNumber());
collector.collect(client, pr);
}
collector.end();
// Inform the user about how many API requests were used
System.out.println();
System.out.println("You have " + client.getRemainingRequests() + " GitHub API requests of "
+ client.getRequestLimit() + " remaining");
System.out.println(
"Generating statistics used " + (start - client.getRemainingRequests()) + " GitHub API requests");
System.out.println();
// Output Stats
// Basic stats
outputBasicStatus(collector);
System.out.println();
// Age Stats
outputAgeStats(collector.getDaysToMergeStats(), "Days to Merge", true);
System.out.println();
outputAgeStats(collector.getDaysOpenStats(), "Days Open", true);
System.out.println();
outputAgeStats(collector.getDaysToCloseStats(), "Days to Close", true);
System.out.println();
// User Stats
List<UserCollector> userStats = collector.getUserStats();
UserComparator<UserCollector> userComparator = new UserComparator<UserCollector>();
if (this.userSummary || this.all) {
System.out.println("Total Users: " + userStats.size());
if (userStats.size() > 0) {
UserCollector maxUser = Collections.max(userStats, userComparator);
List<UserCollector> maxUsers = findEquivalent(userStats, maxUser, userComparator);
UserCollector minUser = Collections.min(userStats, userComparator);
List<UserCollector> minUsers = findEquivalent(userStats, minUser, userComparator);
System.out.println("Max Pull Requests by User: " + maxUser.getTotal() + " " + maxUsers);
System.out.println("Min Pull Requests by User: " + minUser.getTotal() + " " + minUsers);
System.out.println("Average Pull Requests per User: " + (collector.getTotal() / userStats.size()));
}
System.out.println();
}
if (userStats.size() > 0 && (this.userDetailedStats || this.all)) {
Collections.sort(userStats, userComparator);
for (AbstractUserPullRequestCollector userCollector : userStats) {
outputUserStats(userCollector);
System.out.println();
}
}
// Merging User Stats
List<MergingUserCollector> mergingUserStats = collector.getMergingUserStats();
UserComparator<MergingUserCollector> mergeUserComparator = new UserComparator<MergingUserCollector>();
if (this.mergeSummary || this.all) {
System.out.println("Total Merging Users: " + mergingUserStats.size());
if (mergingUserStats.size() > 0) {
MergingUserCollector maxUser = Collections.max(mergingUserStats, mergeUserComparator);
List<MergingUserCollector> maxUsers = findEquivalent(mergingUserStats, maxUser, mergeUserComparator);
MergingUserCollector minUser = Collections.min(mergingUserStats, mergeUserComparator);
List<MergingUserCollector> minUsers = findEquivalent(mergingUserStats, minUser, mergeUserComparator);
System.out.println("Max Pull Requests Merged by User: " + maxUser.getMerged() + " " + maxUsers);
System.out.println("Min Pull Requests Merged by User: " + minUser.getMerged() + " " + minUsers);
System.out.println(
"Average Pull Requests Merged per User: " + (collector.getMerged() / mergingUserStats.size()));
}
System.out.println();
}
if (mergingUserStats.size() > 0 && (this.mergeDetailedStats || this.all)) {
Collections.sort(mergingUserStats, mergeUserComparator);
for (MergingUserCollector userCollector : mergingUserStats) {
outputUserStats(userCollector);
System.out.println();
}
}
}
private void outputBasicStatus(AbstractPullRequestCollector collector) {
if (collector.getTotal() == 0)
return;
System.out.println("Total Pull Requests: " + collector.getTotal());
if (collector.getMerged() > 0) {
System.out.println("Merged Pull Requests: " + collector.getMerged());
}
if (collector.getOpen() > 0) {
System.out.println("Open Pull Requests: " + collector.getOpen());
System.out.println("Open Mergeable Pull Requests: " + collector.getOpenMergeable());
}
if (collector.getClosed() > 0) {
System.out.println("Closed Pull Requests: " + collector.getClosed());
}
if (collector.getMerged() > 0) {
outputPercentage(collector.getMergedPercentage(), "Merged Pull Requests");
}
if (collector.getOpen() > 0) {
outputPercentage(collector.getOpenPercentage(), "Open Pull Requests");
}
if (collector.getClosed() > 0) {
outputPercentage(collector.getClosedPercentage(), "Closed Pull Requests");
}
}
private void outputAgeStats(LongStatsCollector collector, String metric, boolean includeFrequencies) {
if (collector.getDescriptiveStats().getN() == 0)
return;
// Present stats
System.out.println("Minimum " + metric + ": " + (long) collector.getDescriptiveStats().getMin());
System.out.println("Maximum " + metric + ": " + (long) collector.getDescriptiveStats().getMax());
System.out.println(
"Average (Arithmetic Mean) " + metric + ": " + (long) collector.getDescriptiveStats().getMean());
System.out.println("Average (Geometric Mean) " + metric + ": "
+ (long) collector.getDescriptiveStats().getGeometricMean());
if (includeFrequencies) {
long[] modes = collector.getModes();
if (modes != null)
System.out.println("Most Popular " + metric + ": " + toPrintableList(modes));
System.out.println("Cumulative Frequency:");
Frequency freq = collector.getFrequencies();
Percentile percentiles = collector.getPercentiles();
outputPercentile(freq, percentiles, 25, metric);
outputPercentile(freq, percentiles, 50, metric);
outputPercentile(freq, percentiles, 75, metric);
outputPercentile(freq, percentiles, 100, metric);
outputCumulativePrecentage(freq, 7, metric);
outputCumulativePrecentage(freq, 30, metric);
outputCumulativePrecentage(freq, 90, metric);
outputCumulativePrecentage(freq, 180, metric);
outputCumulativePrecentage(freq, 365, metric);
}
}
private <T extends AbstractUserPullRequestCollector> void outputUserStats(T collector) {
System.out.println(collector.getUser().getLogin());
outputBasicStatus(collector);
outputPercentage(collector.getSelfMergedPercentage(), "Self Merged Pull Requests");
outputAgeStats(collector.getDaysToMergeStats(), "Days to Merge", false);
outputAgeStats(collector.getDaysOpenStats(), "Days Open", false);
outputAgeStats(collector.getDaysToCloseStats(), "Days to Close", false);
}
private RepositoryId prepareRepositoryId() {
if (this.repo.size() < 2) {
System.err.println(
"Insufficient repository information provided, you must provide both the owner and repository name");
System.exit(1);
}
System.out.println("Generating PR Statistics for repository " + this.repo.get(0) + "/" + this.repo.get(1));
return new RepositoryId(this.repo.get(0), this.repo.get(1));
}
private void prepareCredentials(GitHubClient client) {
if (this.oauthToken != null) {
// OAuth 2 Authentication
client.setOAuth2Token(this.oauthToken);
System.out.println("Authenticating to GitHub using OAuth2 Token");
} else if (this.oauthTokenFile != null) {
// OAuth 2 Authentication with token stored in file
try (BufferedReader reader = new BufferedReader(new FileReader(this.oauthTokenFile))) {
this.oauthToken = reader.readLine();
client.setOAuth2Token(this.oauthToken);
System.out.println("Authenticating to GitHub using OAuth2 Token");
} catch (IOException e) {
throw new RuntimeException(
String.format("Unable to read specified OAuth Token file %s", this.oauthTokenFile));
}
} else {
// Username and Password authentication
if (this.user == null) {
System.out.print("Please enter your GitHub username [" + System.getProperty("user.name") + "]: ");
this.user = System.console().readLine();
}
if (this.user == null || this.user.length() == 0) {
this.user = System.getProperty("user.name");
}
if (this.pwd == null) {
System.out.print("Please enter your GitHub password: ");
this.pwd = new String(System.console().readPassword());
}
if (this.pwd == null || this.pwd.length() == 0) {
System.err.println("Failed to specify a GitHub password");
System.exit(1);
}
System.out.println("Authenticating to GitHub using Username and Password as user " + this.user);
client.setCredentials(this.user, this.pwd);
}
}
private void outputPercentage(double percentage, String metric) {
System.out.println("Percentage " + metric + ": " + (int) (percentage * 100) + "%");
}
private void outputPercentile(Frequency freq, Percentile percentiles, int p, String metric) {
long value = (long) percentiles.evaluate((double) p);
System.out.println(" " + p + "% (" + value + " " + metric + "): " + (long) freq.getCumFreq(value));
}
private void outputCumulativePrecentage(Frequency freq, long value, String metric) {
System.out.println("Under " + value + " " + metric + ": " + (long) (freq.getCumPct(value) * 100) + "%");
}
private String toPrintableList(long[] values) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < values.length; i++) {
if (i > 0)
builder.append(',');
builder.append(values[i]);
}
return builder.toString();
}
private <T extends AbstractUserPullRequestCollector> List<T> findEquivalent(List<T> users, T user,
UserComparator<T> comparator) {
List<T> equivUsers = new ArrayList<T>();
for (T possUser : users) {
if (comparator.compare(user, possUser) == 0)
equivUsers.add(possUser);
}
return equivUsers;
}
}
| |
/**
* $Revision: 3034 $
* $Date: 2005-11-04 21:02:33 -0300 (Fri, 04 Nov 2005) $
*
* Copyright (C) 2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.reporting.stats;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import org.jivesoftware.openfire.archive.MonitoringConstants;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.reporting.util.TaskEngine;
import org.jivesoftware.openfire.stats.Statistic;
import org.jivesoftware.openfire.stats.StatisticsManager;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.cache.CacheFactory;
import org.jrobin.core.ConsolFuns;
import org.jrobin.core.DsTypes;
import org.jrobin.core.FetchData;
import org.jrobin.core.RrdBackendFactory;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdException;
import org.jrobin.core.Sample;
import org.picocontainer.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The stats workhorse. Handles the job of sampling the different statistics existing in
* the system and persiting them to the database. Also, it tracks through a <i>StatDefinition</i>
* for each stat all the meta information related to a stat.
*
* @author Alexander Wenckus
*/
public class StatsEngine implements Startable {
private static final Logger Log = LoggerFactory.getLogger(StatsEngine.class);
private static final int STAT_RESOULUTION = 60;
private final TaskEngine taskEngine;
private final StatisticsManager statsManager;
private final Map<String, StatDefinition> definitionMap = new HashMap<String, StatDefinition>();
private final Map<String, List<StatDefinition>> multiMap = new HashMap<String, List<StatDefinition>>();
private SampleTask samplingTask = new SampleTask();
/**
* The default constructor used by the plugin container.
*
* @param taskEngine Used to execute tasks.
*/
public StatsEngine(TaskEngine taskEngine) {
this.taskEngine = taskEngine;
statsManager = StatisticsManager.getInstance();
}
public void start() {
try {
// Set that RRD files will be stored in the database
RrdBackendFactory.registerAndSetAsDefaultFactory(new RrdSqlBackendFactory());
// After 10 milliseconds begin sampling in 60 second intervals. Note: We need to start
// asap so that the UI can access this info upon start up
taskEngine.scheduleAtFixedRate(samplingTask, 10, STAT_RESOULUTION * 1000L);
}
catch (RrdException e) {
Log.error("Error initializing RrdbPool.", e);
}
}
public void stop() {
// Clean-up sampling task
samplingTask.cancel();
}
private void checkDatabase(StatDefinition[] def) throws RrdException, IOException {
File directory = new File(getStatsDirectroy());
if (directory.exists()) {
// check if the rrd exists
File rrdFile = new File(getRrdFilePath(def[0].getDbPath()));
if (rrdFile.exists() && rrdFile.canRead()) {
try {
// Import existing RRD file into the DB
RrdSqlBackend.importRRD(def[0].getDbPath(), rrdFile);
// Delete the RRD file
rrdFile.delete();
} catch (IOException e) {
Log.error("Error importing rrd file: " + rrdFile, e);
}
}
}
// check if the rrd exists
if (!RrdSqlBackend.exists(def[0].getDbPath())) {
RrdDb db = null;
try {
RrdDef rrdDef = new RrdDef(def[0].getDbPath(), STAT_RESOULUTION);
for (StatDefinition stat : def) {
String dsType = determineDsType(stat.getStatistic().getStatType());
rrdDef.addDatasource(stat.getDatasourceName(), dsType, 5 * STAT_RESOULUTION, 0,
Double.NaN);
}
// Every minute for 1 hour.
rrdDef.addArchive(((DefaultStatDefinition) def[0]).
consolidationFunction, 0.5, 1, 60);
// Every half-hour for 1 day.
rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 30, 48);
// Every day for 5 years.
rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 1440, 1825);
// Every week for 5 years.
rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 10080, 260);
// Every month for 5 years.
rrdDef.addArchive(ConsolFuns.CF_AVERAGE, 0.5, 43200, 60);
db = new RrdDb(rrdDef);
}
finally {
if(db != null) {
db.close();
}
}
}
}
private String determineDsType(Statistic.Type statType) {
return DsTypes.DT_GAUGE;
}
/**
* Returns the path to the RRD file.
*
* @param datasourceName the name of the data source.
* @return the path to the RRD file.
*/
private String getRrdFilePath(String datasourceName) {
return getStatsDirectroy() + datasourceName + ".rrd";
}
/**
* Returns the directory in which all of the stat databases will be stored.
*
* @return Returns the directory in which all of the stat databases will be stored.
*/
private String getStatsDirectroy() {
return JiveGlobals.getHomeDirectory() + File.separator + MonitoringConstants.NAME
+ File.separator + "stats" + File.separator;
}
private StatDefinition createDefintion(String key) {
StatDefinition def = definitionMap.get(key);
if (def == null) {
Statistic statistic = statsManager.getStatistic(key);
String statGroup = statsManager.getMultistatGroup(key);
try {
def = new DefaultStatDefinition(statGroup != null ? statGroup : key, key, statistic);
// If the definition is a part of a group check to see all defiintions have been
// made for that group
StatDefinition[] definitions;
if (statGroup != null) {
definitions = checkAndCreateGroup(statGroup, def, true);
}
else {
definitions = new StatDefinition[]{def};
multiMap.put(key, Arrays.asList(definitions));
}
if (definitions != null) {
checkDatabase(definitions);
}
definitionMap.put(key, def);
}
catch (RrdException e) {
Log.error("Error creating database definition", e);
}
catch (IOException e) {
Log.error("Error creating database definition", e);
}
}
return def;
}
/**
* Checks to see that all StatDefinitions for a stat group have been created. If they have
* then an array of the StatDefinitions will be returned, if they haven't Null will be returned.
* <p>
* The purpose of this is to know when a database should be initialized, after all the StatDefinitions
* have been created.
*
* @param statGroup The statGroup being checked
* @param def The statdefinition that is being added to the statGroup
* @return Null if the statgroup is completely defined and an array of statdefinitions if it is.
*/
private StatDefinition[] checkAndCreateGroup(String statGroup, StatDefinition def,
boolean shouldCreate)
{
List<StatDefinition> statList = multiMap.get(statGroup);
if (shouldCreate && statList == null) {
statList = new ArrayList<StatDefinition>();
multiMap.put(statGroup, statList);
}
if (statList == null) {
return null;
}
if (shouldCreate) {
statList.add(def);
}
StatDefinition[] definitions;
if (statsManager.getStatGroup(statGroup).size() == statList.size()) {
definitions = statList.toArray(new StatDefinition[statList.size()]);
}
else {
definitions = null;
}
return definitions;
}
/**
* Returns the last minute that passed in seconds since the epoch.
*
* @return the last minute that passed in seconds since the epoch.
*/
private static long getLastMinute() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.SECOND, 0);
return calendar.getTimeInMillis() / 1000;
}
/**
* Returns the definition or definitions related to a statkey. There can be multiple
* definitions if a stat is a multistat.
*
* @param statKey The key for which the definition is desired.
* @return Returns the definition or definitions related to a statkey. There can be multiple
* definitions if a stat is a multistat.
*/
StatDefinition[] getDefinition(String statKey) {
List<StatDefinition> defs = multiMap.get(statKey);
if (defs == null) {
StatDefinition def = definitionMap.get(statKey);
if (def != null) {
return new StatDefinition[] {def};
}
else {
return null;
}
}
else {
return defs.toArray(new StatDefinition[defs.size()]);
}
}
/**
* Returns any multistat group names and any stats that are not part of a multistat.
*
* @return Returns any multistat group names and any stats that are not part of a multistat.
*/
String [] getAllHighLevelNames() {
Set<String> keySet = multiMap.keySet();
return keySet.toArray(new String[keySet.size()]);
}
/**
* The task which samples statistics and persits them to the database.
*
* @author Alexander Wenckus
*/
private class SampleTask extends TimerTask {
private long lastSampleTime = 0;
@Override
public void run() {
if (!ClusterManager.isSeniorClusterMember()) {
// Create statistics definitions but do not sample them since we are not the senior cluster member
for (Map.Entry<String, Statistic> statisticEntry : statsManager.getAllStatistics()) {
String key = statisticEntry.getKey();
StatDefinition def = createDefintion(key);
// Check to see if this stat belongs to a multi-stat and if that multi-stat group
// has been completly defined
String group = statsManager.getMultistatGroup(key);
if (group != null) {
checkAndCreateGroup(group, def, false);
}
}
return;
}
long newTime = getLastMinute();
if (lastSampleTime != 0 && newTime <= lastSampleTime) {
Log.warn("Sample task not run because less then a second has passed since last " +
"sample.");
return;
}
lastSampleTime = newTime;
// Gather sample statistics from remote cluster nodes
Collection<Object> remoteSamples = CacheFactory.doSynchronousClusterTask(new GetStatistics(), false);
List<String> sampledStats = new ArrayList<String>();
for (Map.Entry<String, Statistic> statisticEntry : statsManager.getAllStatistics()) {
String key = statisticEntry.getKey();
StatDefinition def = createDefintion(key);
// Check to see if this stat belongs to a multi-stat and if that multi-stat group
// has been completly defined
String group = statsManager.getMultistatGroup(key);
StatDefinition [] definitions;
if (group != null) {
definitions = checkAndCreateGroup(group, def, false);
if (definitions == null || sampledStats.contains(def.getDatasourceName())) {
continue;
}
}
else {
definitions = new StatDefinition[]{def};
}
RrdDb db = null;
try {
newTime = getLastMinute();
if (def.lastSampleTime <= 0) {
for(StatDefinition definition : definitions) {
definition.lastSampleTime = newTime;
// It is possible that this plugin and thus the StatsEngine didn't
// start when Openfire started so we want to put the stats in a known
// state for proper sampling.
sampleStat(key, definition);
}
continue;
}
db = new RrdDb(def.getDbPath(), false);
// We want to double check the last sample time recorded in the db so as to
// prevent the log files from being inundated if more than one instance of
// Openfire is updating the same database. Also, if there is a task taking a
// long time to complete
if(newTime <= db.getLastArchiveUpdateTime()) {
Log.warn("Sample time of " + newTime + " for statistic " + key + " is " +
"invalid.");
}
Sample sample = db.createSample(newTime);
if (Log.isDebugEnabled()) {
Log.debug("Stat: " + db.getPath() + ". Last sample: " + db.getLastUpdateTime() +
". New sample: " + sample.getTime());
}
for (StatDefinition definition : definitions) {
// Get a statistic sample of this JVM
double statSample = sampleStat(key, definition);
// Add up samples of remote cluster nodes
for (Object nodeResult : remoteSamples) {
Map<String, Double> nodeSamples = (Map<String, Double>) nodeResult;
Double remoteSample = nodeSamples.get(key);
if (remoteSample != null) {
statSample += remoteSample;
}
}
// Update sample with values
sample.setValue(definition.getDatasourceName(), statSample);
sampledStats.add(definition.getDatasourceName());
definition.lastSampleTime = newTime;
definition.lastSample = statSample;
}
sample.update();
}
catch (IOException e) {
Log.error("Error sampling for statistic " + key, e);
}
catch (RrdException e) {
Log.error("Error sampling for statistic " + key, e);
}
finally {
if (db != null) {
try {
db.close();
}
catch (IOException e) {
Log.error("Error releasing db resource", e);
}
}
}
}
}
/**
* Profiles the sampling to make sure that it does not take longer than half a second to
* complete, if it does, a warning is logged.
*
* @param statKey the key related to the statistic.
* @param definition the statistic definition for the stat to be sampled.
* @return the sample.
*/
private double sampleStat(String statKey, StatDefinition definition) {
long start = System.currentTimeMillis();
double sample = definition.getStatistic().sample();
if (System.currentTimeMillis() - start >= 500) {
Log.warn("Stat " + statKey + " took longer than a second to sample.");
}
return sample;
}
}
/**
* Class to process all information retrieved from the stats databases. It also retains
* any meta information related to these databases.
*
* @author Alexander Wenckus
*/
private class DefaultStatDefinition extends StatDefinition {
private String consolidationFunction;
DefaultStatDefinition(String dbPath, String datasourceName, Statistic stat) {
super(dbPath, datasourceName, stat);
this.consolidationFunction = determineConsolidationFun(stat.getStatType());
}
private String determineConsolidationFun(Statistic.Type type) {
switch (type) {
case count:
return ConsolFuns.CF_LAST;
default:
return ConsolFuns.CF_AVERAGE;
}
}
@Override
public double[][] getData(long startTime, long endTime) {
return fetchData(consolidationFunction, startTime, endTime, -1);
}
@Override
public double[][] getData(long startTime, long endTime, int dataPoints) {
// Our greatest datapoints is 60 so if it is something less than that
// then we want an average.
return fetchData((dataPoints != 60 ? ConsolFuns.CF_AVERAGE : consolidationFunction),
startTime, endTime, dataPoints);
}
@Override
public long getLastSampleTime() {
return lastSampleTime;
}
@Override
public double getLastSample() {
return lastSample;
}
@Override
public double[] getMax(long startTime, long endTime) {
return getMax(startTime, endTime, 1);
}
private double discoverMax(double[] doubles) {
double max = 0;
for (double d : doubles) {
if (d > max) {
max = d;
}
}
return max;
}
private double[][] fetchData(String function, long startTime, long endTime, int dataPoints) {
RrdDb db = null;
try {
db = new RrdDb(getDbPath(), true);
FetchData data;
if (dataPoints > 0) {
data = db.createFetchRequest(function, startTime, endTime,
getResolution(startTime, endTime, dataPoints)).fetchData();
}
else {
data = db.createFetchRequest(function, startTime, endTime).fetchData();
}
return data.getValues();
}
catch (IOException e) {
Log.error("Error initializing Rrdb", e);
}
catch (RrdException e) {
Log.error("Error initializing Rrdb", e);
}
finally {
try {
if (db != null) {
db.close();
}
}
catch (IOException e) {
Log.error("Unable to release Rrdb resources",e);
}
}
return null;
}
private long getResolution(long startTime, long endTime, int dataPoints) {
return (endTime - startTime) / (dataPoints * 60);
}
@Override
public double[] getMin(long startTime, long endTime) {
return getMin(startTime, endTime, 1);
}
@Override
public double[] getMin(long startTime, long endTime, int dataPoints) {
double[][] fetchedData = fetchData(consolidationFunction, startTime,
endTime, dataPoints);
if (fetchedData != null) {
double[] toReturn = new double[fetchedData.length];
for (int i = 0; i < fetchedData.length; i++) {
toReturn[i] = discoverMin(fetchedData[i]);
}
return toReturn;
}
return new double[] { 0 };
}
@Override
public double[] getMax(long startTime, long endTime, int dataPoints) {
double[][] fetchedData = fetchData(consolidationFunction, startTime,
endTime, dataPoints);
if (fetchedData != null) {
double[] toReturn = new double[fetchedData.length];
for (int i = 0; i < fetchedData.length; i++) {
toReturn[i] = discoverMax(fetchedData[i]);
}
return toReturn;
}
return new double[] { 0 };
}
private double discoverMin(double[] doubles) {
double min = doubles[0];
for (double d : doubles) {
if (d < min) {
min = d;
}
}
return min;
}
}
}
| |
/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.deprecated;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.List;
public class ImageTest {
private static final ImageId IMAGE_ID = ImageId.of("project", "image");
private static final String GENERATED_ID = "42";
private static final Long CREATION_TIMESTAMP = 1453293540000L;
private static final String DESCRIPTION = "description";
private static final ImageInfo.Status STATUS = ImageInfo.Status.READY;
private static final List<LicenseId> LICENSES = ImmutableList.of(
LicenseId.of("project", "license1"), LicenseId.of("project", "license2"));
private static final Long DISK_SIZE_GB = 42L;
private static final String STORAGE_SOURCE = "source";
private static final Long ARCHIVE_SIZE_BYTES = 24L;
private static final String SHA1_CHECKSUM = "checksum";
private static final DiskId SOURCE_DISK = DiskId.of("project", "zone", "disk");
private static final String SOURCE_DISK_ID = "diskId";
private static final ImageConfiguration.SourceType SOURCE_TYPE =
ImageConfiguration.SourceType.RAW;
private static final StorageImageConfiguration STORAGE_CONFIGURATION =
StorageImageConfiguration.newBuilder(STORAGE_SOURCE)
.setArchiveSizeBytes(ARCHIVE_SIZE_BYTES)
.setContainerType(StorageImageConfiguration.ContainerType.TAR)
.setSha1(SHA1_CHECKSUM)
.setSourceType(SOURCE_TYPE)
.build();
private static final DiskImageConfiguration DISK_CONFIGURATION =
DiskImageConfiguration.newBuilder(SOURCE_DISK)
.setArchiveSizeBytes(ARCHIVE_SIZE_BYTES)
.setSourceDiskId(SOURCE_DISK_ID)
.setSourceType(SOURCE_TYPE)
.build();
private static final DeprecationStatus<ImageId> DEPRECATION_STATUS =
DeprecationStatus.of(DeprecationStatus.Status.DELETED, IMAGE_ID);
private final Compute serviceMockReturnsOptions = createStrictMock(Compute.class);
private final ComputeOptions mockOptions = createMock(ComputeOptions.class);
private Compute compute;
private Image image;
private Image diskImage;
private Image storageImage;
private void initializeExpectedImage(int optionsCalls) {
expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls);
replay(serviceMockReturnsOptions);
diskImage = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, DISK_CONFIGURATION)
.setGeneratedId(GENERATED_ID)
.getCreationTimestamp(CREATION_TIMESTAMP)
.setDescription(DESCRIPTION)
.setStatus(STATUS)
.setDiskSizeGb(DISK_SIZE_GB)
.setLicenses(LICENSES)
.setDeprecationStatus(DEPRECATION_STATUS)
.build();
storageImage = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, STORAGE_CONFIGURATION)
.setGeneratedId(GENERATED_ID)
.getCreationTimestamp(CREATION_TIMESTAMP)
.setDescription(DESCRIPTION)
.setStatus(STATUS)
.setDiskSizeGb(DISK_SIZE_GB)
.setLicenses(LICENSES)
.setDeprecationStatus(DEPRECATION_STATUS)
.build();
compute = createStrictMock(Compute.class);
}
private void initializeImage() {
image = new Image.Builder(compute, IMAGE_ID, DISK_CONFIGURATION)
.setGeneratedId(GENERATED_ID)
.getCreationTimestamp(CREATION_TIMESTAMP)
.setDescription(DESCRIPTION)
.setStatus(STATUS)
.setDiskSizeGb(DISK_SIZE_GB)
.setLicenses(LICENSES)
.setDeprecationStatus(DEPRECATION_STATUS)
.build();
}
@Test
public void testToBuilder() {
initializeExpectedImage(12);
compareImage(diskImage, diskImage.toBuilder().build());
compareImage(storageImage, storageImage.toBuilder().build());
Image newImage = diskImage.toBuilder().setDescription("newDescription").build();
assertEquals("newDescription", newImage.getDescription());
newImage = newImage.toBuilder().setDescription("description").build();
compareImage(diskImage, newImage);
}
@Test
public void testToBuilderIncomplete() {
initializeExpectedImage(6);
ImageInfo imageInfo = ImageInfo.of(IMAGE_ID, DISK_CONFIGURATION);
Image image =
new Image(serviceMockReturnsOptions, new ImageInfo.BuilderImpl(imageInfo));
compareImage(image, image.toBuilder().build());
}
@Test
public void testBuilder() {
initializeExpectedImage(3);
assertEquals(GENERATED_ID, diskImage.getGeneratedId());
assertEquals(IMAGE_ID, diskImage.getImageId());
assertEquals(CREATION_TIMESTAMP, diskImage.getCreationTimestamp());
assertEquals(DESCRIPTION, diskImage.getDescription());
assertEquals(DISK_CONFIGURATION, diskImage.getConfiguration());
assertEquals(STATUS, diskImage.getStatus());
assertEquals(DISK_SIZE_GB, diskImage.getDiskSizeGb());
assertEquals(LICENSES, diskImage.getLicenses());
assertEquals(DEPRECATION_STATUS, diskImage.getDeprecationStatus());
assertSame(serviceMockReturnsOptions, diskImage.getCompute());
assertEquals(GENERATED_ID, storageImage.getGeneratedId());
assertEquals(IMAGE_ID, storageImage.getImageId());
assertEquals(CREATION_TIMESTAMP, storageImage.getCreationTimestamp());
assertEquals(DESCRIPTION, storageImage.getDescription());
assertEquals(STORAGE_CONFIGURATION, storageImage.getConfiguration());
assertEquals(STATUS, storageImage.getStatus());
assertEquals(DISK_SIZE_GB, storageImage.getDiskSizeGb());
assertEquals(LICENSES, storageImage.getLicenses());
assertEquals(DEPRECATION_STATUS, storageImage.getDeprecationStatus());
assertSame(serviceMockReturnsOptions, storageImage.getCompute());
ImageId imageId = ImageId.of("otherImage");
Image image = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, STORAGE_CONFIGURATION)
.setImageId(imageId)
.setConfiguration(DISK_CONFIGURATION)
.build();
assertNull(image.getGeneratedId());
assertEquals(imageId, image.getImageId());
assertNull(image.getCreationTimestamp());
assertNull(image.getDescription());
assertEquals(DISK_CONFIGURATION, image.getConfiguration());
assertNull(image.getStatus());
assertNull(image.getDiskSizeGb());
assertNull(image.getLicenses());
assertNull(image.getDeprecationStatus());
assertSame(serviceMockReturnsOptions, image.getCompute());
}
@Test
public void testToAndFromPb() {
initializeExpectedImage(12);
compareImage(diskImage,
Image.fromPb(serviceMockReturnsOptions, diskImage.toPb()));
compareImage(storageImage,
Image.fromPb(serviceMockReturnsOptions, storageImage.toPb()));
Image image =
new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, DISK_CONFIGURATION).build();
compareImage(image, Image.fromPb(serviceMockReturnsOptions, image.toPb()));
}
@Test
public void testDeleteOperation() {
initializeExpectedImage(3);
expect(compute.getOptions()).andReturn(mockOptions);
Operation operation = new Operation.Builder(serviceMockReturnsOptions)
.setOperationId(GlobalOperationId.of("project", "op"))
.build();
expect(compute.deleteImage(IMAGE_ID)).andReturn(operation);
replay(compute);
initializeImage();
assertSame(operation, image.delete());
}
@Test
public void testDeleteNull() {
initializeExpectedImage(2);
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.deleteImage(IMAGE_ID)).andReturn(null);
replay(compute);
initializeImage();
assertNull(image.delete());
}
@Test
public void testExists_True() throws Exception {
initializeExpectedImage(2);
Compute.ImageOption[] expectedOptions = {Compute.ImageOption.fields()};
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.getImage(IMAGE_ID, expectedOptions)).andReturn(diskImage);
replay(compute);
initializeImage();
assertTrue(image.exists());
verify(compute);
}
@Test
public void testExists_False() throws Exception {
initializeExpectedImage(2);
Compute.ImageOption[] expectedOptions = {Compute.ImageOption.fields()};
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.getImage(IMAGE_ID, expectedOptions)).andReturn(null);
replay(compute);
initializeImage();
assertFalse(image.exists());
verify(compute);
}
@Test
public void testReload() throws Exception {
initializeExpectedImage(5);
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.getImage(IMAGE_ID)).andReturn(storageImage);
replay(compute);
initializeImage();
Image updateImage = image.reload();
compareImage(storageImage, updateImage);
verify(compute);
}
@Test
public void testReloadNull() throws Exception {
initializeExpectedImage(2);
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.getImage(IMAGE_ID)).andReturn(null);
replay(compute);
initializeImage();
assertNull(image.reload());
verify(compute);
}
@Test
public void testReloadWithOptions() throws Exception {
initializeExpectedImage(5);
expect(compute.getOptions()).andReturn(mockOptions);
expect(compute.getImage(IMAGE_ID, Compute.ImageOption.fields())).andReturn(storageImage);
replay(compute);
initializeImage();
Image updateImage = image.reload(Compute.ImageOption.fields());
compareImage(storageImage, updateImage);
verify(compute);
}
@Test
public void testDeprecateImage() {
initializeExpectedImage(3);
expect(compute.getOptions()).andReturn(mockOptions);
Operation operation = new Operation.Builder(serviceMockReturnsOptions)
.setOperationId(GlobalOperationId.of("project", "op"))
.build();
DeprecationStatus<ImageId> status =
DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID);
expect(compute.deprecate(IMAGE_ID, status)).andReturn(operation);
replay(compute);
initializeImage();
assertSame(operation, image.deprecate(status));
}
@Test
public void testDeprecateNull() {
initializeExpectedImage(2);
expect(compute.getOptions()).andReturn(mockOptions);
DeprecationStatus<ImageId> status =
DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID);
expect(compute.deprecate(IMAGE_ID, status)).andReturn(null);
replay(compute);
initializeImage();
assertNull(image.deprecate(status));
}
public void compareImage(Image expected, Image value) {
assertEquals(expected, value);
assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions());
assertEquals(expected.getGeneratedId(), value.getGeneratedId());
assertEquals(expected.getImageId(), value.getImageId());
assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp());
assertEquals(expected.getDescription(), value.getDescription());
assertEquals(expected.getConfiguration(), value.getConfiguration());
assertEquals(expected.getStatus(), value.getStatus());
assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb());
assertEquals(expected.getLicenses(), value.getLicenses());
assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus());
assertEquals(expected.hashCode(), value.hashCode());
}
}
| |
package com.zzn.aeassistant.activity;
import java.io.IOException;
import java.util.Vector;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.zzn.aeassistant.R;
import com.zzn.aeassistant.app.AEApp;
import com.zzn.aeassistant.constants.CodeConstants;
import com.zzn.aeassistant.vo.UserVO;
import com.zzn.aeassistant.zxing.camera.CameraManager;
import com.zzn.aeassistant.zxing.decoding.CaptureActivityHandler;
import com.zzn.aeassistant.zxing.decoding.InactivityTimer;
import com.zzn.aeassistant.zxing.view.ViewfinderView;
@SuppressWarnings("unused")
public class QRScanningActivity extends FragmentActivity implements Callback, OnClickListener {
protected TextView title;
protected ImageButton back;
protected Button save;
private CaptureActivityHandler handler;
private ViewfinderView viewfinderView;
private boolean hasSurface;
private Vector<BarcodeFormat> decodeFormats;
private String characterSet;
private TextView txtResult;
private InactivityTimer inactivityTimer;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private static final float BEEP_VOLUME = 0.10f;
private boolean vibrate;
@Override
protected void onResume() {
super.onResume();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
initCamera(surfaceHolder);
} else {
surfaceHolder.addCallback(this);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
decodeFormats = null;
characterSet = null;
playBeep = true;
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
playBeep = false;
}
initBeepSound();
vibrate = true;
}
@Override
protected void onPause() {
super.onPause();
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
CameraManager.get().closeFlashLight();
CameraManager.get().closeDriver();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
AEApp.getInstance().remove(this);
super.onDestroy();
}
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.get().openDriver(surfaceHolder);
} catch (IOException ioe) {
return;
} catch (RuntimeException e) {
return;
}
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public void openFlashLight() {
CameraManager.get().openFlashLight();
}
public void closeFlashLight() {
CameraManager.get().closeFlashLight();
}
public boolean isFlashLightOn() {
return CameraManager.get().isFlashlightOn();
}
public boolean isSupportFlashLight() {
PackageManager pm = getPackageManager();
FeatureInfo[] fis = pm.getSystemAvailableFeatures();
for (FeatureInfo fi : fis) {
if (PackageManager.FEATURE_CAMERA_FLASH.equals(fi.name))
return true;
}
return false;
}
public Handler getHandler() {
return handler;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
public void handleDecode(Result obj, Bitmap barcode) {
inactivityTimer.onActivity();
// viewfinderView.drawResultBitmap(barcode);
playBeepSoundAndVibrate();
// txtResult.setText(obj.getBarcodeFormat().toString() + ":"
// + obj.getText());
onHandleDecode(obj.getText(), obj.getBarcodeFormat().toString());
this.finish();
}
protected void onHandleDecode(String result, String format) {
Intent intent = new Intent();
intent.putExtra(CodeConstants.KEY_SCAN_RESULT, result);
intent.putExtra(CodeConstants.KEY_SCAN_RESULT_FORMAT, format);
this.setResult(RESULT_OK, intent);
}
private void initBeepSound() {
if (playBeep && mediaPlayer == null) {
// The volume on STREAM_SYSTEM is not adjustable, and users found it
// too loud,
// so we now play on the music stream.
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(beepListener);
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer = null;
}
}
}
private static final long VIBRATE_DURATION = 200L;
private void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
/**
* When the beep has finished playing, rewind to queue up another one.
*/
private final OnCompletionListener beepListener = new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
};
protected int titleStringID() {
return R.string.qrcode_scanning;
}
protected int layoutResID() {
return R.layout.activity_qr_scanning;
}
protected void initView() {
CameraManager.init(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
txtResult = (TextView) findViewById(R.id.txtResult);
hasSurface = false;
inactivityTimer = new InactivityTimer(this);
int topOffset = Math.round(getResources().getDimension(R.dimen.title_bar_height));
CameraManager.get().setFramingOffsetRect(0, -topOffset, 0, -topOffset);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AEApp.getInstance().add(this);
if (savedInstanceState != null
&& savedInstanceState.getSerializable("user") != null
&& savedInstanceState.getSerializable("user") instanceof UserVO) {
AEApp.setUser((UserVO) savedInstanceState.getSerializable("user"));
}
// checkUser();
setContentView(layoutResID());
title = (TextView) findViewById(R.id.title);
if (title != null) {
title.setText(titleStringID());
}
back = (ImageButton) findViewById(R.id.back);
if (back != null) {
back.setOnClickListener(this);
}
save = (Button) findViewById(R.id.save);
if (save != null) {
save.setOnClickListener(this);
}
initView();
}
private long lastClickTime = 0;
@Override
public void onClick(View v) {
if (System.currentTimeMillis() - lastClickTime < 500) {
return;
}
lastClickTime = System.currentTimeMillis();
switch (v.getId()) {
case R.id.back:
onBackClick();
break;
case R.id.save:
onSaveClick();
break;
default:
break;
}
}
protected void onSaveClick() {
}
protected void onBackClick() {
finish();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.FailbackRegistry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import static java.util.Collections.singleton;
import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY;
import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY;
import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL;
import static org.apache.dubbo.registry.nacos.NacosServiceName.valueOf;
/**
* Nacos {@link Registry}
*
* @see #SERVICE_NAME_SEPARATOR
* @see #PAGINATION_SIZE
* @see #LOOKUP_INTERVAL
* @since 2.6.5
*/
public class NacosRegistry extends FailbackRegistry {
/**
* All supported categories
*/
private static final List<String> ALL_SUPPORTED_CATEGORIES = Arrays.asList(
PROVIDERS_CATEGORY,
CONSUMERS_CATEGORY,
ROUTERS_CATEGORY,
CONFIGURATORS_CATEGORY
);
private static final int CATEGORY_INDEX = 0;
private static final int SERVICE_INTERFACE_INDEX = 1;
private static final int SERVICE_VERSION_INDEX = 2;
private static final int SERVICE_GROUP_INDEX = 3;
private static final String WILDCARD = "*";
/**
* The separator for service name
* Change a constant to be configurable, it's designed for Windows file name that is compatible with old
* Nacos binary release(< 0.6.1)
*/
private static final String SERVICE_NAME_SEPARATOR = System.getProperty("nacos.service.name.separator", ":");
/**
* The pagination size of query for Nacos service names(only for Dubbo-OPS)
*/
private static final int PAGINATION_SIZE = Integer.getInteger("nacos.service.names.pagination.size", 100);
/**
* The interval in second of lookup Nacos service names(only for Dubbo-OPS)
*/
private static final long LOOKUP_INTERVAL = Long.getLong("nacos.service.names.lookup.interval", 30);
/**
* {@link ScheduledExecutorService} lookup Nacos service names(only for Dubbo-OPS)
*/
private volatile ScheduledExecutorService scheduledExecutorService;
private final Logger logger = LoggerFactory.getLogger(getClass());
private final NamingService namingService;
private final ConcurrentMap<String, EventListener> nacosListeners;
public NacosRegistry(URL url, NamingService namingService) {
super(url);
this.namingService = namingService;
this.nacosListeners = new ConcurrentHashMap<>();
}
@Override
public boolean isAvailable() {
return "UP".equals(namingService.getServerStatus());
}
@Override
public List<URL> lookup(final URL url) {
final List<URL> urls = new LinkedList<>();
execute(namingService -> {
Set<String> serviceNames = getServiceNames(url, null);
for (String serviceName : serviceNames) {
List<Instance> instances = namingService.getAllInstances(serviceName);
urls.addAll(buildURLs(url, instances));
}
});
return urls;
}
@Override
public void doRegister(URL url) {
final String serviceName = getServiceName(url);
final Instance instance = createInstance(url);
execute(namingService -> namingService.registerInstance(serviceName, instance));
}
@Override
public void doUnregister(final URL url) {
execute(namingService -> {
String serviceName = getServiceName(url);
Instance instance = createInstance(url);
namingService.deregisterInstance(serviceName, instance.getIp(), instance.getPort());
});
}
@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
Set<String> serviceNames = getServiceNames(url, listener);
doSubscribe(url, listener, serviceNames);
}
private void doSubscribe(final URL url, final NotifyListener listener, final Set<String> serviceNames) {
execute(namingService -> {
for (String serviceName : serviceNames) {
List<Instance> instances = namingService.getAllInstances(serviceName);
notifySubscriber(url, listener, instances);
subscribeEventListener(serviceName, url, listener);
}
});
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
if (isAdminProtocol(url)) {
shutdownServiceNamesLookup();
}
}
private void shutdownServiceNamesLookup() {
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdown();
}
}
/**
* Get the service names from the specified {@link URL url}
*
* @param url {@link URL}
* @param listener {@link NotifyListener}
* @return non-null
*/
private Set<String> getServiceNames(URL url, NotifyListener listener) {
if (isAdminProtocol(url)) {
scheduleServiceNamesLookup(url, listener);
return getServiceNamesForOps(url);
} else {
return getServiceNames0(url);
}
}
private Set<String> getServiceNames0(URL url) {
NacosServiceName serviceName = createServiceName(url);
final Set<String> serviceNames;
if (serviceName.isConcrete()) { // is the concrete service name
serviceNames = singleton(serviceName.toString());
} else {
serviceNames = filterServiceNames(serviceName);
}
return serviceNames;
}
private Set<String> filterServiceNames(NacosServiceName serviceName) {
Set<String> serviceNames = new LinkedHashSet<>();
execute(namingService -> {
serviceNames.addAll(namingService.getServicesOfServer(1, Integer.MAX_VALUE).getData()
.stream()
.map(NacosServiceName::new)
.filter(serviceName::isCompatible)
.map(NacosServiceName::toString)
.collect(Collectors.toList()));
});
return serviceNames;
}
private boolean isAdminProtocol(URL url) {
return ADMIN_PROTOCOL.equals(url.getProtocol());
}
private void scheduleServiceNamesLookup(final URL url, final NotifyListener listener) {
if (scheduledExecutorService == null) {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(() -> {
Set<String> serviceNames = getAllServiceNames();
filterData(serviceNames, serviceName -> {
boolean accepted = false;
for (String category : ALL_SUPPORTED_CATEGORIES) {
String prefix = category + SERVICE_NAME_SEPARATOR;
if (serviceName != null && serviceName.startsWith(prefix)) {
accepted = true;
break;
}
}
return accepted;
});
doSubscribe(url, listener, serviceNames);
}, LOOKUP_INTERVAL, LOOKUP_INTERVAL, TimeUnit.SECONDS);
}
}
/**
* Get the service names for Dubbo OPS
*
* @param url {@link URL}
* @return non-null
*/
private Set<String> getServiceNamesForOps(URL url) {
Set<String> serviceNames = getAllServiceNames();
filterServiceNames(serviceNames, url);
return serviceNames;
}
private Set<String> getAllServiceNames() {
final Set<String> serviceNames = new LinkedHashSet<>();
execute(namingService -> {
int pageIndex = 1;
ListView<String> listView = namingService.getServicesOfServer(pageIndex, PAGINATION_SIZE);
// First page data
List<String> firstPageData = listView.getData();
// Append first page into list
serviceNames.addAll(firstPageData);
// the total count
int count = listView.getCount();
// the number of pages
int pageNumbers = count / PAGINATION_SIZE;
int remainder = count % PAGINATION_SIZE;
// remain
if (remainder > 0) {
pageNumbers += 1;
}
// If more than 1 page
while (pageIndex < pageNumbers) {
listView = namingService.getServicesOfServer(++pageIndex, PAGINATION_SIZE);
serviceNames.addAll(listView.getData());
}
});
return serviceNames;
}
private void filterServiceNames(Set<String> serviceNames, URL url) {
final List<String> categories = getCategories(url);
final String targetServiceInterface = url.getServiceInterface();
final String targetVersion = url.getParameter(VERSION_KEY, "");
final String targetGroup = url.getParameter(GROUP_KEY, "");
filterData(serviceNames, serviceName -> {
// split service name to segments
// (required) segments[0] = category
// (required) segments[1] = serviceInterface
// (optional) segments[2] = version
// (optional) segments[3] = group
String[] segments = serviceName.split(SERVICE_NAME_SEPARATOR, -1);
int length = segments.length;
if (length != 4) { // must present 4 segments
return false;
}
String category = segments[CATEGORY_INDEX];
if (!categories.contains(category)) { // no match category
return false;
}
String serviceInterface = segments[SERVICE_INTERFACE_INDEX];
// no match service interface
if (!WILDCARD.equals(targetServiceInterface) &&
!StringUtils.isEquals(targetServiceInterface, serviceInterface)) {
return false;
}
// no match service version
String version = segments[SERVICE_VERSION_INDEX];
if (!WILDCARD.equals(targetVersion) && !StringUtils.isEquals(targetVersion, version)) {
return false;
}
String group = segments[SERVICE_GROUP_INDEX];
return group == null || WILDCARD.equals(targetGroup) || StringUtils.isEquals(targetGroup, group);
});
}
private <T> void filterData(Collection<T> collection, NacosDataFilter<T> filter) {
// remove if not accept
collection.removeIf(data -> !filter.accept(data));
}
@Deprecated
private List<String> doGetServiceNames(URL url) {
List<String> categories = getCategories(url);
List<String> serviceNames = new ArrayList<>(categories.size());
for (String category : categories) {
final String serviceName = getServiceName(url, category);
serviceNames.add(serviceName);
}
return serviceNames;
}
private List<URL> toUrlWithEmpty(URL consumerURL, Collection<Instance> instances) {
List<URL> urls = buildURLs(consumerURL, instances);
if (urls.size() == 0) {
URL empty = URLBuilder.from(consumerURL)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, DEFAULT_CATEGORY)
.build();
urls.add(empty);
}
return urls;
}
private List<URL> buildURLs(URL consumerURL, Collection<Instance> instances) {
List<URL> urls = new LinkedList<>();
if (instances != null && !instances.isEmpty()) {
for (Instance instance : instances) {
URL url = buildURL(instance);
if (UrlUtils.isMatch(consumerURL, url)) {
urls.add(url);
}
}
}
return urls;
}
private void subscribeEventListener(String serviceName, final URL url, final NotifyListener listener)
throws NacosException {
if (!nacosListeners.containsKey(serviceName)) {
EventListener eventListener = event -> {
if (event instanceof NamingEvent) {
NamingEvent e = (NamingEvent) event;
notifySubscriber(url, listener, e.getInstances());
}
};
namingService.subscribe(serviceName, eventListener);
nacosListeners.put(serviceName, eventListener);
}
}
/**
* Notify the Healthy {@link Instance instances} to subscriber.
*
* @param url {@link URL}
* @param listener {@link NotifyListener}
* @param instances all {@link Instance instances}
*/
private void notifySubscriber(URL url, NotifyListener listener, Collection<Instance> instances) {
List<Instance> healthyInstances = new LinkedList<>(instances);
if (healthyInstances.size() > 0) {
// Healthy Instances
filterHealthyInstances(healthyInstances);
}
List<URL> urls = toUrlWithEmpty(url, healthyInstances);
NacosRegistry.this.notify(url, listener, urls);
}
/**
* Get the categories from {@link URL}
*
* @param url {@link URL}
* @return non-null array
*/
private List<String> getCategories(URL url) {
return ANY_VALUE.equals(url.getServiceInterface()) ?
ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY);
}
private URL buildURL(Instance instance) {
Map<String, String> metadata = instance.getMetadata();
String protocol = metadata.get(PROTOCOL_KEY);
String path = metadata.get(PATH_KEY);
return new URL(protocol,
instance.getIp(),
instance.getPort(),
path,
instance.getMetadata());
}
private Instance createInstance(URL url) {
// Append default category if absent
String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
URL newURL = url.addParameter(CATEGORY_KEY, category);
newURL = newURL.addParameter(PROTOCOL_KEY, url.getProtocol());
newURL = newURL.addParameter(PATH_KEY, url.getPath());
String ip = url.getHost();
int port = url.getPort();
Instance instance = new Instance();
instance.setIp(ip);
instance.setPort(port);
instance.setMetadata(new HashMap<>(newURL.getParameters()));
return instance;
}
private NacosServiceName createServiceName(URL url) {
return valueOf(url);
}
private String getServiceName(URL url) {
return getServiceName(url, url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY));
}
private String getServiceName(URL url, String category) {
return category + SERVICE_NAME_SEPARATOR + url.getColonSeparatedKey();
}
private void execute(NamingServiceCallback callback) {
try {
callback.callback(namingService);
} catch (NacosException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getErrMsg(), e);
}
}
}
private void filterHealthyInstances(Collection<Instance> instances) {
filterData(instances, Instance::isEnabled);
}
/**
* A filter for Nacos data
*
* @since 2.6.5
*/
private interface NacosDataFilter<T> {
/**
* Tests whether or not the specified data should be accepted.
*
* @param data The data to be tested
* @return <code>true</code> if and only if <code>data</code>
* should be accepted
*/
boolean accept(T data);
}
/**
* {@link NamingService} Callback
*
* @since 2.6.5
*/
interface NamingServiceCallback {
/**
* Callback
*
* @param namingService {@link NamingService}
* @throws NacosException
*/
void callback(NamingService namingService) throws NacosException;
}
}
| |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class IC1 {
String[] keywords = { "auto", "break", "case", "char", "const", "continue",
"default", "do", "double", "else", "enum", "extern", "float",
"for", "goto", "if", "int", "include", "long", "main", "register",
"return", "short", "signed", "sizeof", "static", "struct",
"switch", "typedef", "union", "unsigned", "void", "volatile",
"while" };
String[] ariOp = { "+", "-", "*", "/" };
String[] relOp = { "!", ">", "==", "<", "!=", "<=", ">=" };
FileReader fr = null;
BufferedReader br = null;
FileReader fr1;
BufferedReader br1;
static String value = null;
int j = 0, length = 0, k = 0, l = 0, stacktop = 0, index = 0;
String parTable[][] = new String[36][22];
String productions[] = { "", "S -> A S", "S -> I S", "S -> A", "S -> I",
"A -> id = E ;", "I -> while ( C ) { S }", "C -> id relop id",
"E -> E + T", "E -> E - T", "E -> T", "T -> T * F", "T -> T / F",
"T -> F", "F -> ( E )", "F -> id" };
String[] ic_reduce = { "na", "na", "na", "na", "na", "=", "na", "r", "+",
"-", "na", "*", "/", "na", "na", "na" };
String terNonter[] = { "id", ";", "=", "{", "}", "(", ")", "relop",
"while", "+", "-", "*", "/", "$", "S", "A", "I", "C", "E", "T", "F" };
static int readOneLine = 0;
int goInLoop = 0, readLastChar = 0,cunt=0;
Stack st = new Stack();
Stack symbol = new Stack();
static Stack inputString = new Stack();
static Stack valueStack = new Stack();
public static void main(String[] args) throws IOException {
String str = null, strng = null, str1 = null, line = null, line1 = null, splitLine[] = null;
int j = 0, k = 0;
IC1 sy = new IC1();
// reading input file
FileReader fr = new FileReader("Input1.txt");
BufferedReader br = new BufferedReader(fr);
FileReader fr2 = new FileReader("Input1.txt");
BufferedReader br2 = new BufferedReader(fr2);
// reading parsing table
FileReader fr1 = new FileReader("Parse.csv");
BufferedReader br1 = new BufferedReader(fr1);
line = br1.readLine();
// loading parse table in an array
j = 0;
while ((line = br1.readLine()) != null) {
splitLine = line.split(",");
k = 0;
for (int i = 1; i < splitLine.length; i++) {
sy.parTable[j][k] = splitLine[i];
k++;
}
j++;
}
for (int g = 0; g < sy.parTable.length; g++) {
//System.out.print(g + "\t");
for (int h = 0; h < splitLine.length; h++) {
// System.out.print(sy.parTable[g][h] + "\t");
}
//System.out.println();
}
System.out.println("\nCode Gen\n");
sy.st.push("0");
inputString.push("$");
sy.value = "started";
// System.out.print("\n\nStack\tSymbol\tInput String\tAction\n");
// System.out.print(Arrays.toString(sy.st.toArray()) + "\t");
// System.out.print(Arrays.toString(sy.symbol.toArray()) + "\t");
// System.out.print(Arrays.toString(inputString.toArray()) + "\t");
// execute token wise
strng = br2.readLine();
// str = br.readLine();
while ((str = br.readLine()) != null) {
if ((br2.readLine() == null)) {
readOneLine = 1;
}
String token = sy.lex(str);
}
if (value.equals("ACCEPT")) {
System.out.println("STRING ACCEPTED");
} else {
System.out.println("STRING REJECTED");
}
}
public String lex(String str) throws IOException {
// System.out.println("in lex function");
String str1 = null, array[];
if (str.trim().length() > 0) {
// remove extra spaces
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while (st.hasMoreElements()) {
sb.append(st.nextElement()).append(" ");
}
str = sb.toString().trim();
// remove tabs or new line
str = str.replaceAll("\t", "");
str1 = str.replaceAll("\n", "");
// check for single line comment
if (str1.contains("//")) {
// System.out.println("\n" + str1);
// System.out.println("\nSingle line comment");
int ind = str1.indexOf("//");
str1 = str1.substring(0, ind);
// System.out.println("New String " + str1);
}
// check for multiple line comment
if (str1.contains("/*")) {
// System.out.println("\nMultiple line comment");
// System.out.println(str1);
str1 = str1.substring(str1.indexOf("/*"), str1.length());
while (!str1.contains("*/")) {
str1 = br.readLine();
// System.out.println(str1);
str1.replaceAll(str1, "");
}
int a = str1.indexOf("*/");
str1 = str1.substring(a + 2, str1.length());
}
// split with spaces
array = str1.split(" ");
// System.out.println("\n" + str1 + "\n");
// readOneLine=0;
for (int i = 0; i < array.length; i++) {
if ((i == (array.length - 1)) && (readOneLine == 1)) {
readLastChar = 1;
}
if (checkKeyword(array[i])) {
// System.out.println("Keyword : " + array[i]);
syntax(array[i], array[i]);
} else if (checkAriOperator(array[i])) {
// System.out.println("Arithmatic operator : " + array[i]);
syntax(array[i], array[i]);
} else if (checkRelOp(array[i])) {
// System.out.println("Relational operator : " + array[i]);
syntax("relop", array[i]);
} else if (array[i].equals("=")) {
// System.out.println("Assignment Operator : " + array[i]);
syntax(array[i], array[i]);
} else if ((array[i].equals("{")) || (array[i].equals("}"))
|| (array[i].equals("(")) || (array[i].equals(")"))) {
// System.out.println("Brackets : " + array[i]);
syntax(array[i], array[i]);
} else if ((array[i].equals("||")) || (array[i].equals("&&"))) {
// System.out.println("Logical Operators : " + array[i]);
syntax(array[i], array[i]);
} else if ((array[i].equals(";")) || (array[i].equals(","))) {
// System.out.println("Delimitor : " + array[i]);
syntax(array[i], array[i]);
} else if (!Character.isDigit(array[i].charAt(0))) {
// System.out.println("Identifier : " + array[i]);
syntax("id", array[i]);
} else if (checkNumber(array[i])) {
// System.out.println("Integer Number : " + array[i]);
syntax(array[i], array[i]);
} else if (checkNumber1(array[i])) {
// System.out.println("Float Number : " + array[i]);
syntax(array[i], array[i]);
} else {
// System.out.println("Invalid identifier!!!!! : " + array[i]);
}
}
// System.out.println("Read one line and readOneLine = "
// + readOneLine);
readOneLine = 1;
}
return (null);
}
public void syntax(String token, String token1) {
String value1=null,value2=null,value3=null;
inputString.push(token);
System.out.print(Arrays.toString(inputString.toArray()));
int i = 0;
while (((!inputString.peek().equals("$")) || (goInLoop == 1) || (readLastChar == 1)
&& (!((value.equals("ACCEPT")) || (value.equals("null")))))
&& i < 100) {
String input = (String) inputString.peek();
for (k = 0; k < terNonter.length; k++) {
if (input.equals(terNonter[k])) {
index = k;
break;
}
}
String top = (String) st.peek();
stacktop = Integer.parseInt(top);
// get value from table
value = parTable[stacktop][index];
// System.out.println(" value is " + value + " stacktop " +
// stacktop
// + " input is " + input);
if (!((value.equals("ACCEPT")) || (value.equals("null")))) {
if (value.startsWith("S")) {
// System.out.print("\nShift operation -> read " + value);
// System.out.println("\n");
if (value.length() == 2)
value = value.substring(1, 2);
else
value = value.substring(1, 3);
st.push(value);
symbol.push(input);
inputString.pop();
if (token == "id" || token == "relop") {
valueStack.push(token1);
}
} else if (value.startsWith("R")) {
// System.out.print("Reduce operation -> read " + value);
if (value.length() == 2)
value = value.substring(1, 2);
else
value = value.substring(1, 3);
int num = Integer.parseInt(value);
String reductn = ic_reduce[num];
System.out.println(Arrays.toString(valueStack.toArray()) + "\t");
switch (reductn) {
case "na":
break;
case "+":
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\nt" + (cunt++) + "= " + value1+ " + " + value2 + "\n");
valueStack.push("t" + (cunt - 1));
System.out.print(Arrays.toString(valueStack.toArray()) + "\t");
break;
case "-":
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\nt" + (cunt++) + "= " + value1+ " - " + value2 + "\n");
valueStack.push("t" + (cunt - 1));
System.out.print( Arrays.toString(valueStack.toArray()) + "\t");
break;
case "*":
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\nt" + (cunt++) + "= " + value1+ " * " + value2 + "\n");
valueStack.push("t" + (cunt - 1));
System.out.print(Arrays.toString(valueStack.toArray()) + "\t");
break;
case "/":
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\nt" + (cunt++) + "= " + value1+ " / " + value2 + "\n");
valueStack.push("t" + (cunt - 1));
System.out.print(Arrays.toString(valueStack.toArray()) + "\t");
break;
case "=":
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\n"+value1+ " = " + value2 + "\n");
//valueStack.push("t" + (cunt - 1));
System.out.print(Arrays.toString(valueStack.toArray()) + "\t");
valueStack.empty();
break;
case "relop":
value3 = "" + valueStack.pop();
value2 = "" + valueStack.pop();
value1 = "" + valueStack.pop();
System.out.println("\nt" + (cunt++) + "= " + value1 + value2 + value3 + "\n");
valueStack.push("t"+(cunt));
System.out.print(Arrays.toString(valueStack.toArray()) + "\t");
break;
}
String prod = productions[num];
String rhs = prod.substring(5, prod.length());
String[] rhsArr = rhs.split(" ");
prod = prod.substring(0, 1);
// System.out
// .println(" " + symbol.peek() + " reduced to " + prod);
// System.out.println("\n");
for (int o = 0; o < rhsArr.length; o++) {
// System.out.println(rhsArr[o]);
st.pop();
}
symbol.pop();
symbol.push(prod);
// checking after reduce and non terminal
// String symtop = (String) symbol.peek();
for (k = 0; k < terNonter.length; k++) {
if (prod.equals(terNonter[k])) {
index = k;
break;
}
}
top = (String) st.peek();
stacktop = Integer.parseInt(top);
value = parTable[stacktop][index];
st.push(value);
// System.out.println("\n\nafter reduce\n");
// System.out.println("stck : "+stacktop);
// System.out.println("input : "+ input);
// System.out.println("symbol : "+symbol.peek()
// +"uska index "+index);
// System.out.println("value[stack][input] "+value
// +" that is pushed to stack");
} else {
st.push(value);
symbol.push(input);
inputString.pop();
}
// System.out.print("\n\n" + Arrays.toString(st.toArray()) + "\t");
// System.out.print(Arrays.toString(symbol.toArray()) + "\t");
// System.out.print(Arrays.toString(inputString.toArray()) + "\t");
// System.out.println("\n");
}
if ((inputString.peek().equals("$")) && (readOneLine == 1)) {
goInLoop = 1;
}
i++;
}
}
public boolean checkNumber(String str) {
try {
int e = Integer.parseInt(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public boolean checkNumber1(String str) {
try {
float w = Float.parseFloat(str);
} catch (NumberFormatException e) {
return false;
}
return true;
}
public boolean checkKeyword(String str) {
boolean res = false;
for (int k = 0; k < keywords.length; k++) {
if (str.equals(keywords[k])) {
res = true;
break;
}
}
return res;
}
public boolean checkAriOperator(String str) {
boolean res = false;
for (int k = 0; k < ariOp.length; k++) {
if (str.equals(ariOp[k])) {
res = true;
break;
}
}
return res;
}
public boolean checkRelOp(String str) {
boolean res = false;
for (int k = 0; k < relOp.length; k++) {
if (str.equals(relOp[k])) {
res = true;
break;
}
}
return res;
}
}
| |
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.common;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.drools.FactException;
import org.drools.core.util.LinkedList;
import org.drools.core.util.LinkedListEntry;
import org.drools.core.util.ObjectHashMap;
import org.drools.impl.StatefulKnowledgeSessionImpl;
import org.drools.marshalling.impl.MarshallerReaderContext;
import org.drools.marshalling.impl.MarshallerWriteContext;
import org.drools.marshalling.impl.PersisterHelper;
import org.drools.marshalling.impl.ProtobufMessages;
import org.drools.marshalling.impl.ProtobufMessages.ActionQueue.Action;
import org.drools.marshalling.impl.ProtobufMessages.ActionQueue.LogicalRetract;
import org.drools.rule.Rule;
import org.drools.spi.Activation;
import org.drools.spi.PropagationContext;
/**
* The Truth Maintenance System is responsible for tracking two things. Firstly
* It maintains a Map to track the classes with the same Equality, using the
* EqualityKey. The EqualityKey has an internal datastructure which references
* all the handles which are equal. Secondly It maintains another map tracking
* the justificiations for logically asserted facts.
*/
public class TruthMaintenanceSystem {
private AbstractWorkingMemory workingMemory;
private ObjectHashMap justifiedMap;
private ObjectHashMap assertMap;
public TruthMaintenanceSystem() {
}
public TruthMaintenanceSystem(final AbstractWorkingMemory workingMemory) {
this.workingMemory = workingMemory;
this.justifiedMap = new ObjectHashMap();
this.assertMap = new ObjectHashMap();
this.assertMap.setComparator( EqualityKeyComparator.getInstance() );
}
// public void write(WMSerialisationOutContext context) throws IOException {
// ObjectOutputStream stream = context.stream;
//
// EqualityKey[] keys = new EqualityKey[ this.assertMap.size() ];
// org.drools.util.Iterator it = this.assertMap.iterator();
// int i = 0;
// for ( ObjectEntry entry = ( ObjectEntry ) it.next(); entry != null; entry = ( ObjectEntry ) it.next() ) {
// EqualityKey key = ( EqualityKey ) entry.getKey();
// keys[i++] = key;
// }
//
// Arrays.sort( keys, EqualityKeySorter.instance );
//
// // write the assert map of Equality keys
// for ( EqualityKey key : keys ) {
// stream.writeInt( PersisterEnums.EQUALITY_KEY );
// stream.writeInt( key.getStatus() );
// InternalFactHandle handle = key.getFactHandle();
// stream.writeInt( handle.getId() );
// context.out.println( "EqualityKey int:" + key.getStatus() + " int:" + handle.getId() );
// if ( key.getOtherFactHandle() != null && !key.getOtherFactHandle().isEmpty() ) {
// for ( InternalFactHandle handle2 : key.getOtherFactHandle() ) {
// stream.writeInt( PersisterEnums.FACT_HANDLE );
// stream.writeInt( handle2.getId() );
// context.out.println( "OtherHandle int:" + handle2.getId() );
// }
// }
// stream.writeInt( PersisterEnums.END );
// }
// stream.writeInt( PersisterEnums.END );
// }
//
// public static class EqualityKeySorter implements Comparator<EqualityKey> {
// public static final EqualityKeySorter instance = new EqualityKeySorter();
// public int compare(EqualityKey key1,
// EqualityKey key2) {
// return key1.getFactHandle().getId() - key2.getFactHandle().getId();
// }
// }
//
// public void read(WMSerialisationInContext context) throws IOException {
// ObjectInputStream stream = context.stream;
//
// while ( stream.readInt() == PersisterEnums.EQUALITY_KEY ) {
// int status = stream.readInt();
// InternalFactHandle handle = ( InternalFactHandle ) context.handles.get( stream.readInt() );
// EqualityKey key = new EqualityKey(handle, status);
// handle.setEqualityKey( key );
// while ( stream.readInt() == PersisterEnums.FACT_HANDLE ) {
// handle = ( InternalFactHandle ) context.wm.getFactHandle( stream.readInt() );
// key.addFactHandle( handle );
// handle.setEqualityKey( key );
// }
// put( key );
// }
// }
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// workingMemory = (AbstractWorkingMemory)in.readObject();
// justifiedMap = (PrimitiveLongMap)in.readObject();
// assertMap = (ObjectHashMap)in.readObject();
// }
//
// public void writeExternal(ObjectOutput out) throws IOException {
// out.writeObject(workingMemory);
// out.writeObject(justifiedMap);
// out.writeObject(assertMap);
// }
public ObjectHashMap getJustifiedMap() {
return this.justifiedMap;
}
public ObjectHashMap getAssertMap() {
return this.assertMap;
}
public Object put(final EqualityKey key) {
return this.assertMap.put( key,
key,
false );
}
public EqualityKey get(final EqualityKey key) {
return (EqualityKey) this.assertMap.get( key );
}
public EqualityKey get(final Object object) {
return (EqualityKey) this.assertMap.get( object );
}
public EqualityKey remove(final EqualityKey key) {
return (EqualityKey) this.assertMap.remove( key );
}
/**
* An Activation is no longer true so it no longer justifies any of the logical facts
* it logically asserted. It iterates over the Activation's LinkedList of DependencyNodes
* it retrieves the justitication set for each DependencyNode's FactHandle and removes
* itself. If the Set is empty it retracts the FactHandle from the WorkingMemory.
*
* @param activation
* @param context
* @param rule
* @throws FactException
*/
public void removeLogicalDependencies(final Activation activation,
final PropagationContext context,
final Rule rule) throws FactException {
final org.drools.core.util.LinkedList list = activation.getLogicalDependencies();
if ( list == null || list.isEmpty() ) {
return;
}
for ( LogicalDependency node = (LogicalDependency) list.getFirst(); node != null; node = (LogicalDependency) node.getNext() ) {
removeLogicalDependency( activation, node, context );
}
}
public void removeLogicalDependency(final Activation activation,
final LogicalDependency node,
final PropagationContext context) {
final InternalFactHandle handle = (InternalFactHandle) node.getJustified();
final LinkedList list = (LinkedList) this.justifiedMap.get( handle.getId() );
if ( list != null ) {
list.remove( node.getJustifierEntry() );
WorkingMemoryAction action = new LogicalRetractCallback( this,
node,
list,
handle,
context,
activation );
workingMemory.queueWorkingMemoryAction( action );
}
}
public static class LogicalRetractCallback
implements
WorkingMemoryAction {
private TruthMaintenanceSystem tms;
private LogicalDependency node;
private LinkedList list;
private InternalFactHandle handle;
private PropagationContext context;
private Activation activation;
public LogicalRetractCallback() {
}
public LogicalRetractCallback(final TruthMaintenanceSystem tms,
final LogicalDependency node,
final LinkedList list,
final InternalFactHandle handle,
final PropagationContext context,
final Activation activation) {
this.tms = tms;
this.node = node;
this.list = list;
this.handle = handle;
this.context = context;
}
public LogicalRetractCallback(MarshallerReaderContext context) throws IOException {
this.tms = context.wm.getTruthMaintenanceSystem();
this.handle = context.handles.get( context.readInt() );
this.context = context.propagationContexts.get( context.readLong() );
this.activation = (Activation) context.terminalTupleMap.get( context.readInt() ).getObject();
this.list = ( LinkedList ) this.tms.getJustifiedMap().get( handle.getId() );
for ( LinkedListEntry entry = (LinkedListEntry) list.getFirst(); entry != null; entry = (LinkedListEntry) entry.getNext() ) {
final LogicalDependency node = (LogicalDependency) entry.getObject();
if ( node.getJustifier() == this.activation ) {
this.node = node;
break;
}
}
}
public LogicalRetractCallback(MarshallerReaderContext context,
Action _action) {
LogicalRetract _retract = _action.getLogicalRetract();
this.tms = context.wm.getTruthMaintenanceSystem();
this.handle = context.handles.get( _retract.getHandleId() );
this.activation = (Activation) context.filter.getTuplesCache().get(
PersisterHelper.createActivationKey( _retract.getActivation().getPackageName(),
_retract.getActivation().getRuleName(),
_retract.getActivation().getTuple() ) ).getObject();
this.context = this.activation.getPropagationContext();
this.list = ( LinkedList ) this.tms.getJustifiedMap().get( handle.getId() );
for ( LinkedListEntry entry = (LinkedListEntry) list.getFirst(); entry != null; entry = (LinkedListEntry) entry.getNext() ) {
final LogicalDependency node = (LogicalDependency) entry.getObject();
if ( node.getJustifier() == this.activation ) {
this.node = node;
break;
}
}
}
public void write(MarshallerWriteContext context) throws IOException {
context.writeShort( WorkingMemoryAction.LogicalRetractCallback );
context.writeInt( this.handle.getId() );
context.writeLong( this.context.getPropagationNumber() );
context.writeInt( context.terminalTupleMap.get( this.activation.getTuple() ) );
}
public ProtobufMessages.ActionQueue.Action serialize(MarshallerWriteContext context) {
LogicalRetract _retract = ProtobufMessages.ActionQueue.LogicalRetract.newBuilder()
.setHandleId( this.handle.getId() )
.setActivation( PersisterHelper.createActivation( this.activation.getRule().getPackageName(),
this.activation.getRule().getName(),
this.activation.getTuple() ) )
.build();
return ProtobufMessages.ActionQueue.Action.newBuilder()
.setType( ProtobufMessages.ActionQueue.ActionType.LOGICAL_RETRACT )
.setLogicalRetract( _retract )
.build();
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
tms = (TruthMaintenanceSystem) in.readObject();
node = (LogicalDependency) in.readObject();
list = (LinkedList) in.readObject();
handle = (InternalFactHandle) in.readObject();
context = (PropagationContext) in.readObject();
activation = (Activation) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject( tms );
out.writeObject( node );
out.writeObject( list );
out.writeObject( handle );
out.writeObject( context );
out.writeObject( activation );
}
public void execute(InternalWorkingMemory workingMemory) {
if ( list.isEmpty() ) {
this.tms.getJustifiedMap().remove( handle.getId() );
// this needs to be scheduled so we don't upset the current
// working memory operation
workingMemory.retract( this.handle,
false,
true,
(Rule) context.getRuleOrigin(),
this.activation );
}
}
public void execute(InternalKnowledgeRuntime kruntime) {
execute(((StatefulKnowledgeSessionImpl) kruntime).getInternalWorkingMemory());
}
}
/**
* The FactHandle is being removed from the system so remove any logical dependencies
* between the justified FactHandle and its justifiers. Removes the FactHandle key
* from the justifiedMap. It then iterates over all the LogicalDependency nodes, if any,
* in the returned Set and removes the LogicalDependency node from the LinkedList maintained
* by the Activation.
*
* @see LogicalDependency
*
* @param handle - The FactHandle to be removed
* @throws FactException
*/
public void removeLogicalDependencies(final InternalFactHandle handle) throws FactException {
final LinkedList list = (LinkedList) this.justifiedMap.remove( handle.getId() );
if ( list != null && !list.isEmpty() ) {
for ( LinkedListEntry entry = (LinkedListEntry) list.getFirst(); entry != null; entry = (LinkedListEntry) entry.getNext() ) {
final LogicalDependency node = (LogicalDependency) entry.getObject();
node.getJustifier().getLogicalDependencies().remove( node );
}
}
}
/**
* Adds a justification for the FactHandle to the justifiedMap.
*
* @param handle
* @param activation
* @param context
* @param rule
* @throws FactException
*/
public void addLogicalDependency(final InternalFactHandle handle,
final Activation activation,
final PropagationContext context,
final Rule rule) throws FactException {
final LogicalDependency node = new LogicalDependency( activation,
handle );
activation.getRule().setHasLogicalDependency( true );
activation.addLogicalDependency( node );
LinkedList list = (LinkedList) this.justifiedMap.get( handle.getId() );
if ( list == null ) {
if ( context.getType() == PropagationContext.MODIFICATION ) {
// if this was a update, chances are its trying to retract a logical assertion
}
list = new LinkedList();
this.justifiedMap.put( handle.getId(),
list );
}
list.add( node.getJustifierEntry() );
}
public void clear() {
this.justifiedMap.clear();
this.assertMap.clear();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sysds.hops.rewrite;
import java.util.ArrayList;
import java.util.List;
import org.apache.sysds.common.Types.OpOp2;
import org.apache.sysds.hops.Hop;
import org.apache.sysds.hops.IndexingOp;
import org.apache.sysds.hops.LeftIndexingOp;
import org.apache.sysds.hops.LiteralOp;
/**
* Rule: Indexing vectorization. This rewrite rule set simplifies
* multiple right / left indexing accesses within a DAG into row/column
* index accesses, which is beneficial for two reasons: (1) it is an
* enabler for later row/column partitioning, and (2) it reduces the number
* of operations over potentially large data (i.e., prevents unnecessary MR
* operations and reduces pressure on the buffer pool due to copy on write
* on left indexing).
*
*/
public class RewriteIndexingVectorization extends HopRewriteRule
{
@Override
public ArrayList<Hop> rewriteHopDAGs(ArrayList<Hop> roots, ProgramRewriteStatus state) {
if( roots == null )
return roots;
for( Hop h : roots )
rule_IndexingVectorization( h );
return roots;
}
@Override
public Hop rewriteHopDAG(Hop root, ProgramRewriteStatus state) {
if( root == null )
return root;
rule_IndexingVectorization( root );
return root;
}
private void rule_IndexingVectorization( Hop hop ) {
if(hop.isVisited())
return;
//recursively process children
for( int i=0; i<hop.getInput().size(); i++)
{
Hop hi = hop.getInput().get(i);
//apply indexing vectorization rewrites
//MB: disabled right indexing rewrite because (1) piggybacked in MR anyway, (2) usually
//not too much overhead, and (3) makes literal replacement more difficult
hi = vectorizeRightLeftIndexingChains(hi); //e.g., B[,1]=A[,1]; B[,2]=A[2]; -> B[,1:2] = A[,1:2]
//vectorizeRightIndexing( hi ); //e.g., multiple rightindexing X[i,1], X[i,3] -> X[i,];
hi = vectorizeLeftIndexing( hi ); //e.g., multiple left indexing X[i,1], X[i,3] -> X[i,];
//process childs recursively after rewrites
rule_IndexingVectorization( hi );
}
hop.setVisited();
}
private static Hop vectorizeRightLeftIndexingChains(Hop hi) {
//check for valid root operator
if( !(hi instanceof LeftIndexingOp
&& hi.getInput().get(1) instanceof IndexingOp
&& hi.getInput().get(1).getParent().size()==1) )
return hi;
LeftIndexingOp lix0 = (LeftIndexingOp) hi;
IndexingOp rix0 = (IndexingOp) hi.getInput().get(1);
if( !(lix0.isRowLowerEqualsUpper() || lix0.isColLowerEqualsUpper())
|| lix0.isRowLowerEqualsUpper() != rix0.isRowLowerEqualsUpper()
|| lix0.isColLowerEqualsUpper() != rix0.isColLowerEqualsUpper())
return hi;
boolean row = lix0.isRowLowerEqualsUpper();
if( !( (row ? HopRewriteUtils.isFullRowIndexing(lix0) : HopRewriteUtils.isFullColumnIndexing(lix0))
&& (row ? HopRewriteUtils.isFullRowIndexing(rix0) : HopRewriteUtils.isFullColumnIndexing(rix0))) )
return hi;
//determine consecutive left-right indexing chains for rows/columns
List<LeftIndexingOp> lix = new ArrayList<>(); lix.add(lix0);
List<IndexingOp> rix = new ArrayList<>(); rix.add(rix0);
LeftIndexingOp clix = lix0;
IndexingOp crix = rix0;
while( isConsecutiveLeftRightIndexing(clix, crix, clix.getInput().get(0))
&& clix.getInput().get(0).getParent().size()==1
&& clix.getInput().get(0).getInput().get(1).getParent().size()==1 ) {
clix = (LeftIndexingOp)clix.getInput().get(0);
crix = (IndexingOp)clix.getInput().get(1);
lix.add(clix); rix.add(crix);
}
//rewrite pattern if at least two consecutive pairs
if( lix.size() >= 2 ) {
IndexingOp rixn = rix.get(rix.size()-1);
Hop rlrix = rixn.getInput().get(1);
Hop rurix = row ? HopRewriteUtils.createBinary(rlrix, new LiteralOp(rix.size()-1), OpOp2.PLUS) : rixn.getInput().get(2);
Hop clrix = rixn.getInput().get(3);
Hop curix = row ? rixn.getInput().get(4) : HopRewriteUtils.createBinary(clrix, new LiteralOp(rix.size()-1), OpOp2.PLUS);
IndexingOp rixNew = HopRewriteUtils.createIndexingOp(rixn.getInput().get(0), rlrix, rurix, clrix, curix);
LeftIndexingOp lixn = lix.get(rix.size()-1);
Hop rllix = lixn.getInput().get(2);
Hop rulix = row ? HopRewriteUtils.createBinary(rllix, new LiteralOp(lix.size()-1), OpOp2.PLUS) : lixn.getInput().get(3);
Hop cllix = lixn.getInput().get(4);
Hop culix = row ? lixn.getInput().get(5) : HopRewriteUtils.createBinary(cllix, new LiteralOp(lix.size()-1), OpOp2.PLUS);
LeftIndexingOp lixNew = HopRewriteUtils.createLeftIndexingOp(lixn.getInput().get(0), rixNew, rllix, rulix, cllix, culix);
//rewire parents and childs
HopRewriteUtils.replaceChildReference(hi.getParent().get(0), hi, lixNew);
for( int i=0; i<lix.size(); i++ ) {
HopRewriteUtils.removeAllChildReferences(lix.get(i));
HopRewriteUtils.removeAllChildReferences(rix.get(i));
}
hi = lixNew;
LOG.debug("Applied vectorizeRightLeftIndexingChains (line "+hi.getBeginLine()+")");
}
return hi;
}
private static boolean isConsecutiveLeftRightIndexing(LeftIndexingOp lix, IndexingOp rix, Hop input) {
if( !(input instanceof LeftIndexingOp
&& input.getInput().get(1) instanceof IndexingOp) )
return false;
boolean row = lix.isRowLowerEqualsUpper();
LeftIndexingOp lix2 = (LeftIndexingOp) input;
IndexingOp rix2 = (IndexingOp) input.getInput().get(1);
//check row/column access with full row/column indexing
boolean access = (row ? HopRewriteUtils.isFullRowIndexing(lix2) && HopRewriteUtils.isFullRowIndexing(rix2) :
HopRewriteUtils.isFullColumnIndexing(lix2) && HopRewriteUtils.isFullColumnIndexing(rix2));
//check equivalent right indexing inputs
boolean rixInputs = (rix.getInput().get(0) == rix2.getInput().get(0));
//check consecutive access
boolean consecutive = (row ? HopRewriteUtils.isConsecutiveIndex(lix2.getInput().get(2), lix.getInput().get(2))
&& HopRewriteUtils.isConsecutiveIndex(rix2.getInput().get(1), rix.getInput().get(1)) :
HopRewriteUtils.isConsecutiveIndex(lix2.getInput().get(4), lix.getInput().get(4))
&& HopRewriteUtils.isConsecutiveIndex(rix2.getInput().get(3), rix.getInput().get(3)));
return access && rixInputs && consecutive;
}
/**
* Note: unnecessary row or column indexing then later removed via
* dynamic rewrites
*
* @param hop high-level operator
*/
@SuppressWarnings("unused")
private static void vectorizeRightIndexing( Hop hop )
{
if( hop instanceof IndexingOp ) //right indexing
{
IndexingOp ihop0 = (IndexingOp) hop;
boolean isSingleRow = ihop0.isRowLowerEqualsUpper();
boolean isSingleCol = ihop0.isColLowerEqualsUpper();
boolean appliedRow = false;
//search for multiple indexing in same row
if( isSingleRow && isSingleCol ){
Hop input = ihop0.getInput().get(0);
//find candidate set
//dependence on common subexpression elimination to find equal input / row expression
ArrayList<Hop> ihops = new ArrayList<Hop>();
ihops.add(ihop0);
for( Hop c : input.getParent() ){
if( c != ihop0 && c instanceof IndexingOp && c.getInput().get(0) == input
&& ((IndexingOp) c).isRowLowerEqualsUpper()
&& c.getInput().get(1)==ihop0.getInput().get(1) )
{
ihops.add( c );
}
}
//apply rewrite if found candidates
if( ihops.size() > 1 ){
//new row indexing operator
IndexingOp newRix = new IndexingOp("tmp", input.getDataType(), input.getValueType(), input,
ihop0.getInput().get(1), ihop0.getInput().get(1), new LiteralOp(1),
HopRewriteUtils.createValueHop(input, false), true, false);
HopRewriteUtils.setOutputParameters(newRix, -1, -1, input.getBlocksize(), -1);
newRix.refreshSizeInformation();
//rewire current operator and all candidates
for( Hop c : ihops ) {
HopRewriteUtils.removeChildReference(c, input); //input data
HopRewriteUtils.addChildReference(c, newRix, 0);
HopRewriteUtils.removeChildReferenceByPos(c, c.getInput().get(1),1); //row lower expr
HopRewriteUtils.addChildReference(c, new LiteralOp(1), 1);
HopRewriteUtils.removeChildReferenceByPos(c, c.getInput().get(2),2); //row upper expr
HopRewriteUtils.addChildReference(c, new LiteralOp(1), 2);
c.refreshSizeInformation();
}
appliedRow = true;
LOG.debug("Applied vectorizeRightIndexingRow");
}
}
//search for multiple indexing in same col
if( isSingleRow && isSingleCol && !appliedRow ){
Hop input = ihop0.getInput().get(0);
//find candidate set
//dependence on common subexpression elimination to find equal input / row expression
ArrayList<Hop> ihops = new ArrayList<Hop>();
ihops.add(ihop0);
for( Hop c : input.getParent() ){
if( c != ihop0 && c instanceof IndexingOp && c.getInput().get(0) == input
&& ((IndexingOp) c).isColLowerEqualsUpper()
&& c.getInput().get(3)==ihop0.getInput().get(3) )
{
ihops.add( c );
}
}
//apply rewrite if found candidates
if( ihops.size() > 1 ){
//new row indexing operator
IndexingOp newRix = new IndexingOp("tmp", input.getDataType(), input.getValueType(), input,
new LiteralOp(1), HopRewriteUtils.createValueHop(input, true),
ihop0.getInput().get(3), ihop0.getInput().get(3), false, true);
HopRewriteUtils.setOutputParameters(newRix, -1, -1, input.getBlocksize(), -1);
newRix.refreshSizeInformation();
//rewire current operator and all candidates
for( Hop c : ihops ) {
HopRewriteUtils.removeChildReference(c, input); //input data
HopRewriteUtils.addChildReference(c, newRix, 0);
HopRewriteUtils.replaceChildReference(c, c.getInput().get(3), new LiteralOp(1), 3); //col lower expr
HopRewriteUtils.replaceChildReference(c, c.getInput().get(4), new LiteralOp(1), 4); //col upper expr
c.refreshSizeInformation();
}
LOG.debug("Applied vectorizeRightIndexingCol");
}
}
}
}
@SuppressWarnings("unchecked")
private static Hop vectorizeLeftIndexing( Hop hop )
{
Hop ret = hop;
if( hop instanceof LeftIndexingOp ) //left indexing
{
LeftIndexingOp ihop0 = (LeftIndexingOp) hop;
boolean isSingleRow = ihop0.isRowLowerEqualsUpper();
boolean isSingleCol = ihop0.isColLowerEqualsUpper();
boolean appliedRow = false;
if( isSingleRow && isSingleCol )
{
//collect simple chains (w/o multiple consumers) of left indexing ops
ArrayList<Hop> ihops = new ArrayList<>();
ihops.add(ihop0);
Hop current = ihop0;
while( current.getInput().get(0) instanceof LeftIndexingOp ) {
LeftIndexingOp tmp = (LeftIndexingOp) current.getInput().get(0);
if( tmp.getParent().size()>1 //multiple consumers, i.e., not a simple chain
|| !tmp.isRowLowerEqualsUpper() //row merge not applicable
|| tmp.getInput().get(2) != ihop0.getInput().get(2) //not the same row
|| tmp.getInput().get(0).getDim2() <= 1 ) //target is single column or unknown
{
break;
}
ihops.add( tmp );
current = tmp;
}
//apply rewrite if found candidates
if( ihops.size() > 1 ){
Hop input = current.getInput().get(0);
Hop rowExpr = ihop0.getInput().get(2); //keep before reset
//new row indexing operator
IndexingOp newRix = new IndexingOp("tmp1", input.getDataType(), input.getValueType(),
input, rowExpr, rowExpr, new LiteralOp(1),
HopRewriteUtils.createValueHop(input, false), true, false);
HopRewriteUtils.setOutputParameters(newRix, -1, -1, input.getBlocksize(), -1);
newRix.refreshSizeInformation();
//reset visit status of copied hops (otherwise hidden by left indexing)
for( Hop c : newRix.getInput() )
c.resetVisitStatus();
//rewrite bottom left indexing operator
HopRewriteUtils.removeChildReference(current, input); //input data
HopRewriteUtils.addChildReference(current, newRix, 0);
//reset row index all candidates and refresh sizes (bottom-up)
for( int i=ihops.size()-1; i>=0; i-- ) {
Hop c = ihops.get(i);
HopRewriteUtils.replaceChildReference(c, c.getInput().get(2), new LiteralOp(1), 2); //row lower expr
HopRewriteUtils.replaceChildReference(c, c.getInput().get(3), new LiteralOp(1), 3); //row upper expr
((LeftIndexingOp)c).setRowLowerEqualsUpper(true);
c.refreshSizeInformation();
}
//new row left indexing operator (for all parents, only intermediates are guaranteed to have 1 parent)
//(note: it's important to clone the parent list before creating newLix on top of ihop0)
ArrayList<Hop> ihop0parents = (ArrayList<Hop>) ihop0.getParent().clone();
ArrayList<Integer> ihop0parentsPos = new ArrayList<>();
for( Hop parent : ihop0parents ) {
int posp = HopRewriteUtils.getChildReferencePos(parent, ihop0);
HopRewriteUtils.removeChildReferenceByPos(parent, ihop0, posp); //input data
ihop0parentsPos.add(posp);
}
LeftIndexingOp newLix = new LeftIndexingOp("tmp2", input.getDataType(), input.getValueType(),
input, ihop0, rowExpr, rowExpr, new LiteralOp(1),
HopRewriteUtils.createValueHop(input, false), true, false);
HopRewriteUtils.setOutputParameters(newLix, -1, -1, input.getBlocksize(), -1);
newLix.refreshSizeInformation();
//reset visit status of copied hops (otherwise hidden by left indexing)
for( Hop c : newLix.getInput() )
c.resetVisitStatus();
for( int i=0; i<ihop0parentsPos.size(); i++ ) {
Hop parent = ihop0parents.get(i);
int posp = ihop0parentsPos.get(i);
HopRewriteUtils.addChildReference(parent, newLix, posp);
}
appliedRow = true;
ret = newLix;
LOG.debug("Applied vectorizeLeftIndexingRow for hop "+hop.getHopID());
}
}
if( isSingleRow && isSingleCol && !appliedRow )
{
//collect simple chains (w/o multiple consumers) of left indexing ops
ArrayList<Hop> ihops = new ArrayList<>();
ihops.add(ihop0);
Hop current = ihop0;
while( current.getInput().get(0) instanceof LeftIndexingOp ) {
LeftIndexingOp tmp = (LeftIndexingOp) current.getInput().get(0);
if( tmp.getParent().size()>1 //multiple consumers, i.e., not a simple chain
|| !tmp.isColLowerEqualsUpper() //row merge not applicable
|| tmp.getInput().get(4) != ihop0.getInput().get(4) //not the same col
|| tmp.getInput().get(0).getDim1() <= 1 ) //target is single row or unknown
{
break;
}
ihops.add( tmp );
current = tmp;
}
//apply rewrite if found candidates
if( ihops.size() > 1 ){
Hop input = current.getInput().get(0);
Hop colExpr = ihop0.getInput().get(4); //keep before reset
//new row indexing operator
IndexingOp newRix = new IndexingOp("tmp1", input.getDataType(), input.getValueType(),
input, new LiteralOp(1), HopRewriteUtils.createValueHop(input, true),
colExpr, colExpr, false, true);
HopRewriteUtils.setOutputParameters(newRix, -1, -1, input.getBlocksize(), -1);
newRix.refreshSizeInformation();
//reset visit status of copied hops (otherwise hidden by left indexing)
for( Hop c : newRix.getInput() )
c.resetVisitStatus();
//rewrite bottom left indexing operator
HopRewriteUtils.removeChildReference(current, input); //input data
HopRewriteUtils.addChildReference(current, newRix, 0);
//reset col index all candidates and refresh sizes (bottom-up)
for( int i=ihops.size()-1; i>=0; i-- ) {
Hop c = ihops.get(i);
HopRewriteUtils.replaceChildReference(c, c.getInput().get(4), new LiteralOp(1), 4); //col lower expr
HopRewriteUtils.replaceChildReference(c, c.getInput().get(5), new LiteralOp(1), 5); //col upper expr
((LeftIndexingOp)c).setColLowerEqualsUpper(true);
c.refreshSizeInformation();
}
//new row left indexing operator (for all parents, only intermediates are guaranteed to have 1 parent)
//(note: it's important to clone the parent list before creating newLix on top of ihop0)
ArrayList<Hop> ihop0parents = (ArrayList<Hop>) ihop0.getParent().clone();
ArrayList<Integer> ihop0parentsPos = new ArrayList<>();
for( Hop parent : ihop0parents ) {
int posp = HopRewriteUtils.getChildReferencePos(parent, ihop0);
HopRewriteUtils.removeChildReferenceByPos(parent, ihop0, posp); //input data
ihop0parentsPos.add(posp);
}
LeftIndexingOp newLix = new LeftIndexingOp("tmp2", input.getDataType(), input.getValueType(),
input, ihop0, new LiteralOp(1), HopRewriteUtils.createValueHop(input, true),
colExpr, colExpr, false, true);
HopRewriteUtils.setOutputParameters(newLix, -1, -1, input.getBlocksize(), -1);
newLix.refreshSizeInformation();
//reset visit status of copied hops (otherwise hidden by left indexing)
for( Hop c : newLix.getInput() )
c.resetVisitStatus();
for( int i=0; i<ihop0parentsPos.size(); i++ ) {
Hop parent = ihop0parents.get(i);
int posp = ihop0parentsPos.get(i);
HopRewriteUtils.addChildReference(parent, newLix, posp);
}
ret = newLix;
LOG.debug("Applied vectorizeLeftIndexingCol for hop "+hop.getHopID());
}
}
}
return ret;
}
}
| |
/*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.textpane;
import com.dmdirc.ui.messages.CachingDocument;
import com.dmdirc.ui.messages.LinePosition;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.List;
import javax.swing.UIManager;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Renders basic text, line wrapping where appropriate.
*/
public class BasicTextLineRenderer implements LineRenderer {
/** Single Side padding for textpane. */
private static final int SINGLE_SIDE_PADDING = 3;
/** Both Side padding for textpane. */
private static final int DOUBLE_SIDE_PADDING = SINGLE_SIDE_PADDING * 2;
/** Render result to use. This instance is recycled for each render call. */
private final RenderResult result = new RenderResult();
private final TextPane textPane;
private final TextPaneCanvas textPaneCanvas;
private final CachingDocument<AttributedString> document;
private final Color highlightForeground;
private final Color highlightBackground;
/** Reused in each render pass to save creating a new list. */
private final List<TextLayout> wrappedLines = new ArrayList<>();
public BasicTextLineRenderer(final TextPane textPane, final TextPaneCanvas textPaneCanvas,
final CachingDocument<AttributedString> document) {
this.textPane = textPane;
this.textPaneCanvas = textPaneCanvas;
this.document = document;
highlightForeground = UIManager.getColor("TextArea.selectionForeground");
highlightBackground = UIManager.getColor("TextArea.selectionBackground");
}
@Override
public RenderResult render(final Graphics2D graphics, final float canvasWidth,
final float canvasHeight, final float drawPosY, final int line) {
result.drawnAreas.clear();
result.textLayouts.clear();
result.totalHeight = 0;
final AttributedCharacterIterator iterator = document.getStyledLine(line).getIterator();
final int paragraphStart = iterator.getBeginIndex();
final int paragraphEnd = iterator.getEndIndex();
final LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(iterator,
graphics.getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
float newDrawPosY = drawPosY;
// Calculate layouts for each wrapped line.
wrappedLines.clear();
int chars = 0;
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = checkNotNull(lineMeasurer.nextLayout(canvasWidth));
chars += layout.getCharacterCount();
wrappedLines.add(layout);
}
// Loop through each wrapped line
for (int i = wrappedLines.size() - 1; i >= 0; i--) {
final TextLayout layout = wrappedLines.get(i);
// Calculate the initial X position
final float drawPosX;
if (layout.isLeftToRight()) {
drawPosX = SINGLE_SIDE_PADDING;
} else {
drawPosX = canvasWidth - layout.getAdvance();
}
chars -= layout.getCharacterCount();
// Check if the target is in range
if (newDrawPosY >= 0 || newDrawPosY <= canvasHeight) {
renderLine(graphics, canvasWidth, line, drawPosX, newDrawPosY, i, chars,
layout);
}
// Calculate the Y offset
newDrawPosY -= layout.getAscent() + layout.getLeading() + layout.getDescent();
}
result.totalHeight = drawPosY - newDrawPosY;
return result;
}
protected void renderLine(final Graphics2D graphics, final float canvasWidth, final int line,
final float drawPosX, final float drawPosY, final int numberOfWraps, final int chars,
final TextLayout layout) {
graphics.setColor(textPane.getForeground());
layout.draw(graphics, drawPosX, drawPosY);
doHighlight(line, chars, layout, graphics, canvasWidth + DOUBLE_SIDE_PADDING,
drawPosX, drawPosY);
final LineInfo lineInfo = new LineInfo(line, numberOfWraps);
result.firstVisibleLine = line;
result.textLayouts.put(lineInfo, layout);
result.drawnAreas.put(lineInfo,
new Rectangle2D.Float(0,
drawPosY - layout.getAscent() - layout.getLeading(),
canvasWidth + DOUBLE_SIDE_PADDING,
layout.getAscent() + layout.getDescent() + layout.getLeading()));
}
/**
* Redraws the text that has been highlighted.
*
* @param line Line number
* @param chars Number of characters already handled in a wrapped line
* @param layout Current wrapped line's textlayout
* @param g Graphics surface to draw highlight on
* @param drawPosX current x location of the line
* @param drawPosY current y location of the line
*/
protected void doHighlight(final int line, final int chars,
final TextLayout layout, final Graphics2D g, final float canvasWidth,
final float drawPosX, final float drawPosY) {
final LinePosition selectedRange = textPaneCanvas.getSelectedRange();
final int selectionStartLine = selectedRange.getStartLine();
final int selectionStartChar = selectedRange.getStartPos();
final int selectionEndLine = selectedRange.getEndLine();
final int selectionEndChar = selectedRange.getEndPos();
// Does this line need highlighting?
if (selectionStartLine <= line && selectionEndLine >= line) {
final int firstChar;
// Determine the first char we care about
if (selectionStartLine < line || selectionStartChar < chars) {
firstChar = 0;
} else {
firstChar = selectionStartChar - chars;
}
// ... And the last
final int lastChar;
if (selectionEndLine > line || selectionEndChar > chars + layout.getCharacterCount()) {
lastChar = layout.getCharacterCount();
} else {
lastChar = selectionEndChar - chars;
}
// If the selection includes the chars we're showing
if (lastChar > 0 && firstChar < layout.getCharacterCount() && lastChar > firstChar) {
doHighlight(line,
layout.getLogicalHighlightShape(firstChar, lastChar), g, canvasWidth,
drawPosY, drawPosX, chars + firstChar, chars + lastChar,
lastChar == layout.getCharacterCount());
}
}
}
private void doHighlight(final int line, final Shape logicalHighlightShape, final Graphics2D g,
final float canvasWidth, final float drawPosY, final float drawPosX,
final int firstChar, final int lastChar, final boolean isEndOfLine) {
final AttributedCharacterIterator iterator = document.getStyledLine(line).getIterator();
final AttributedString as = new AttributedString(iterator, firstChar, lastChar);
as.addAttribute(TextAttribute.FOREGROUND, highlightForeground);
as.addAttribute(TextAttribute.BACKGROUND, highlightBackground);
final TextLayout newLayout = new TextLayout(as.getIterator(), g.getFontRenderContext());
final Rectangle2D bounds = logicalHighlightShape.getBounds();
g.setColor(highlightBackground);
g.translate(drawPosX + bounds.getX(), drawPosY);
if (isEndOfLine) {
g.fill(new Rectangle2D.Double(
bounds.getWidth(),
bounds.getY(),
canvasWidth - bounds.getX() - bounds.getWidth(),
bounds.getHeight()));
}
newLayout.draw(g, 0, 0);
g.translate(-drawPosX - bounds.getX(), -drawPosY);
}
}
| |
package com.physicaloid.lib.usb.driver.uart;
import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.util.Log;
import com.physicaloid.BuildConfig;
import com.physicaloid.lib.UsbVidList;
import com.physicaloid.lib.framework.SerialCommunicator;
import com.physicaloid.lib.usb.UsbCdcConnection;
import com.physicaloid.lib.usb.UsbVidPid;
import com.physicaloid.misc.RingBuffer;
import java.util.ArrayList;
import java.util.List;
public class UartCp210x extends SerialCommunicator {
private static final String TAG = UartCp210x.class.getSimpleName();
private static final boolean DEBUG_SHOW = false && BuildConfig.DEBUG;
private static final int DEFAULT_BAUDRATE = 9600;
private UsbCdcConnection mUsbConnetionManager;
private UartConfig mUartConfig;
private static final int RING_BUFFER_SIZE = 1024;
private static final int USB_READ_BUFFER_SIZE = 256;
private static final int USB_WRITE_BUFFER_SIZE = 256;
private RingBuffer mBuffer;
private boolean mReadThreadStop = true;
private UsbDeviceConnection mConnection;
private UsbEndpoint mEndpointIn;
private UsbEndpoint mEndpointOut;
private boolean isOpened;
/* Config request types */
private static final byte REQTYPE_HOST_TO_INTERFACE = (byte) 0x41;
private static final byte REQTYPE_INTERFACE_TO_HOST = (byte) 0xc1;
@SuppressWarnings("unused")
private static final byte REQTYPE_HOST_TO_DEVICE = (byte) 0x40;
@SuppressWarnings("unused")
private static final byte REQTYPE_DEVICE_TO_HOST = (byte) 0xc0;
/* Config request codes */
private static final byte CP210X_IFC_ENABLE = 0x00;
@SuppressWarnings("unused")
private static final byte CP210X_SET_BAUDDIV = 0x01;
@SuppressWarnings("unused")
private static final byte CP210X_GET_BAUDDIV = 0x02;
@SuppressWarnings("unused")
private static final byte CP210X_SET_LINE_CTL = 0x03;
private static final byte CP210X_GET_LINE_CTL = 0x04;
@SuppressWarnings("unused")
private static final byte CP210X_SET_BREAK = 0x05;
@SuppressWarnings("unused")
private static final byte CP210X_IMM_CHAR = 0x06;
private static final byte CP210X_SET_MHS = 0x07;
@SuppressWarnings("unused")
private static final byte CP210X_GET_MDMSTS = 0x08;
@SuppressWarnings("unused")
private static final byte CP210X_SET_XON = 0x09;
@SuppressWarnings("unused")
private static final byte CP210X_SET_XOFF = 0x0A;
@SuppressWarnings("unused")
private static final byte CP210X_SET_EVENTMASK = 0x0B;
@SuppressWarnings("unused")
private static final byte CP210X_GET_EVENTMASK = 0x0C;
@SuppressWarnings("unused")
private static final byte CP210X_SET_CHAR = 0x0D;
@SuppressWarnings("unused")
private static final byte CP210X_GET_CHARS = 0x0E;
@SuppressWarnings("unused")
private static final byte CP210X_GET_PROPS = 0x0F;
@SuppressWarnings("unused")
private static final byte CP210X_GET_COMM_STATUS = 0x10;
@SuppressWarnings("unused")
private static final byte CP210X_RESET = 0x11;
@SuppressWarnings("unused")
private static final byte CP210X_PURGE = 0x12;
@SuppressWarnings("unused")
private static final byte CP210X_SET_FLOW = 0x13;
@SuppressWarnings("unused")
private static final byte CP210X_GET_FLOW = 0x14;
@SuppressWarnings("unused")
private static final byte CP210X_EMBED_EVENTS = 0x15;
@SuppressWarnings("unused")
private static final byte CP210X_GET_EVENTSTATE = 0x16;
@SuppressWarnings("unused")
private static final byte CP210X_SET_CHARS = 0x19;
@SuppressWarnings("unused")
private static final byte CP210X_GET_BAUDRATE = 0x1D;
private static final byte CP210X_SET_BAUDRATE = 0x1E;
/* CP210X_IFC_ENABLE */
private static final int UART_ENABLE = 0x0001;
private static final int UART_DISABLE = 0x0000;
/* CP210X_(SET|GET)_BAUDDIV */
@SuppressWarnings("unused")
private static final int BAUD_RATE_GEN_FREQ = 0x384000;
/* CP210X_(SET|GET)_LINE_CTL */
private static final int BITS_DATA_MASK = 0x0f00;
@SuppressWarnings("unused")
private static final int BITS_DATA_5 = 0x0500;
@SuppressWarnings("unused")
private static final int BITS_DATA_6 = 0x0600;
;
private static final int BITS_DATA_7 = 0x0700;
private static final int BITS_DATA_8 = 0x0800;
@SuppressWarnings("unused")
private static final int BITS_DATA_9 = 0x0900;
private static final int BITS_PARITY_MASK = 0x00f0;
private static final int BITS_PARITY_NONE = 0x0000;
private static final int BITS_PARITY_ODD = 0x0010;
private static final int BITS_PARITY_EVEN = 0x0020;
private static final int BITS_PARITY_MARK = 0x0030;
private static final int BITS_PARITY_SPACE = 0x0040;
private static final int BITS_STOP_MASK = 0x000f;
private static final int BITS_STOP_1 = 0x0000;
private static final int BITS_STOP_1_5 = 0x0001;
private static final int BITS_STOP_2 = 0x0002;
/* CP210X_SET_BREAK */
@SuppressWarnings("unused")
private static final int BREAK_ON = 0x0001;
@SuppressWarnings("unused")
private static final int BREAK_OFF = 0x0000;
/* CP210X_(SET_MHS|GET_MDMSTS) */
private static final int CONTROL_DTR = 0x0001;
private static final int CONTROL_RTS = 0x0002;
@SuppressWarnings("unused")
private static final int CONTROL_CTS = 0x0010;
@SuppressWarnings("unused")
private static final int CONTROL_DSR = 0x0020;
@SuppressWarnings("unused")
private static final int CONTROL_RING = 0x0040;
@SuppressWarnings("unused")
private static final int CONTROL_DCD = 0x0080;
private static final int CONTROL_WRITE_DTR = 0x0100;
private static final int CONTROL_WRITE_RTS = 0x0200;
public UartCp210x(Context context) {
super(context);
mUsbConnetionManager = new UsbCdcConnection(context);
mUartConfig = new UartConfig();
mBuffer = new RingBuffer(RING_BUFFER_SIZE);
isOpened = false;
}
@Override
public boolean open() {
for (UsbVidList id : UsbVidList.values()) {
if (open(new UsbVidPid(id.getVid(), 0))) {
return true;
}
}
return false;
}
public boolean open(UsbVidPid ids) {
if (mUsbConnetionManager.open(ids)) {
mConnection = mUsbConnetionManager.getConnection();
mEndpointIn = mUsbConnetionManager.getEndpointIn();
mEndpointOut = mUsbConnetionManager.getEndpointOut();
if (!init()) {
return false;
}
if (!setBaudrate(DEFAULT_BAUDRATE)) {
return false;
}
mBuffer.clear();
startRead();
isOpened = true;
return true;
}
return false;
}
@Override
public boolean close() {
stopRead();
isOpened = false;
cp210xUsbDisable();
return mUsbConnetionManager.close();
}
@Override
public int read(byte[] buf, int size) {
return mBuffer.get(buf, size);
}
@Override
public int write(byte[] buf, int size) {
if (buf == null) {
return 0;
}
int offset = 0;
int write_size;
int written_size;
byte[] wbuf = new byte[USB_WRITE_BUFFER_SIZE];
while (offset < size) {
write_size = USB_WRITE_BUFFER_SIZE;
if (offset + write_size > size) {
write_size = size - offset;
}
System.arraycopy(buf, offset, wbuf, 0, write_size);
written_size = mConnection.bulkTransfer(mEndpointOut, wbuf, write_size, 100);
if (written_size < 0) {
return -1;
}
offset += written_size;
}
return offset;
}
private void stopRead() {
mReadThreadStop = true;
}
private void startRead() {
if (mReadThreadStop) {
mReadThreadStop = false;
new Thread(mLoop).start();
}
}
private Runnable mLoop = new Runnable() {
@Override
public void run() {
int len = 0;
byte[] rbuf = new byte[USB_READ_BUFFER_SIZE];
for (; ; ) {// this is the main loop for transferring
try {
len = mConnection.bulkTransfer(mEndpointIn,
rbuf, rbuf.length, 50);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
if (len > 0) {
mBuffer.add(rbuf, len);
onRead(len);
}
if (mReadThreadStop) {
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} // end of run()
}; // end of runnable
@Override
public boolean setUartConfig(UartConfig config) {
boolean res = true;
boolean ret = true;
if (mUartConfig.baudrate != config.baudrate) {
res = setBaudrate(config.baudrate);
ret = ret && res;
}
if (mUartConfig.dataBits != config.dataBits) {
res = setDataBits(config.dataBits);
ret = ret && res;
}
if (mUartConfig.parity != config.parity) {
res = setParity(config.parity);
ret = ret && res;
}
if (mUartConfig.stopBits != config.stopBits) {
res = setStopBits(config.stopBits);
ret = ret && res;
}
if (mUartConfig.dtrOn != config.dtrOn ||
mUartConfig.rtsOn != config.rtsOn) {
res = setDtrRts(config.dtrOn, config.rtsOn);
ret = ret && res;
}
return ret;
}
/**
* Initializes CP210x communication
*
* @return true : successful, false : fail
*/
private boolean init() {
int ret = cp210xUsbEnable();
if (ret < 0) {
return false;
}
return true;
}
@Override
public boolean isOpened() {
return isOpened;
}
/**
* Enables CP210x
*
* @return positive value : successful, negative value : fail
*/
private int cp210xUsbEnable() {
if (mConnection == null) return -1;
return mConnection.controlTransfer(
REQTYPE_HOST_TO_INTERFACE,
CP210X_IFC_ENABLE,
UART_ENABLE,
0,
null,
0,
100);
}
/**
* Disables CP210x
*
* @return positive value : successful, negative value : fail
*/
private int cp210xUsbDisable() {
if (mConnection == null) return -1;
return mConnection.controlTransfer(
REQTYPE_HOST_TO_INTERFACE,
CP210X_IFC_ENABLE,
UART_DISABLE,
0,
null,
0,
100);
}
/**
* Gets configurations from CP210x
*
* @param request request id
* @param buf gotten buffer
* @param size size of getting buffer
* @return positive value : successful, negative value : fail
*/
private int cp210xGetConfig(int request, byte[] buf, int size) {
if (mConnection == null) return -1;
int ret = mConnection.controlTransfer(
REQTYPE_INTERFACE_TO_HOST,
request,
0x0000,
0,
buf,
size,
100);
return ret;
}
/**
* Sets configurations from CP210x
*
* @param request request id
* @param buf set buffer
* @param size size of sending buffer
* @return
*/
private int cp210xSetConfig(int request, byte[] buf, int size) {
if (mConnection == null) return -1;
int ret = mConnection.controlTransfer(
REQTYPE_HOST_TO_INTERFACE,
request,
0x0000,
0,
buf,
size,
100);
return ret;
}
@Override
public boolean setBaudrate(int baudrate) {
if (baudrate <= 300) baudrate = 300;
else if (baudrate <= 600) baudrate = 600;
else if (baudrate <= 1200) baudrate = 1200;
else if (baudrate <= 1800) baudrate = 1800;
else if (baudrate <= 2400) baudrate = 2400;
else if (baudrate <= 4000) baudrate = 4000;
else if (baudrate <= 4803) baudrate = 4800;
else if (baudrate <= 7207) baudrate = 7200;
else if (baudrate <= 9612) baudrate = 9600;
else if (baudrate <= 14428) baudrate = 14400;
else if (baudrate <= 16062) baudrate = 16000;
else if (baudrate <= 19250) baudrate = 19200;
else if (baudrate <= 28912) baudrate = 28800;
else if (baudrate <= 38601) baudrate = 38400;
else if (baudrate <= 51558) baudrate = 51200;
else if (baudrate <= 56280) baudrate = 56000;
else if (baudrate <= 58053) baudrate = 57600;
else if (baudrate <= 64111) baudrate = 64000;
else if (baudrate <= 77608) baudrate = 76800;
else if (baudrate <= 117028) baudrate = 115200;
else if (baudrate <= 129347) baudrate = 128000;
else if (baudrate <= 156868) baudrate = 153600;
else if (baudrate <= 237832) baudrate = 230400;
else if (baudrate <= 254234) baudrate = 250000;
else if (baudrate <= 273066) baudrate = 256000;
else if (baudrate <= 491520) baudrate = 460800;
else if (baudrate <= 567138) baudrate = 500000;
else if (baudrate <= 670254) baudrate = 576000;
else if (baudrate < 1000000) baudrate = 921600;
else if (baudrate > 2000000) baudrate = 2000000;
byte[] baudBytes = new byte[4];
intToLittleEndianBytes(baudrate, baudBytes);
int ret = cp210xSetConfig(CP210X_SET_BAUDRATE, baudBytes, 4);
if (ret < 0) {
if (DEBUG_SHOW) {
Log.d(TAG, "Fail to setBaudrate");
}
return false;
}
mUartConfig.baudrate = baudrate;
return true;
}
@Override
public boolean setDataBits(int dataBits) {
int bits;
byte[] buf = new byte[2];
cp210xGetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
bits = littleEndianBytesToInt(buf);
bits &= ~BITS_DATA_MASK;
switch (dataBits) {
case UartConfig.DATA_BITS7:
bits |= BITS_DATA_7;
break;
case UartConfig.DATA_BITS8:
bits |= BITS_DATA_8;
break;
default:
bits |= BITS_DATA_8;
break;
}
intToLittleEndianBytes(bits, buf);
int ret = cp210xSetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
if (ret < 0) {
if (DEBUG_SHOW) {
Log.e(TAG, "Fail to setDataBits");
}
return false;
}
mUartConfig.dataBits = dataBits;
return true;
}
@Override
public boolean setParity(int parity) {
int bits;
byte[] buf = new byte[2];
cp210xGetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
bits = littleEndianBytesToInt(buf);
bits &= ~BITS_PARITY_MASK;
switch (parity) {
case UartConfig.PARITY_NONE:
bits |= BITS_PARITY_NONE;
break;
case UartConfig.PARITY_ODD:
bits |= BITS_PARITY_ODD;
break;
case UartConfig.PARITY_EVEN:
bits |= BITS_PARITY_EVEN;
break;
case UartConfig.PARITY_MARK:
bits |= BITS_PARITY_MARK;
break;
case UartConfig.PARITY_SPACE:
bits |= BITS_PARITY_SPACE;
break;
default:
bits |= BITS_PARITY_NONE;
break;
}
intToLittleEndianBytes(bits, buf);
int ret = cp210xSetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
if (ret < 0) {
if (DEBUG_SHOW) {
Log.d(TAG, "Fail to setParity");
}
return false;
}
mUartConfig.parity = parity;
return true;
}
@Override
public boolean setStopBits(int stopBits) {
int bits;
byte[] buf = new byte[2];
cp210xGetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
bits = littleEndianBytesToInt(buf);
bits &= ~BITS_STOP_MASK;
switch (stopBits) {
case UartConfig.STOP_BITS1:
bits |= BITS_STOP_1;
break;
case UartConfig.STOP_BITS1_5:
bits |= BITS_STOP_1_5;
break;
case UartConfig.STOP_BITS2:
bits |= BITS_STOP_2;
break;
default:
bits |= BITS_STOP_1;
break;
}
intToLittleEndianBytes(bits, buf);
int ret = cp210xSetConfig(CP210X_GET_LINE_CTL, buf, buf.length);
if (ret < 0) {
if (DEBUG_SHOW) {
Log.d(TAG, "Fail to setStopBits");
}
return false;
}
mUartConfig.stopBits = stopBits;
return true;
}
@Override
public boolean setDtrRts(boolean dtrOn, boolean rtsOn) {
int ctrlValue = 0x0000;
byte[] buf = new byte[4];
if (dtrOn) {
ctrlValue |= CONTROL_DTR;
ctrlValue |= CONTROL_WRITE_DTR;
} else {
ctrlValue &= ~CONTROL_DTR;
ctrlValue |= CONTROL_WRITE_DTR;
}
if (rtsOn) {
ctrlValue |= CONTROL_RTS;
ctrlValue |= CONTROL_WRITE_RTS;
} else {
ctrlValue &= ~CONTROL_RTS;
ctrlValue |= CONTROL_WRITE_RTS;
}
intToLittleEndianBytes(ctrlValue, buf);
int ret = cp210xSetConfig(CP210X_SET_MHS, buf, buf.length);
if (ret < 0) {
if (DEBUG_SHOW) {
Log.d(TAG, "Fail to setDtrRts");
}
return false;
}
mUartConfig.dtrOn = dtrOn;
mUartConfig.rtsOn = rtsOn;
return true;
}
@Override
public UartConfig getUartConfig() {
return mUartConfig;
}
@Override
public int getBaudrate() {
return mUartConfig.baudrate;
}
@Override
public int getDataBits() {
return mUartConfig.dataBits;
}
@Override
public int getParity() {
return mUartConfig.parity;
}
@Override
public int getStopBits() {
return mUartConfig.stopBits;
}
@Override
public boolean getDtr() {
return mUartConfig.dtrOn;
}
@Override
public boolean getRts() {
return mUartConfig.rtsOn;
}
@Override
public void clearBuffer() {
mBuffer.clear();
}
//////////////////////////////////////////////////////////
// Listener for reading uart
//////////////////////////////////////////////////////////
private List<ReadLisener> uartReadListenerList
= new ArrayList<ReadLisener>();
private boolean mStopReadListener = false;
@Override
public void addReadListener(ReadLisener listener) {
uartReadListenerList.add(listener);
}
@Override
public void clearReadListener() {
uartReadListenerList.clear();
}
@Override
public void startReadListener() {
mStopReadListener = false;
}
@Override
public void stopReadListener() {
mStopReadListener = true;
}
private void onRead(int size) {
if (mStopReadListener) return;
for (ReadLisener listener : uartReadListenerList) {
listener.onRead(size);
}
}
//////////////////////////////////////////////////////////
/**
* Transfers int to little endian byte array
*
* @param in integer value
* @param out 4 or less length byte array
*/
private void intToLittleEndianBytes(int in, byte[] out) {
if (out == null) return;
if (out.length > 4) return;
for (int i = 0; i < out.length; i++) {
out[i] = (byte) ((in >> (i * 8)) & 0x000000FF);
}
}
/**
* Transfers little endian byte array to int
*
* @param in 4 or less length byte array
* @return integer value
*/
private int littleEndianBytesToInt(byte[] in) {
if (in == null) return 0;
if (in.length > 4) return 0;
int ret = 0;
for (int i = 0; i < in.length; i++) {
ret |= (((int) in[i]) & 0x000000FF) << (i * 8);
}
return ret;
}
}
| |
package edu.mum.cs.ds.atm.ui;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
public class UnitilyPayment {
public JFrame frame;
private JTable table;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitilyPayment window = new UnitilyPayment();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitilyPayment() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 826, 767);
frame.setTitle("Utility Payment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(12, 13, 784, 373);
frame.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{231, 123, 116, 73, 0};
gbl_panel.rowHeights = new int[]{22, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblEnterTheWithdral = new JLabel("Select the Utility");
GridBagConstraints gbc_lblEnterTheWithdral = new GridBagConstraints();
gbc_lblEnterTheWithdral.anchor = GridBagConstraints.EAST;
gbc_lblEnterTheWithdral.insets = new Insets(0, 0, 5, 5);
gbc_lblEnterTheWithdral.gridx = 1;
gbc_lblEnterTheWithdral.gridy = 3;
panel.add(lblEnterTheWithdral, gbc_lblEnterTheWithdral);
JComboBox comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 5);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 2;
gbc_comboBox.gridy = 3;
panel.add(comboBox, gbc_comboBox);
JLabel lblEnterTheAmount = new JLabel("Enter the Amount");
GridBagConstraints gbc_lblEnterTheAmount = new GridBagConstraints();
gbc_lblEnterTheAmount.anchor = GridBagConstraints.EAST;
gbc_lblEnterTheAmount.insets = new Insets(0, 0, 5, 5);
gbc_lblEnterTheAmount.gridx = 1;
gbc_lblEnterTheAmount.gridy = 5;
panel.add(lblEnterTheAmount, gbc_lblEnterTheAmount);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 5);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 2;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JPanel panel_1 = new JPanel();
panel_1.setBounds(12, 389, 391, 169);
frame.getContentPane().add(panel_1);
JPanel panel_3 = new JPanel();
panel_3.setBounds(12, 559, 391, 161);
frame.getContentPane().add(panel_3);
Panel panel_2 = new Panel();
panel_2.setBackground(SystemColor.activeCaption);
panel_2.setBounds(405, 389, 391, 321);
frame.getContentPane().add(panel_2);
GridBagLayout gbl_panel_2 = new GridBagLayout();
gbl_panel_2.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_2.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel_2.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_2.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel_2.setLayout(gbl_panel_2);
JButton button_11 = new JButton("1");
GridBagConstraints gbc_button_11 = new GridBagConstraints();
gbc_button_11.insets = new Insets(0, 0, 5, 5);
gbc_button_11.gridx = 2;
gbc_button_11.gridy = 1;
panel_2.add(button_11, gbc_button_11);
JButton button_10 = new JButton("2");
GridBagConstraints gbc_button_10 = new GridBagConstraints();
gbc_button_10.insets = new Insets(0, 0, 5, 5);
gbc_button_10.gridx = 4;
gbc_button_10.gridy = 1;
panel_2.add(button_10, gbc_button_10);
JButton button_9 = new JButton("3");
GridBagConstraints gbc_button_9 = new GridBagConstraints();
gbc_button_9.insets = new Insets(0, 0, 5, 5);
gbc_button_9.gridx = 6;
gbc_button_9.gridy = 1;
panel_2.add(button_9, gbc_button_9);
JButton button_8 = new JButton("4");
GridBagConstraints gbc_button_8 = new GridBagConstraints();
gbc_button_8.insets = new Insets(0, 0, 5, 5);
gbc_button_8.gridx = 2;
gbc_button_8.gridy = 3;
panel_2.add(button_8, gbc_button_8);
JButton button_7 = new JButton("5");
GridBagConstraints gbc_button_7 = new GridBagConstraints();
gbc_button_7.insets = new Insets(0, 0, 5, 5);
gbc_button_7.gridx = 4;
gbc_button_7.gridy = 3;
panel_2.add(button_7, gbc_button_7);
JButton button_6 = new JButton("6");
GridBagConstraints gbc_button_6 = new GridBagConstraints();
gbc_button_6.insets = new Insets(0, 0, 5, 5);
gbc_button_6.gridx = 6;
gbc_button_6.gridy = 3;
panel_2.add(button_6, gbc_button_6);
JButton button_5 = new JButton("7");
GridBagConstraints gbc_button_5 = new GridBagConstraints();
gbc_button_5.insets = new Insets(0, 0, 5, 5);
gbc_button_5.gridx = 2;
gbc_button_5.gridy = 5;
panel_2.add(button_5, gbc_button_5);
JButton button_4 = new JButton("8");
GridBagConstraints gbc_button_4 = new GridBagConstraints();
gbc_button_4.insets = new Insets(0, 0, 5, 5);
gbc_button_4.gridx = 4;
gbc_button_4.gridy = 5;
panel_2.add(button_4, gbc_button_4);
JButton button_3 = new JButton("9");
GridBagConstraints gbc_button_3 = new GridBagConstraints();
gbc_button_3.insets = new Insets(0, 0, 5, 5);
gbc_button_3.gridx = 6;
gbc_button_3.gridy = 5;
panel_2.add(button_3, gbc_button_3);
JButton button_2 = new JButton(".");
GridBagConstraints gbc_button_2 = new GridBagConstraints();
gbc_button_2.insets = new Insets(0, 0, 5, 5);
gbc_button_2.gridx = 2;
gbc_button_2.gridy = 7;
panel_2.add(button_2, gbc_button_2);
JButton button_1 = new JButton("0");
GridBagConstraints gbc_button_1 = new GridBagConstraints();
gbc_button_1.insets = new Insets(0, 0, 5, 5);
gbc_button_1.gridx = 4;
gbc_button_1.gridy = 7;
panel_2.add(button_1, gbc_button_1);
JButton button = new JButton("#");
GridBagConstraints gbc_button = new GridBagConstraints();
gbc_button.insets = new Insets(0, 0, 5, 5);
gbc_button.gridx = 6;
gbc_button.gridy = 7;
panel_2.add(button, gbc_button);
JButton btnEnter = new JButton("Enter");
GridBagConstraints gbc_btnEnter = new GridBagConstraints();
gbc_btnEnter.insets = new Insets(0, 0, 5, 5);
gbc_btnEnter.gridx = 2;
gbc_btnEnter.gridy = 9;
panel_2.add(btnEnter, gbc_btnEnter);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
}
});
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.insets = new Insets(0, 0, 5, 5);
gbc_btnCancel.gridx = 6;
gbc_btnCancel.gridy = 9;
panel_2.add(btnCancel, gbc_btnCancel);
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lexmodelbuilding.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Provides information about a built in slot type.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BuiltinSlotTypeMetadata" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BuiltinSlotTypeMetadata implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
* </p>
*/
private String signature;
/**
* <p>
* A list of target locales for the slot.
* </p>
*/
private java.util.List<String> supportedLocales;
/**
* <p>
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
* </p>
*
* @param signature
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* <p>
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
* </p>
*
* @return A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
*/
public String getSignature() {
return this.signature;
}
/**
* <p>
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
* </p>
*
* @param signature
* A unique identifier for the built-in slot type. To find the signature for a slot type, see <a href=
* "https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference"
* >Slot Type Reference</a> in the <i>Alexa Skills Kit</i>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public BuiltinSlotTypeMetadata withSignature(String signature) {
setSignature(signature);
return this;
}
/**
* <p>
* A list of target locales for the slot.
* </p>
*
* @return A list of target locales for the slot.
* @see Locale
*/
public java.util.List<String> getSupportedLocales() {
return supportedLocales;
}
/**
* <p>
* A list of target locales for the slot.
* </p>
*
* @param supportedLocales
* A list of target locales for the slot.
* @see Locale
*/
public void setSupportedLocales(java.util.Collection<String> supportedLocales) {
if (supportedLocales == null) {
this.supportedLocales = null;
return;
}
this.supportedLocales = new java.util.ArrayList<String>(supportedLocales);
}
/**
* <p>
* A list of target locales for the slot.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setSupportedLocales(java.util.Collection)} or {@link #withSupportedLocales(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param supportedLocales
* A list of target locales for the slot.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Locale
*/
public BuiltinSlotTypeMetadata withSupportedLocales(String... supportedLocales) {
if (this.supportedLocales == null) {
setSupportedLocales(new java.util.ArrayList<String>(supportedLocales.length));
}
for (String ele : supportedLocales) {
this.supportedLocales.add(ele);
}
return this;
}
/**
* <p>
* A list of target locales for the slot.
* </p>
*
* @param supportedLocales
* A list of target locales for the slot.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Locale
*/
public BuiltinSlotTypeMetadata withSupportedLocales(java.util.Collection<String> supportedLocales) {
setSupportedLocales(supportedLocales);
return this;
}
/**
* <p>
* A list of target locales for the slot.
* </p>
*
* @param supportedLocales
* A list of target locales for the slot.
* @return Returns a reference to this object so that method calls can be chained together.
* @see Locale
*/
public BuiltinSlotTypeMetadata withSupportedLocales(Locale... supportedLocales) {
java.util.ArrayList<String> supportedLocalesCopy = new java.util.ArrayList<String>(supportedLocales.length);
for (Locale value : supportedLocales) {
supportedLocalesCopy.add(value.toString());
}
if (getSupportedLocales() == null) {
setSupportedLocales(supportedLocalesCopy);
} else {
getSupportedLocales().addAll(supportedLocalesCopy);
}
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSignature() != null)
sb.append("Signature: ").append(getSignature()).append(",");
if (getSupportedLocales() != null)
sb.append("SupportedLocales: ").append(getSupportedLocales());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof BuiltinSlotTypeMetadata == false)
return false;
BuiltinSlotTypeMetadata other = (BuiltinSlotTypeMetadata) obj;
if (other.getSignature() == null ^ this.getSignature() == null)
return false;
if (other.getSignature() != null && other.getSignature().equals(this.getSignature()) == false)
return false;
if (other.getSupportedLocales() == null ^ this.getSupportedLocales() == null)
return false;
if (other.getSupportedLocales() != null && other.getSupportedLocales().equals(this.getSupportedLocales()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSignature() == null) ? 0 : getSignature().hashCode());
hashCode = prime * hashCode + ((getSupportedLocales() == null) ? 0 : getSupportedLocales().hashCode());
return hashCode;
}
@Override
public BuiltinSlotTypeMetadata clone() {
try {
return (BuiltinSlotTypeMetadata) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.lexmodelbuilding.model.transform.BuiltinSlotTypeMetadataMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.classic.spi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.MDC;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.net.LoggingEventPreSerializationTransformer;
import ch.qos.logback.core.spi.PreSerializationTransformer;
public class LoggingEventSerializationTest {
LoggerContext lc;
Logger logger;
ByteArrayOutputStream bos;
ObjectOutputStream oos;
ObjectInputStream inputStream;
PreSerializationTransformer<ILoggingEvent> pst = new LoggingEventPreSerializationTransformer();
@Before
public void setUp() throws Exception {
lc = new LoggerContext();
lc.setName("testContext");
logger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
// create the byte output stream
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
}
@After
public void tearDown() throws Exception {
lc = null;
logger = null;
oos.close();
}
@Test
public void smoke() throws Exception {
ILoggingEvent event = createLoggingEvent();
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
}
@Test
public void context() throws Exception {
lc.putProperty("testKey", "testValue");
ILoggingEvent event = createLoggingEvent();
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
assertNotNull(remoteEvent.getLoggerName());
assertEquals(Logger.ROOT_LOGGER_NAME, remoteEvent.getLoggerName());
LoggerContextVO loggerContextRemoteView = remoteEvent.getLoggerContextVO();
assertNotNull(loggerContextRemoteView);
assertEquals("testContext", loggerContextRemoteView.getName());
Map<String, String> props = loggerContextRemoteView.getPropertyMap();
assertNotNull(props);
assertEquals("testValue", props.get("testKey"));
}
@Test
public void MDC() throws Exception {
MDC.put("key", "testValue");
ILoggingEvent event = createLoggingEvent();
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
Map<String, String> MDCPropertyMap = remoteEvent.getMDCPropertyMap();
assertEquals("testValue", MDCPropertyMap.get("key"));
}
@Test
public void updatedMDC() throws Exception {
MDC.put("key", "testValue");
ILoggingEvent event1 = createLoggingEvent();
Serializable s1 = pst.transform(event1);
oos.writeObject(s1);
MDC.put("key", "updatedTestValue");
ILoggingEvent event2 = createLoggingEvent();
Serializable s2 = pst.transform(event2);
oos.writeObject(s2);
// create the input stream based on the ouput stream
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
inputStream = new ObjectInputStream(bis);
// skip over one object
inputStream.readObject();
ILoggingEvent remoteEvent2 = (ILoggingEvent) inputStream.readObject();
// We observe the second logging event. It should provide us with
// the updated MDC property.
Map<String, String> MDCPropertyMap = remoteEvent2.getMDCPropertyMap();
assertEquals("updatedTestValue", MDCPropertyMap.get("key"));
}
@Test
public void nonSerializableParameters() throws Exception {
LoggingEvent event = createLoggingEvent();
LuckyCharms lucky0 = new LuckyCharms(0);
event.setArgumentArray(new Object[] { lucky0, null });
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
Object[] aa = remoteEvent.getArgumentArray();
assertNotNull(aa);
assertEquals(2, aa.length);
assertEquals("LC(0)", aa[0]);
assertNull(aa[1]);
}
@Test
public void _Throwable() throws Exception {
LoggingEvent event = createLoggingEvent();
Throwable throwable = new Throwable("just testing");
ThrowableProxy tp = new ThrowableProxy(throwable);
event.setThrowableProxy(tp);
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
}
@Test
public void extendendeThrowable() throws Exception {
LoggingEvent event = createLoggingEvent();
Throwable throwable = new Throwable("just testing");
ThrowableProxy tp = new ThrowableProxy(throwable);
event.setThrowableProxy(tp);
tp.calculatePackagingData();
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
}
@Test
public void serializeLargeArgs() throws Exception {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 100000; i++) {
buffer.append("X");
}
String largeString = buffer.toString();
Object[] argArray = new Object[] { new LuckyCharms(2), largeString };
LoggingEvent event = createLoggingEvent();
event.setArgumentArray(argArray);
ILoggingEvent remoteEvent = writeAndRead(event);
checkForEquality(event, remoteEvent);
Object[] aa = remoteEvent.getArgumentArray();
assertNotNull(aa);
assertEquals(2, aa.length);
String stringBack = (String) aa[1];
assertEquals(largeString, stringBack);
}
private LoggingEvent createLoggingEvent() {
return new LoggingEvent(this.getClass().getName(), logger,
Level.DEBUG, "test message", null, null);
}
private void checkForEquality(ILoggingEvent original,
ILoggingEvent afterSerialization) {
assertEquals(original.getLevel(), afterSerialization.getLevel());
assertEquals(original.getFormattedMessage(), afterSerialization
.getFormattedMessage());
assertEquals(original.getMessage(), afterSerialization.getMessage());
System.out.println();
ThrowableProxyVO witness = ThrowableProxyVO.build(original
.getThrowableProxy());
assertEquals(witness, afterSerialization.getThrowableProxy());
}
private ILoggingEvent writeAndRead(ILoggingEvent event) throws IOException,
ClassNotFoundException {
Serializable ser = pst.transform(event);
oos.writeObject(ser);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
inputStream = new ObjectInputStream(bis);
return (ILoggingEvent) inputStream.readObject();
}
}
| |
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 2.0 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
** Processing integration: Andres Colubri, February 2012
*/
package processing.opengl.tess;
class TessMono {
/* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region
* (what else would it do??) The region must consist of a single
* loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this
* case means that any vertical line intersects the interior of the
* region in a single interval.
*
* Tessellation consists of adding interior edges (actually pairs of
* half-edges), to split the region into non-overlapping triangles.
*
* The basic idea is explained in Preparata and Shamos (which I don''t
* have handy right now), although their implementation is more
* complicated than this one. The are two edge chains, an upper chain
* and a lower chain. We process all vertices from both chains in order,
* from right to left.
*
* The algorithm ensures that the following invariant holds after each
* vertex is processed: the untessellated region consists of two
* chains, where one chain (say the upper) is a single edge, and
* the other chain is concave. The left vertex of the single edge
* is always to the left of all vertices in the concave chain.
*
* Each step consists of adding the rightmost unprocessed vertex to one
* of the two chains, and forming a fan of triangles from the rightmost
* of two chain endpoints. Determining whether we can add each triangle
* to the fan is a simple orientation test. By making the fan as large
* as possible, we restore the invariant (check it yourself).
*/
static boolean __gl_meshTessellateMonoRegion(GLUface face, boolean avoidDegenerateTris) {
GLUhalfEdge up, lo;
/* All edges are oriented CCW around the boundary of the region.
* First, find the half-edge whose origin vertex is rightmost.
* Since the sweep goes from left to right, face->anEdge should
* be close to the edge we want.
*/
up = face.anEdge;
assert (up.Lnext != up && up.Lnext.Lnext != up);
for (; Geom.VertLeq(up.Sym.Org, up.Org); up = up.Onext.Sym)
;
for (; Geom.VertLeq(up.Org, up.Sym.Org); up = up.Lnext)
;
lo = up.Onext.Sym;
boolean mustConnect = false; // hack for avoidDegenerateTris
while (up.Lnext != lo) {
if (avoidDegenerateTris && !mustConnect) {
// Skip over regions where several vertices are collinear,
// to try to avoid producing degenerate (zero-area) triangles
//
// The "mustConnect" flag is a hack to try to avoid
// skipping too large regions and causing incorrect
// triangulations. This entire modification is overall
// not robust and needs more work
if (Geom.EdgeCos(lo.Lnext.Org, lo.Org, lo.Lnext.Lnext.Org) <= -Geom.ONE_MINUS_EPSILON) {
// Lines around lo
do {
lo = lo.Onext.Sym;
mustConnect = true;
} while (up.Lnext != lo &&
Geom.EdgeCos(lo.Lnext.Org, lo.Org, lo.Lnext.Lnext.Org) <= -Geom.ONE_MINUS_EPSILON);
} else if (Geom.EdgeCos(up.Onext.Sym.Org, up.Org, up.Onext.Sym.Onext.Sym.Org) <= -Geom.ONE_MINUS_EPSILON) {
// Lines around up
do {
up = up.Lnext;
mustConnect = true;
} while (up.Lnext != lo &&
Geom.EdgeCos(up.Onext.Sym.Org, up.Org, up.Onext.Sym.Onext.Sym.Org) <= -Geom.ONE_MINUS_EPSILON);
}
if (up.Lnext == lo)
break;
}
if (Geom.VertLeq(up.Sym.Org, lo.Org)) {
/* up.Sym.Org is on the left. It is safe to form triangles from lo.Org.
* The EdgeGoesLeft test guarantees progress even when some triangles
* are CW, given that the upper and lower chains are truly monotone.
*/
while (lo.Lnext != up && (Geom.EdgeGoesLeft(lo.Lnext)
|| Geom.EdgeSign(lo.Org, lo.Sym.Org, lo.Lnext.Sym.Org) <= 0)) {
GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(lo.Lnext, lo);
mustConnect = false;
if (tempHalfEdge == null) return false;
lo = tempHalfEdge.Sym;
}
lo = lo.Onext.Sym;
} else {
/* lo.Org is on the left. We can make CCW triangles from up.Sym.Org. */
while (lo.Lnext != up && (Geom.EdgeGoesRight(up.Onext.Sym)
|| Geom.EdgeSign(up.Sym.Org, up.Org, up.Onext.Sym.Org) >= 0)) {
GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(up, up.Onext.Sym);
mustConnect = false;
if (tempHalfEdge == null) return false;
up = tempHalfEdge.Sym;
}
up = up.Lnext;
}
}
/* Now lo.Org == up.Sym.Org == the leftmost vertex. The remaining region
* can be tessellated in a fan from this leftmost vertex.
*/
assert (lo.Lnext != up);
while (lo.Lnext.Lnext != up) {
GLUhalfEdge tempHalfEdge = Mesh.__gl_meshConnect(lo.Lnext, lo);
if (tempHalfEdge == null) return false;
lo = tempHalfEdge.Sym;
}
return true;
}
/* __gl_meshTessellateInterior( mesh ) tessellates each region of
* the mesh which is marked "inside" the polygon. Each such region
* must be monotone.
*/
public static boolean __gl_meshTessellateInterior(GLUmesh mesh, boolean avoidDegenerateTris) {
GLUface f, next;
/*LINTED*/
for (f = mesh.fHead.next; f != mesh.fHead; f = next) {
/* Make sure we don''t try to tessellate the new triangles. */
next = f.next;
if (f.inside) {
if (!__gl_meshTessellateMonoRegion(f, avoidDegenerateTris)) return false;
}
}
return true;
}
/* __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces
* which are not marked "inside" the polygon. Since further mesh operations
* on NULL faces are not allowed, the main purpose is to clean up the
* mesh so that exterior loops are not represented in the data structure.
*/
public static void __gl_meshDiscardExterior(GLUmesh mesh) {
GLUface f, next;
/*LINTED*/
for (f = mesh.fHead.next; f != mesh.fHead; f = next) {
/* Since f will be destroyed, save its next pointer. */
next = f.next;
if (!f.inside) {
Mesh.__gl_meshZapFace(f);
}
}
}
// private static final int MARKED_FOR_DELETION = 0x7fffffff;
/* __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the
* winding numbers on all edges so that regions marked "inside" the
* polygon have a winding number of "value", and regions outside
* have a winding number of 0.
*
* If keepOnlyBoundary is TRUE, it also deletes all edges which do not
* separate an interior region from an exterior one.
*/
public static boolean __gl_meshSetWindingNumber(GLUmesh mesh, int value, boolean keepOnlyBoundary) {
GLUhalfEdge e, eNext;
for (e = mesh.eHead.next; e != mesh.eHead; e = eNext) {
eNext = e.next;
if (e.Sym.Lface.inside != e.Lface.inside) {
/* This is a boundary edge (one side is interior, one is exterior). */
e.winding = (e.Lface.inside) ? value : -value;
} else {
/* Both regions are interior, or both are exterior. */
if (!keepOnlyBoundary) {
e.winding = 0;
} else {
if (!Mesh.__gl_meshDelete(e)) return false;
}
}
}
return true;
}
}
| |
package com.aichifan.app4myqa.vagerview;
/**
* Created by mic on 2016/8/29.
*/
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import com.aichifan.app4myqa.R;
import com.aichifan.app4myqa.adapter.NiceSpinnerAdapter;
import com.aichifan.app4myqa.adapter.NiceSpinnerAdapterWrapper;
import com.aichifan.app4myqa.adapter.NiceSpinnerBaseAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author angelo.marchesin
*/
@SuppressWarnings("unused")
public class NiceSpinner extends TextView {
private static final int MAX_LEVEL = 10000;
private static final int DEFAULT_ELEVATION = 16;
private static final String INSTANCE_STATE = "instance_state";
private static final String SELECTED_INDEX = "selected_index";
private static final String IS_POPUP_SHOWING = "is_popup_showing";
private int selectedIndex;
private Drawable drawable;
private PopupWindow popupWindow;
private ListView listView;
private NiceSpinnerBaseAdapter adapter;
private AdapterView.OnItemClickListener onItemClickListener;
private AdapterView.OnItemSelectedListener onItemSelectedListener;
private boolean isArrowHide;
private int textColor;
private int backgroundSelector;
private List<String> dates;
private EditText editText;
private List<String> mListTitle;
private boolean flag = false;
@SuppressWarnings("ConstantConditions")
public NiceSpinner(Context context) {
super(context);
init(context, null);
}
public NiceSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public NiceSpinner(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@Override
public Parcelable onSaveInstanceState() {
Bundle bundle = new Bundle();
bundle.putParcelable(INSTANCE_STATE, super.onSaveInstanceState());
bundle.putInt(SELECTED_INDEX, selectedIndex);
if (popupWindow != null) {
bundle.putBoolean(IS_POPUP_SHOWING, popupWindow.isShowing());
dismissDropDown();
}
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable savedState) {
if (savedState instanceof Bundle) {
Bundle bundle = (Bundle) savedState;
selectedIndex = bundle.getInt(SELECTED_INDEX);
if (adapter != null) {
setText(adapter.getItemInDataset(selectedIndex).toString());
adapter.notifyItemSelected(selectedIndex);
}
if (bundle.getBoolean(IS_POPUP_SHOWING)) {
if (popupWindow != null) {
// Post the show request into the looper to avoid bad token exception
post(new Runnable() {
@Override
public void run() {
showDropDown();
}
});
}
}
savedState = bundle.getParcelable(INSTANCE_STATE);
}
super.onRestoreInstanceState(savedState);
}
private void getmDataSub(List<String> mDataSubs, String data) {
int length = mDataSubs.size();
for (int i = 0; i < length; ++i) {
if (mDataSubs.get(i).contains(data)) {
// if (flag){
// dates.clear();
// }
// flag = false;
flag = true;
dates.add(mDataSubs.get(i));
}
}
}
private void huiFu(List<String> mDataSubs) {
int length = mDataSubs.size();
for (int i = 0; i < length; ++i) {
String data = mDataSubs.get(i);
dates.add(data);
}
flag = true;
}
private void init(Context context, AttributeSet attrs) {
Resources resources = getResources();
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NiceSpinner);
int defaultPadding = resources.getDimensionPixelSize(R.dimen.one_and_a_half_grid_unit);
setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
setPadding(resources.getDimensionPixelSize(R.dimen.three_grid_unit), defaultPadding,
defaultPadding,
defaultPadding);
setClickable(true);
backgroundSelector = typedArray.getResourceId(R.styleable
.NiceSpinner_backgroundSelector,
R.drawable.selector);
setBackgroundResource(backgroundSelector);
textColor = typedArray.getColor(R.styleable.NiceSpinner_textTint, 0XFF000000);
setTextColor(textColor);
View view = View.inflate(context, R.layout.view_main, null);
editText = (EditText) view.findViewById(R.id.edit);
listView = (ListView) view.findViewById(R.id.list);
// listView = new ListView(context);
// Set the spinner's id into the listview to make it pretend to be the right parent in
// onItemClick
listView.setId(getId());
listView.setDivider(null);
listView.setItemsCanFocus(true);
//hide vertical and horizontal scrollbars
listView.setVerticalScrollBarEnabled(false);
listView.setHorizontalScrollBarEnabled(false);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position >= selectedIndex && position < adapter.getCount()) {
position++;
}
// Need to set selected index before calling listeners or getSelectedIndex()
// can be
// reported incorrectly due to race conditions.
selectedIndex = position;
if (onItemClickListener != null) {
onItemClickListener.onItemClick(parent, view, position, id);
}
if (onItemSelectedListener != null) {
onItemSelectedListener.onItemSelected(parent, view, position, id);
}
adapter.notifyItemSelected(position);
setText(adapter.getItemInDataset(position).toString());
dismissDropDown();
}
});
popupWindow = new PopupWindow(context);
// popupWindow.setContentView(editText);
// popupWindow.setContentView(listView);
popupWindow.setContentView(view);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
popupWindow.setElevation(DEFAULT_ELEVATION);
popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable
.spinner_drawable));
} else {
popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable
.drop_down_shadow));
}
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
if (!isArrowHide) {
animateArrow(false);
}
}
});
isArrowHide = typedArray.getBoolean(R.styleable.NiceSpinner_hideArrow, false);
if (!isArrowHide) {
Drawable basicDrawable = ContextCompat.getDrawable(context, R.drawable.arrow);
int resId = typedArray.getColor(R.styleable.NiceSpinner_arrowTint, -1);
if (basicDrawable != null) {
drawable = DrawableCompat.wrap(basicDrawable);
if (resId != -1) {
DrawableCompat.setTint(drawable, resId);
}
}
setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
}
typedArray.recycle();
}
public int getSelectedIndex() {
return selectedIndex;
}
/**
* Set the default spinner item using its index
*
* @param position the item's position
*/
public void setSelectedIndex(int position) {
if (adapter != null) {
if (position >= 0 && position <= adapter.getCount()) {
adapter.notifyItemSelected(position);
selectedIndex = position;
setText(adapter.getItemInDataset(position).toString());
} else {
throw new IllegalArgumentException("Position must be lower than adapter " +
"count!");
}
}
}
public void addOnItemClickListener(@NonNull AdapterView.OnItemClickListener
onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public void setOnItemSelectedListener(@NonNull AdapterView.OnItemSelectedListener
onItemSelectedListener) {
this.onItemSelectedListener = onItemSelectedListener;
}
public <T> void attachDataSource(@NonNull List<T> dataset) {
dates = (List<String>) dataset;
mListTitle = new ArrayList<String>(dates);
adapter = new NiceSpinnerAdapter<>(getContext(), dates, textColor, backgroundSelector);
setAdapterInternal(adapter);
}
public void setAdapter(@NonNull ListAdapter adapter) {
this.adapter = new NiceSpinnerAdapterWrapper(getContext(), adapter, textColor,
backgroundSelector);
setAdapterInternal(this.adapter);
}
private void setAdapterInternal(@NonNull final NiceSpinnerBaseAdapter adapter) {
// If the adapter needs to be settled again, ensure to reset the selected index as well
selectedIndex = 0;
listView.setAdapter(adapter);
setText(adapter.getItemInDataset(selectedIndex).toString());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
String data = editable.toString();
// System.out.println(mListTitle.size());
if (TextUtils.isEmpty(data)) {
dates.clear();
huiFu(mListTitle);
}else {
dates.clear();
getmDataSub(mListTitle, data);
}
adapter.notifyDataSetChanged();
if(flag)
setSelectedIndex(0);
flag = false;
// selectedIndex = 0;
// setText(adapter.getItemInDataset(selectedIndex).toString());
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
popupWindow.setWidth(MeasureSpec.getSize(widthMeasureSpec));
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(@NonNull MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (!popupWindow.isShowing()) {
showDropDown();
} else {
dismissDropDown();
}
}
return super.onTouchEvent(event);
}
private void animateArrow(boolean shouldRotateUp) {
int start = shouldRotateUp ? 0 : MAX_LEVEL;
int end = shouldRotateUp ? MAX_LEVEL : 0;
ObjectAnimator animator = ObjectAnimator.ofInt(drawable, "level", start, end);
animator.setInterpolator(new LinearOutSlowInInterpolator());
animator.start();
}
public void dismissDropDown() {
if (!isArrowHide) {
animateArrow(false);
}
popupWindow.dismiss();
}
public void showDropDown() {
if (!isArrowHide) {
animateArrow(true);
}
popupWindow.showAsDropDown(this);
}
public void setTintColor(@ColorRes int resId) {
if (drawable != null && !isArrowHide) {
DrawableCompat.setTint(drawable, ContextCompat.getColor(getContext(), resId));
}
}
}
| |
/*
* Copyright (c) 2016-2021 VMware Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.core.publisher;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import reactor.core.CoreSubscriber;
import reactor.core.Scannable;
import reactor.test.subscriber.AssertSubscriber;
import static org.assertj.core.api.Assertions.assertThat;
import static reactor.core.publisher.Sinks.EmitFailureHandler.FAIL_FAST;
public class FluxJoinTest {
final BiFunction<Integer, Integer, Integer> add = (t1, t2) -> t1 + t2;
<T> Function<Integer, Flux<T>> just(final Flux<T> publisher) {
return t1 -> publisher;
}
@Test
public void normal1() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> m =
source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
source1.emitNext(2, FAIL_FAST);
source1.emitNext(4, FAIL_FAST);
source2.emitNext(16, FAIL_FAST);
source2.emitNext(32, FAIL_FAST);
source2.emitNext(64, FAIL_FAST);
source1.emitComplete(FAIL_FAST);
source2.emitComplete(FAIL_FAST);
ts.assertValues(17, 18, 20, 33, 34, 36, 65, 66, 68)
.assertComplete()
.assertNoError();
}
@Test
public void normal1WithDuration() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> duration1 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> m = source1.asFlux().join(source2.asFlux(), just(duration1.asFlux()), just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
source1.emitNext(2, FAIL_FAST);
source2.emitNext(16, FAIL_FAST);
duration1.emitNext(1, FAIL_FAST);
source1.emitNext(4, FAIL_FAST);
source1.emitNext(8, FAIL_FAST);
source1.emitComplete(FAIL_FAST);
source2.emitComplete(FAIL_FAST);
ts.assertValues(17, 18, 20, 24)
.assertComplete()
.assertNoError();
}
@Test
public void normal2() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> m =
source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
source1.emitNext(2, FAIL_FAST);
source1.emitComplete(FAIL_FAST);
source2.emitNext(16, FAIL_FAST);
source2.emitNext(32, FAIL_FAST);
source2.emitNext(64, FAIL_FAST);
source2.emitComplete(FAIL_FAST);
ts.assertValues(17, 18, 33, 34, 65, 66)
.assertComplete()
.assertNoError();
}
@Test
public void leftThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> m =
source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(Flux.never()), add);
m.subscribe(ts);
source2.emitNext(1, FAIL_FAST);
source1.emitError(new RuntimeException("Forced failure"), FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void rightThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> m =
source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
source2.emitError(new RuntimeException("Forced failure"), FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void leftDurationThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> duration1 = Flux.error(new RuntimeException("Forced failure"));
Flux<Integer> m = source1.asFlux().join(source2.asFlux(), just(duration1), just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void rightDurationThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Flux<Integer> duration1 = Flux.error(new RuntimeException("Forced failure"));
Flux<Integer> m = source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(duration1), add);
m.subscribe(ts);
source2.emitNext(1, FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void leftDurationSelectorThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Function<Integer, Flux<Integer>> fail = t1 -> {
throw new RuntimeException("Forced failure");
};
Flux<Integer> m = source1.asFlux().join(source2.asFlux(), fail, just(Flux.never()), add);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void rightDurationSelectorThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
Function<Integer, Flux<Integer>> fail = t1 -> {
throw new RuntimeException("Forced failure");
};
Flux<Integer> m = source1.asFlux().join(source2.asFlux(), just(Flux.never()), fail, add);
m.subscribe(ts);
source2.emitNext(1, FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void resultSelectorThrows() {
AssertSubscriber<Object> ts = AssertSubscriber.create();
Sinks.Many<Integer> source1 = Sinks.unsafe().many().multicast().directBestEffort();
Sinks.Many<Integer> source2 = Sinks.unsafe().many().multicast().directBestEffort();
BiFunction<Integer, Integer, Integer> fail = (t1, t2) -> {
throw new RuntimeException("Forced failure");
};
Flux<Integer> m =
source1.asFlux().join(source2.asFlux(), just(Flux.never()), just(Flux.never()), fail);
m.subscribe(ts);
source1.emitNext(1, FAIL_FAST);
source2.emitNext(2, FAIL_FAST);
ts.assertErrorMessage("Forced failure")
.assertNotComplete()
.assertNoValues();
}
@Test
public void scanOperator(){
Flux<Integer> parent = Flux.just(1);
FluxJoin<Integer, Integer, Integer, Integer, Integer> test = new FluxJoin<>(parent, Flux.just(2), just(Flux.just(3)), just(Flux.just(4)), add);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(-1);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanSubscription() {
CoreSubscriber<String> actual = new LambdaSubscriber<>(null, e -> {}, null, sub -> sub.request(100));
FluxJoin.JoinSubscription<String, String, String, String, String> test =
new FluxJoin.JoinSubscription<>(actual,
s -> Mono.just(s),
s -> Mono.just(s),
(l, r) -> l);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
test.request(123);
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(123);
test.queue.add(1);
test.queue.add(5);
assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
test.active = 0;
assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
test.error = new IllegalStateException("boom");
assertThat(test.scan(Scannable.Attr.ERROR)).isSameAs(test.error);
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
}
| |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ads.googleads.v10.resources;
import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class AdGroupSimulationName implements ResourceName {
private static final PathTemplate
CUSTOMER_ID_AD_GROUP_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE =
PathTemplate.createWithoutUrlEncoding(
"customers/{customer_id}/adGroupSimulations/{ad_group_id}~{type}~{modification_method}~{start_date}~{end_date}");
private volatile Map<String, String> fieldValuesMap;
private final String customerId;
private final String adGroupId;
private final String type;
private final String modificationMethod;
private final String startDate;
private final String endDate;
@Deprecated
protected AdGroupSimulationName() {
customerId = null;
adGroupId = null;
type = null;
modificationMethod = null;
startDate = null;
endDate = null;
}
private AdGroupSimulationName(Builder builder) {
customerId = Preconditions.checkNotNull(builder.getCustomerId());
adGroupId = Preconditions.checkNotNull(builder.getAdGroupId());
type = Preconditions.checkNotNull(builder.getType());
modificationMethod = Preconditions.checkNotNull(builder.getModificationMethod());
startDate = Preconditions.checkNotNull(builder.getStartDate());
endDate = Preconditions.checkNotNull(builder.getEndDate());
}
public String getCustomerId() {
return customerId;
}
public String getAdGroupId() {
return adGroupId;
}
public String getType() {
return type;
}
public String getModificationMethod() {
return modificationMethod;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public static Builder newBuilder() {
return new Builder();
}
public Builder toBuilder() {
return new Builder(this);
}
public static AdGroupSimulationName of(
String customerId,
String adGroupId,
String type,
String modificationMethod,
String startDate,
String endDate) {
return newBuilder()
.setCustomerId(customerId)
.setAdGroupId(adGroupId)
.setType(type)
.setModificationMethod(modificationMethod)
.setStartDate(startDate)
.setEndDate(endDate)
.build();
}
public static String format(
String customerId,
String adGroupId,
String type,
String modificationMethod,
String startDate,
String endDate) {
return newBuilder()
.setCustomerId(customerId)
.setAdGroupId(adGroupId)
.setType(type)
.setModificationMethod(modificationMethod)
.setStartDate(startDate)
.setEndDate(endDate)
.build()
.toString();
}
public static AdGroupSimulationName parse(String formattedString) {
if (formattedString.isEmpty()) {
return null;
}
Map<String, String> matchMap =
CUSTOMER_ID_AD_GROUP_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.validatedMatch(
formattedString, "AdGroupSimulationName.parse: formattedString not in valid format");
return of(
matchMap.get("customer_id"),
matchMap.get("ad_group_id"),
matchMap.get("type"),
matchMap.get("modification_method"),
matchMap.get("start_date"),
matchMap.get("end_date"));
}
public static List<AdGroupSimulationName> parseList(List<String> formattedStrings) {
List<AdGroupSimulationName> list = new ArrayList<>(formattedStrings.size());
for (String formattedString : formattedStrings) {
list.add(parse(formattedString));
}
return list;
}
public static List<String> toStringList(List<AdGroupSimulationName> values) {
List<String> list = new ArrayList<>(values.size());
for (AdGroupSimulationName value : values) {
if (value == null) {
list.add("");
} else {
list.add(value.toString());
}
}
return list;
}
public static boolean isParsableFrom(String formattedString) {
return CUSTOMER_ID_AD_GROUP_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.matches(
formattedString);
}
@Override
public Map<String, String> getFieldValuesMap() {
if (fieldValuesMap == null) {
synchronized (this) {
if (fieldValuesMap == null) {
ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
if (customerId != null) {
fieldMapBuilder.put("customer_id", customerId);
}
if (adGroupId != null) {
fieldMapBuilder.put("ad_group_id", adGroupId);
}
if (type != null) {
fieldMapBuilder.put("type", type);
}
if (modificationMethod != null) {
fieldMapBuilder.put("modification_method", modificationMethod);
}
if (startDate != null) {
fieldMapBuilder.put("start_date", startDate);
}
if (endDate != null) {
fieldMapBuilder.put("end_date", endDate);
}
fieldValuesMap = fieldMapBuilder.build();
}
}
}
return fieldValuesMap;
}
public String getFieldValue(String fieldName) {
return getFieldValuesMap().get(fieldName);
}
@Override
public String toString() {
return CUSTOMER_ID_AD_GROUP_ID_TYPE_MODIFICATION_METHOD_START_DATE_END_DATE.instantiate(
"customer_id",
customerId,
"ad_group_id",
adGroupId,
"type",
type,
"modification_method",
modificationMethod,
"start_date",
startDate,
"end_date",
endDate);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o != null || getClass() == o.getClass()) {
AdGroupSimulationName that = ((AdGroupSimulationName) o);
return Objects.equals(this.customerId, that.customerId)
&& Objects.equals(this.adGroupId, that.adGroupId)
&& Objects.equals(this.type, that.type)
&& Objects.equals(this.modificationMethod, that.modificationMethod)
&& Objects.equals(this.startDate, that.startDate)
&& Objects.equals(this.endDate, that.endDate);
}
return false;
}
@Override
public int hashCode() {
int h = 1;
h *= 1000003;
h ^= Objects.hashCode(customerId);
h *= 1000003;
h ^= Objects.hashCode(adGroupId);
h *= 1000003;
h ^= Objects.hashCode(type);
h *= 1000003;
h ^= Objects.hashCode(modificationMethod);
h *= 1000003;
h ^= Objects.hashCode(startDate);
h *= 1000003;
h ^= Objects.hashCode(endDate);
return h;
}
/**
* Builder for
* customers/{customer_id}/adGroupSimulations/{ad_group_id}~{type}~{modification_method}~{start_date}~{end_date}.
*/
public static class Builder {
private String customerId;
private String adGroupId;
private String type;
private String modificationMethod;
private String startDate;
private String endDate;
protected Builder() {}
public String getCustomerId() {
return customerId;
}
public String getAdGroupId() {
return adGroupId;
}
public String getType() {
return type;
}
public String getModificationMethod() {
return modificationMethod;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public Builder setCustomerId(String customerId) {
this.customerId = customerId;
return this;
}
public Builder setAdGroupId(String adGroupId) {
this.adGroupId = adGroupId;
return this;
}
public Builder setType(String type) {
this.type = type;
return this;
}
public Builder setModificationMethod(String modificationMethod) {
this.modificationMethod = modificationMethod;
return this;
}
public Builder setStartDate(String startDate) {
this.startDate = startDate;
return this;
}
public Builder setEndDate(String endDate) {
this.endDate = endDate;
return this;
}
private Builder(AdGroupSimulationName adGroupSimulationName) {
this.customerId = adGroupSimulationName.customerId;
this.adGroupId = adGroupSimulationName.adGroupId;
this.type = adGroupSimulationName.type;
this.modificationMethod = adGroupSimulationName.modificationMethod;
this.startDate = adGroupSimulationName.startDate;
this.endDate = adGroupSimulationName.endDate;
}
public AdGroupSimulationName build() {
return new AdGroupSimulationName(this);
}
}
}
| |
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.admin.client.resource;
import org.jboss.resteasy.annotations.cache.NoCache;
import org.keycloak.representations.adapters.action.GlobalRequestResult;
import org.keycloak.representations.idm.AdminEventRepresentation;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.PartialImportRepresentation;
import org.keycloak.representations.idm.RealmEventsConfigRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @author rodrigo.sasaki@icarros.com.br
*/
public interface RealmResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
RealmRepresentation toRepresentation();
@PUT
@Consumes(MediaType.APPLICATION_JSON)
void update(RealmRepresentation realmRepresentation);
@Path("clients")
ClientsResource clients();
@Path("client-templates")
ClientTemplatesResource clientTemplates();
@Path("client-description-converter")
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
@Produces(MediaType.APPLICATION_JSON)
ClientRepresentation convertClientDescription(String description);
@Path("users")
UsersResource users();
@Path("roles")
RolesResource roles();
@Path("roles-by-id")
RoleByIdResource rolesById();
@Path("groups")
GroupsResource groups();
@DELETE
@Path("events")
void clearEvents();
@GET
@Path("events")
@Produces(MediaType.APPLICATION_JSON)
List<EventRepresentation> getEvents();
@Path("events")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<EventRepresentation> getEvents(@QueryParam("type") List<String> types, @QueryParam("client") String client,
@QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo,
@QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult,
@QueryParam("max") Integer maxResults);
@DELETE
@Path("admin-events")
void clearAdminEvents();
@GET
@Path("admin-events")
@Produces(MediaType.APPLICATION_JSON)
List<AdminEventRepresentation> getAdminEvents();
@GET
@Path("admin-events")
@Produces(MediaType.APPLICATION_JSON)
List<AdminEventRepresentation> getAdminEvents(@QueryParam("operationTypes") List<String> operationTypes, @QueryParam("authRealm") String authRealm, @QueryParam("authClient") String authClient,
@QueryParam("authUser") String authUser, @QueryParam("authIpAddress") String authIpAddress,
@QueryParam("resourcePath") String resourcePath, @QueryParam("dateFrom") String dateFrom,
@QueryParam("dateTo") String dateTo, @QueryParam("first") Integer firstResult,
@QueryParam("max") Integer maxResults);
@GET
@Path("events/config")
@Produces(MediaType.APPLICATION_JSON)
public RealmEventsConfigRepresentation getRealmEventsConfig();
@PUT
@Path("events/config")
@Consumes(MediaType.APPLICATION_JSON)
public void updateRealmEventsConfig(RealmEventsConfigRepresentation rep);
@GET
@Path("group-by-path/{path: .*}")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public GroupRepresentation getGroupByPath(@PathParam("path") String path);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("default-groups")
public List<GroupRepresentation> getDefaultGroups();
@PUT
@Path("default-groups/{groupId}")
public void addDefaultGroup(@PathParam("groupId") String groupId);
@DELETE
@Path("default-groups/{groupId}")
public void removeDefaultGroup(@PathParam("groupId") String groupId);
@Path("identity-provider")
IdentityProvidersResource identityProviders();
@DELETE
void remove();
@Path("client-session-stats")
@GET
List<Map<String, String>> getClientSessionStats();
@Path("clients-initial-access")
ClientInitialAccessResource clientInitialAccess();
@Path("client-registration-policy")
ClientRegistrationPolicyResource clientRegistrationPolicy();
@Path("partialImport")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response partialImport(PartialImportRepresentation rep);
@Path("partial-export")
@POST
@Produces(MediaType.APPLICATION_JSON)
RealmRepresentation partialExport(@QueryParam("exportGroupsAndRoles") Boolean exportGroupsAndRoles,
@QueryParam("exportClients") Boolean exportClients);
@Path("authentication")
@Consumes(MediaType.APPLICATION_JSON)
AuthenticationManagementResource flows();
@Path("attack-detection")
AttackDetectionResource attackDetection();
@Path("testLDAPConnection")
@GET
@NoCache
Response testLDAPConnection(@QueryParam("action") String action, @QueryParam("connectionUrl") String connectionUrl,
@QueryParam("bindDn") String bindDn, @QueryParam("bindCredential") String bindCredential,
@QueryParam("useTruststoreSpi") String useTruststoreSpi, @QueryParam("connectionTimeout") String connectionTimeout);
@Path("testSMTPConnection/{config}")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
Response testSMTPConnection(final @PathParam("config") String config) throws Exception;
@Path("clear-realm-cache")
@POST
void clearRealmCache();
@Path("clear-user-cache")
@POST
void clearUserCache();
@Path("clear-keys-cache")
@POST
void clearKeysCache();
@Path("push-revocation")
@POST
@Produces(MediaType.APPLICATION_JSON)
GlobalRequestResult pushRevocation();
@Path("logout-all")
@POST
@Produces(MediaType.APPLICATION_JSON)
GlobalRequestResult logoutAll();
@Path("sessions/{session}")
@DELETE
void deleteSession(@PathParam("session") String sessionId);
@Path("components")
ComponentsResource components();
@Path("user-storage")
UserStorageProviderResource userStorage();
@Path("keys")
KeyResource keys();
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.enumConstant;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrEnumConstantInitializer;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyResolveResultImpl;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.GrFieldImpl;
import org.jetbrains.plugins.groovy.lang.psi.stubs.GrFieldStub;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
import static org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.MODIFIER_LIST;
/**
* @author: Dmitry.Krasilschikov
* @date: 06.04.2007
*/
public class GrEnumConstantImpl extends GrFieldImpl implements GrEnumConstant {
private final MyReference myReference = new MyReference();
public GrEnumConstantImpl(@NotNull ASTNode node) {
super(node);
}
public GrEnumConstantImpl(GrFieldStub stub) {
super(stub, GroovyElementTypes.ENUM_CONSTANT);
}
public String toString() {
return "Enumeration constant";
}
@Nullable
@Override
public GrModifierList getModifierList() {
return getStubOrPsiChild(MODIFIER_LIST);
}
@Override
public boolean hasModifierProperty(@NonNls @NotNull String property) {
if (property.equals(PsiModifier.STATIC)) return true;
if (property.equals(PsiModifier.PUBLIC)) return true;
if (property.equals(PsiModifier.FINAL)) return true;
return false;
}
@Override
public void accept(@NotNull GroovyElementVisitor visitor) {
visitor.visitEnumConstant(this);
}
@Override
@Nullable
public GrTypeElement getTypeElementGroovy() {
return null;
}
@Override
@NotNull
public PsiType getType() {
return JavaPsiFacade.getInstance(getProject()).getElementFactory().createType(getContainingClass(), PsiSubstitutor.EMPTY);
}
@Nullable
@Override
public PsiType getDeclaredType() {
return getType();
}
@Override
@Nullable
public PsiType getTypeGroovy() {
return getType();
}
@Override
public void setType(@Nullable PsiType type) {
throw new RuntimeException("Cannot set type for enum constant");
}
@Override
@Nullable
public GrExpression getInitializerGroovy() {
return null;
}
@Override
public boolean isProperty() {
return false;
}
@Override
public GroovyResolveResult[] multiResolveClass() {
GroovyResolveResult result = new GroovyResolveResultImpl(getContainingClass(), this, null, PsiSubstitutor.EMPTY, true, true);
return new GroovyResolveResult[]{result};
}
@Override
@Nullable
public GrArgumentList getArgumentList() {
return findChildByClass(GrArgumentList.class);
}
@Override
public GrNamedArgument addNamedArgument(final GrNamedArgument namedArgument) throws IncorrectOperationException {
GrArgumentList list = getArgumentList();
assert list != null;
if (list.getText().trim().isEmpty()) {
final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
final GrArgumentList newList = factory.createArgumentList();
list = (GrArgumentList)list.replace(newList);
}
return list.addNamedArgument(namedArgument);
}
@NotNull
@Override
public GrNamedArgument[] getNamedArguments() {
final GrArgumentList argumentList = getArgumentList();
return argumentList == null ? GrNamedArgument.EMPTY_ARRAY : argumentList.getNamedArguments();
}
@NotNull
@Override
public GrExpression[] getExpressionArguments() {
final GrArgumentList argumentList = getArgumentList();
return argumentList == null ? GrExpression.EMPTY_ARRAY : argumentList.getExpressionArguments();
}
@NotNull
@Override
public GroovyResolveResult[] getCallVariants(@Nullable GrExpression upToArgument) {
return multiResolve(true);
}
@NotNull
@Override
public JavaResolveResult resolveMethodGenerics() {
return JavaResolveResult.EMPTY;
}
@Override
@Nullable
public GrEnumConstantInitializer getInitializingClass() {
return getStubOrPsiChild(GroovyElementTypes.ENUM_CONSTANT_INITIALIZER);
}
@NotNull
@Override
public PsiEnumConstantInitializer getOrCreateInitializingClass() {
final GrEnumConstantInitializer initializingClass = getInitializingClass();
if (initializingClass != null) return initializingClass;
final GrEnumConstantInitializer initializer =
GroovyPsiElementFactory.getInstance(getProject()).createEnumConstantFromText("foo{}").getInitializingClass();
LOG.assertTrue(initializer != null);
final GrArgumentList argumentList = getArgumentList();
if (argumentList != null) {
return (PsiEnumConstantInitializer)addAfter(initializer, argumentList);
}
else {
return (PsiEnumConstantInitializer)addAfter(initializer, getNameIdentifierGroovy());
}
}
@Override
public PsiReference getReference() {
return myReference;
}
@Override
public PsiMethod resolveConstructor() {
return resolveMethod();
}
@NotNull
@Override
public GroovyResolveResult[] multiResolve(boolean incompleteCode) {
PsiType[] argTypes = PsiUtil.getArgumentTypes(getFirstChild(), false);
PsiClass clazz = getContainingClass();
return ResolveUtil.getAllClassConstructors(clazz, PsiSubstitutor.EMPTY, argTypes, this);
}
@NotNull
@Override
public PsiClass getContainingClass() {
PsiClass aClass = super.getContainingClass();
assert aClass != null;
return aClass;
}
private class MyReference implements PsiPolyVariantReference {
@Override
@NotNull
public ResolveResult[] multiResolve(boolean incompleteCode) {
return GrEnumConstantImpl.this.multiResolve(false);
}
@NotNull
@Override
public PsiElement getElement() {
return GrEnumConstantImpl.this;
}
@NotNull
@Override
public TextRange getRangeInElement() {
return getNameIdentifierGroovy().getTextRange().shiftLeft(getNode().getStartOffset());
}
@Override
public PsiElement resolve() {
return resolveMethod();
}
@NotNull
public GroovyResolveResult advancedResolve() {
return GrEnumConstantImpl.this.advancedResolve();
}
@Override
@NotNull
public String getCanonicalText() {
return getContainingClass().getName();
}
@Override
public PsiElement handleElementRename(@NotNull String newElementName) throws IncorrectOperationException {
return getElement();
}
@Override
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
throw new IncorrectOperationException("invalid operation");
}
@Override
public boolean isReferenceTo(@NotNull PsiElement element) {
return element instanceof GrMethod && ((GrMethod)element).isConstructor() && getManager().areElementsEquivalent(resolve(), element);
}
@Override
public boolean isSoft() {
return false;
}
}
@Nullable
@Override
public Object computeConstantValue() {
return this;
}
}
| |
/*
* Copyright 2012 Switchfly
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.switchfly.inputvalidation;
import com.switchfly.compress.AssetPackageMode;
import com.switchfly.inputvalidation.exception.InvalidRequestParameterException;
import com.switchfly.inputvalidation.exception.MissingRequestParameterException;
import com.switchfly.inputvalidation.validator.Validator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RequestParameterTest {
private static final ValidationStrategy<String> ALWAYS_INVALID_VALIDATION = new ValidationStrategy<String>(null, new Validator<String>() {
@Override
public boolean execute(String content) {
return false;
}
}, null);
@Test
public void testGetName() throws Exception {
assertEquals("Abc-12_4", new RequestParameter("Abc-12_4", null).getName());
assertEquals("Abc-12_4_script", new RequestParameter("?Ab = c-1&2_4_!\"'<script>", null).getName());
assertEquals(null, new RequestParameter(null, null).getName());
assertEquals(" ", new RequestParameter(" ", null).getName());
assertEquals("", new RequestParameter("", null).getName());
}
@Test
public void testToStringWithValidValues() throws Exception {
assertEquals("foo", new RequestParameter(null, "foo").toString());
}
@Test
public void testToStringWithDefaultValues() throws Exception {
assertEquals("foo", new RequestParameter(null, "foo").toString("bar"));
assertEquals("bar", new RequestParameter(null, "").toString("bar"));
assertEquals("bar", new RequestParameter(null, null).toString("bar"));
assertEquals("bar", new RequestParameter(null, "foo").validateWith(ALWAYS_INVALID_VALIDATION).toString("bar"));
}
@Test
public void testToStringInvalidValues() throws Exception {
try {
new RequestParameter("foo", "").toString();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toString();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "bar").validateWith(ALWAYS_INVALID_VALIDATION).toString();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("bar", e.getParameterValue());
}
}
@Test
public void testToIntegerWithValidValues() throws Exception {
assertEquals(Integer.valueOf(1), new RequestParameter(null, "1").toInteger());
assertEquals(Integer.valueOf(-1), new RequestParameter(null, "-1").toInteger());
}
@Test
public void testToIntegerWithDefaultValues() throws Exception {
assertEquals(Integer.valueOf(2), new RequestParameter(null, "2").toInteger(1));
assertEquals(Integer.valueOf(1), new RequestParameter(null, "foo").toInteger(1));
assertEquals(Integer.valueOf(1), new RequestParameter(null, "").toInteger(1));
assertEquals(Integer.valueOf(1), new RequestParameter(null, null).toInteger(1));
assertEquals(Integer.valueOf(1), new RequestParameter(null, "2").validateWith(ALWAYS_INVALID_VALIDATION).toInteger(1));
}
@Test
public void testToIntegerWithInValidValues() throws Exception {
try {
new RequestParameter("foo", "").toInteger();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toInteger();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "1").validateWith(ALWAYS_INVALID_VALIDATION).toInteger();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("1", e.getParameterValue());
}
}
@Test
public void testToLongerWithValidValues() throws Exception {
assertEquals(Long.valueOf(1), new RequestParameter(null, "1").toLong());
assertEquals(Long.valueOf(-1), new RequestParameter(null, "-1").toLong());
}
@Test
public void testToLongerWithDefaultValues() throws Exception {
assertEquals(Long.valueOf(2), new RequestParameter(null, "2").toLong(1));
assertEquals(Long.valueOf(1), new RequestParameter(null, "foo").toLong(1));
assertEquals(Long.valueOf(1), new RequestParameter(null, "").toLong(1));
assertEquals(Long.valueOf(1), new RequestParameter(null, null).toLong(1));
assertEquals(Long.valueOf(1), new RequestParameter(null, "2").validateWith(ALWAYS_INVALID_VALIDATION).toLong(1));
}
@Test
public void testToLongerInvalidValues() throws Exception {
try {
new RequestParameter("foo", "").toLong();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toLong();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "1").validateWith(ALWAYS_INVALID_VALIDATION).toLong();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("1", e.getParameterValue());
}
}
@Test
public void testToDouble() throws Exception {
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "0.1").toDouble());
assertEquals(Double.valueOf(-0.1), new RequestParameter(null, "-0.1").toDouble());
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "foo").toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "").toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, null).toDouble(0.1));
try {
new RequestParameter("foo", "").toDouble();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toDouble();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "0.1").validateWith(ALWAYS_INVALID_VALIDATION).toDouble();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("0.1", e.getParameterValue());
}
}
@Test
public void testToDoubleWithValidValues() throws Exception {
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "0.1").toDouble());
assertEquals(Double.valueOf(-0.1), new RequestParameter(null, "-0.1").toDouble());
}
@Test
public void testToDoubleWithDefaultValues() throws Exception {
assertEquals(Double.valueOf(0.2), new RequestParameter(null, "0.2").toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "foo").toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "").toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, null).toDouble(0.1));
assertEquals(Double.valueOf(0.1), new RequestParameter(null, "0.2").validateWith(ALWAYS_INVALID_VALIDATION).toDouble(0.1));
}
@Test
public void testToDoubleWithInvalidValues() throws Exception {
try {
new RequestParameter("foo", "").toDouble();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toDouble();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "0.1").validateWith(ALWAYS_INVALID_VALIDATION).toDouble();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("0.1", e.getParameterValue());
}
}
@Test
public void testToBooleanWithValidValues() throws Exception {
assertEquals(true, new RequestParameter(null, "true").toBoolean());
assertEquals(true, new RequestParameter(null, "TRUE").toBoolean());
assertEquals(true, new RequestParameter(null, "yes").toBoolean());
assertEquals(true, new RequestParameter(null, "YES").toBoolean());
assertEquals(false, new RequestParameter(null, "false").toBoolean());
assertEquals(false, new RequestParameter(null, "no").toBoolean());
assertEquals(false, new RequestParameter(null, "1").toBoolean());
assertEquals(false, new RequestParameter(null, "0").toBoolean());
assertEquals(false, new RequestParameter(null, "foo").toBoolean());
}
@Test
public void testToBooleanWithDefaultValues() throws Exception {
assertEquals(true, new RequestParameter(null, "true").toBoolean(false));
assertEquals(false, new RequestParameter(null, "foo").toBoolean(true));
assertEquals(true, new RequestParameter(null, "true").toBoolean(false));
assertEquals(true, new RequestParameter(null, "").toBoolean(true));
assertEquals(true, new RequestParameter(null, null).toBoolean(true));
assertEquals(false, new RequestParameter(null, "true").validateWith(ALWAYS_INVALID_VALIDATION).toBoolean(false));
}
@Test
public void testToBooleanWithInvalidValues() throws Exception {
try {
new RequestParameter("foo", "").toBoolean();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", null).toBoolean();
} catch (MissingRequestParameterException e) {
assertEquals("foo", e.getParameterName());
}
try {
new RequestParameter("foo", "true").validateWith(ALWAYS_INVALID_VALIDATION).toBoolean();
} catch (InvalidRequestParameterException e) {
assertEquals("foo", e.getParameterName());
assertEquals("true", e.getParameterValue());
}
}
@Test
public void testToEnumWithValidValues() throws Exception {
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, "PRODUCTION").toEnum(AssetPackageMode.class));
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, "production").toEnum(AssetPackageMode.class));
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, "Production").toEnum(AssetPackageMode.class));
}
@Test
public void testToEnumWithDefaultValues() throws Exception {
assertEquals(AssetPackageMode.DEBUG, new RequestParameter(null, "debug").toEnum(AssetPackageMode.class, AssetPackageMode.PRODUCTION));
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, "").toEnum(AssetPackageMode.class, AssetPackageMode.PRODUCTION));
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, null).toEnum(AssetPackageMode.class, AssetPackageMode.PRODUCTION));
assertEquals(AssetPackageMode.PRODUCTION, new RequestParameter(null, "foo").toEnum(AssetPackageMode.class, AssetPackageMode.PRODUCTION));
assertEquals(AssetPackageMode.PRODUCTION,
new RequestParameter(null, "debug").validateWith(ALWAYS_INVALID_VALIDATION).toEnum(AssetPackageMode.class, AssetPackageMode.PRODUCTION));
}
@Test
public void testToEnumWithInvalidValues() throws Exception {
try {
new RequestParameter("mode", null).toEnum(AssetPackageMode.class);
} catch (MissingRequestParameterException e) {
assertEquals("mode", e.getParameterName());
}
try {
new RequestParameter("mode", "").toEnum(AssetPackageMode.class);
} catch (MissingRequestParameterException e) {
assertEquals("mode", e.getParameterName());
}
try {
new RequestParameter("mode", "foo").toEnum(AssetPackageMode.class);
} catch (InvalidRequestParameterException e) {
assertEquals("mode", e.getParameterName());
assertEquals("foo", e.getParameterValue());
}
try {
new RequestParameter("mode", "debug").validateWith(ALWAYS_INVALID_VALIDATION).toEnum(AssetPackageMode.class);
} catch (InvalidRequestParameterException e) {
assertEquals("mode", e.getParameterName());
assertEquals("debug", e.getParameterValue());
}
}
}
| |
package stroom.proxy.repo;
import stroom.proxy.repo.dao.SqliteJooqHelper;
import name.falgout.jeffrey.testing.junit.guice.GuiceExtension;
import name.falgout.jeffrey.testing.junit.guice.IncludeModule;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.inject.Inject;
import static org.assertj.core.api.Assertions.assertThat;
import static stroom.proxy.repo.db.jooq.tables.Aggregate.AGGREGATE;
import static stroom.proxy.repo.db.jooq.tables.ForwardAggregate.FORWARD_AGGREGATE;
import static stroom.proxy.repo.db.jooq.tables.Source.SOURCE;
import static stroom.proxy.repo.db.jooq.tables.SourceEntry.SOURCE_ENTRY;
import static stroom.proxy.repo.db.jooq.tables.SourceItem.SOURCE_ITEM;
@ExtendWith(GuiceExtension.class)
@IncludeModule(ProxyRepoTestModule.class)
public class TestCleanup {
@Inject
private RepoSources proxyRepoSources;
@Inject
private RepoSourceItems proxyRepoSourceEntries;
@Inject
private Aggregator aggregator;
@Inject
private AggregateForwarder aggregateForwarder;
@Inject
private Cleanup cleanup;
@Inject
private MockForwardDestinations mockForwardDestinations;
@Inject
private ProxyRepoDbConnProvider connProvider;
@Inject
private SqliteJooqHelper jooqHelper;
@BeforeEach
void beforeEach() {
aggregateForwarder.clear();
aggregator.clear();
proxyRepoSourceEntries.clear();
proxyRepoSources.clear();
mockForwardDestinations.clear();
}
@Test
void testCleanup() {
final SqliteJooqHelper jooq = new SqliteJooqHelper(connProvider);
jooq.context(context -> {
long sourceId = 0;
long sourceItemId = 0;
long sourceEntryId = 0;
long aggregateId = 0;
long forwardAggregateId = 0;
for (int i = 1; i <= 2; i++) {
String feedName = "TEST_FEED_" + i;
for (int j = 0; j < 6; j++) {
// Add sources.
context
.insertInto(
SOURCE,
SOURCE.ID,
SOURCE.PATH,
SOURCE.LAST_MODIFIED_TIME_MS,
SOURCE.EXAMINED)
.values(
++sourceId,
StringUtils.leftPad(String.valueOf(sourceId), 3, "0") + ".zip",
System.currentTimeMillis(),
true)
.execute();
// Add an aggregate.
for (int k = 0; k < 2; k++) {
aggregateId++;
// Add aggregate.
context
.insertInto(
AGGREGATE,
AGGREGATE.ID,
AGGREGATE.CREATE_TIME_MS,
AGGREGATE.FEED_NAME,
AGGREGATE.TYPE_NAME,
AGGREGATE.BYTE_SIZE,
AGGREGATE.ITEMS,
AGGREGATE.COMPLETE)
.values(
aggregateId,
System.currentTimeMillis(),
feedName,
null,
170L,
2,
true)
.execute();
// Add aggregate forward.
context
.insertInto(
FORWARD_AGGREGATE,
FORWARD_AGGREGATE.ID,
FORWARD_AGGREGATE.UPDATE_TIME_MS,
FORWARD_AGGREGATE.FK_AGGREGATE_ID,
FORWARD_AGGREGATE.SUCCESS,
FORWARD_AGGREGATE.ERROR,
FORWARD_AGGREGATE.TRIES,
FORWARD_AGGREGATE.FK_FORWARD_URL_ID)
.values(
++forwardAggregateId,
System.currentTimeMillis(),
aggregateId,
false,
null,
null,
1)
.execute();
// Add source items.
for (int l = 1; l <= 4; l++) {
context
.insertInto(
SOURCE_ITEM,
SOURCE_ITEM.ID,
SOURCE_ITEM.NAME,
SOURCE_ITEM.FEED_NAME,
SOURCE_ITEM.TYPE_NAME,
SOURCE_ITEM.SOURCE_ID,
SOURCE_ITEM.AGGREGATE_ID)
.values(
++sourceItemId,
i + "_" + j + "_" + k + "_" + l,
feedName,
null,
sourceId,
aggregateId)
.execute();
// Add source entry.
context
.insertInto(
SOURCE_ENTRY,
SOURCE_ENTRY.ID,
SOURCE_ENTRY.EXTENSION,
SOURCE_ENTRY.EXTENSION_TYPE,
SOURCE_ENTRY.BYTE_SIZE,
SOURCE_ENTRY.FK_SOURCE_ITEM_ID)
.values(
++sourceEntryId,
".hdr",
2,
84L,
sourceItemId)
.execute();
context
.insertInto(
SOURCE_ENTRY,
SOURCE_ENTRY.ID,
SOURCE_ENTRY.EXTENSION,
SOURCE_ENTRY.EXTENSION_TYPE,
SOURCE_ENTRY.BYTE_SIZE,
SOURCE_ENTRY.FK_SOURCE_ITEM_ID)
.values(
++sourceEntryId,
".dat",
4,
1L,
sourceItemId)
.execute();
}
}
}
}
});
// Make sure we can't delete any sources.
jooqHelper.printAllTables();
assertThat(proxyRepoSources.getDeletableSources().size()).isZero();
// Now pretend we forwarded the first aggregates.
jooqHelper.printAllTables();
forward(1);
// Make sure we can delete source entries and items but not data.
jooqHelper.printAllTables();
assertThat(proxyRepoSources.getDeletableSources().size()).isZero();
// Now forward some more.
jooqHelper.printAllTables();
forward(2);
// Check we can now delete the first source.
jooqHelper.printAllTables();
assertThat(proxyRepoSources.getDeletableSources().size()).isOne();
// Forward remaining.
jooqHelper.printAllTables();
final long minId = jooq.getMinId(FORWARD_AGGREGATE, FORWARD_AGGREGATE.ID).orElse(0L);
final long maxId = jooq.getMaxId(FORWARD_AGGREGATE, FORWARD_AGGREGATE.ID).orElse(0L);
for (long i = minId; i <= maxId; i++) {
forward(i);
}
// Check everything is deleted.
jooqHelper.printAllTables();
assertThat(proxyRepoSources.getDeletableSources().size()).isEqualTo(12);
cleanup.cleanupSources();
// Check we have no source left
assertThat(jooq.count(SOURCE_ENTRY)).isZero();
assertThat(jooq.count(SOURCE_ITEM)).isZero();
assertThat(jooq.count(SOURCE)).isZero();
}
private void forward(long aggregateId) {
final Aggregate aggregate = new Aggregate(aggregateId, null, null);
final ForwardUrl forwardUrl = new ForwardUrl(1, "test");
final ForwardAggregate forwardAggregate = ForwardAggregate
.builder()
.id(aggregateId)
.aggregate(aggregate)
.forwardUrl(forwardUrl)
.build();
aggregateForwarder.forward(forwardAggregate);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.reservation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.hadoop.yarn.api.records.ReservationId;
import org.apache.hadoop.yarn.api.records.ReservationRequest;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.server.resourcemanager.reservation.exceptions.PlanningException;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
import org.apache.hadoop.yarn.util.Clock;
import org.apache.hadoop.yarn.util.UTCClock;
import org.apache.hadoop.yarn.util.resource.ResourceCalculator;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class InMemoryPlan implements Plan {
private static final Logger LOG = LoggerFactory.getLogger(InMemoryPlan.class);
private static final Resource ZERO_RESOURCE = Resource.newInstance(0, 0);
private TreeMap<ReservationInterval, Set<InMemoryReservationAllocation>> currentReservations =
new TreeMap<ReservationInterval, Set<InMemoryReservationAllocation>>();
private RLESparseResourceAllocation rleSparseVector;
private Map<String, RLESparseResourceAllocation> userResourceAlloc =
new HashMap<String, RLESparseResourceAllocation>();
private Map<ReservationId, InMemoryReservationAllocation> reservationTable =
new HashMap<ReservationId, InMemoryReservationAllocation>();
private final ReentrantReadWriteLock readWriteLock =
new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private final SharingPolicy policy;
private final ReservationAgent agent;
private final long step;
private final ResourceCalculator resCalc;
private final Resource minAlloc, maxAlloc;
private final String queueName;
private final QueueMetrics queueMetrics;
private final Planner replanner;
private final boolean getMoveOnExpiry;
private final Clock clock;
private Resource totalCapacity;
InMemoryPlan(QueueMetrics queueMetrics, SharingPolicy policy,
ReservationAgent agent, Resource totalCapacity, long step,
ResourceCalculator resCalc, Resource minAlloc, Resource maxAlloc,
String queueName, Planner replanner, boolean getMoveOnExpiry) {
this(queueMetrics, policy, agent, totalCapacity, step, resCalc, minAlloc,
maxAlloc, queueName, replanner, getMoveOnExpiry, new UTCClock());
}
InMemoryPlan(QueueMetrics queueMetrics, SharingPolicy policy,
ReservationAgent agent, Resource totalCapacity, long step,
ResourceCalculator resCalc, Resource minAlloc, Resource maxAlloc,
String queueName, Planner replanner, boolean getMoveOnExpiry, Clock clock) {
this.queueMetrics = queueMetrics;
this.policy = policy;
this.agent = agent;
this.step = step;
this.totalCapacity = totalCapacity;
this.resCalc = resCalc;
this.minAlloc = minAlloc;
this.maxAlloc = maxAlloc;
this.rleSparseVector = new RLESparseResourceAllocation(resCalc, minAlloc);
this.queueName = queueName;
this.replanner = replanner;
this.getMoveOnExpiry = getMoveOnExpiry;
this.clock = clock;
}
@Override
public QueueMetrics getQueueMetrics() {
return queueMetrics;
}
private void incrementAllocation(ReservationAllocation reservation) {
assert (readWriteLock.isWriteLockedByCurrentThread());
Map<ReservationInterval, ReservationRequest> allocationRequests =
reservation.getAllocationRequests();
// check if we have encountered the user earlier and if not add an entry
String user = reservation.getUser();
RLESparseResourceAllocation resAlloc = userResourceAlloc.get(user);
if (resAlloc == null) {
resAlloc = new RLESparseResourceAllocation(resCalc, minAlloc);
userResourceAlloc.put(user, resAlloc);
}
for (Map.Entry<ReservationInterval, ReservationRequest> r : allocationRequests
.entrySet()) {
resAlloc.addInterval(r.getKey(), r.getValue());
rleSparseVector.addInterval(r.getKey(), r.getValue());
}
}
private void decrementAllocation(ReservationAllocation reservation) {
assert (readWriteLock.isWriteLockedByCurrentThread());
Map<ReservationInterval, ReservationRequest> allocationRequests =
reservation.getAllocationRequests();
String user = reservation.getUser();
RLESparseResourceAllocation resAlloc = userResourceAlloc.get(user);
for (Map.Entry<ReservationInterval, ReservationRequest> r : allocationRequests
.entrySet()) {
resAlloc.removeInterval(r.getKey(), r.getValue());
rleSparseVector.removeInterval(r.getKey(), r.getValue());
}
if (resAlloc.isEmpty()) {
userResourceAlloc.remove(user);
}
}
public Set<ReservationAllocation> getAllReservations() {
readLock.lock();
try {
if (currentReservations != null) {
Set<ReservationAllocation> flattenedReservations =
new HashSet<ReservationAllocation>();
for (Set<InMemoryReservationAllocation> reservationEntries : currentReservations
.values()) {
flattenedReservations.addAll(reservationEntries);
}
return flattenedReservations;
} else {
return null;
}
} finally {
readLock.unlock();
}
}
@Override
public boolean addReservation(ReservationAllocation reservation)
throws PlanningException {
// Verify the allocation is memory based otherwise it is not supported
InMemoryReservationAllocation inMemReservation =
(InMemoryReservationAllocation) reservation;
if (inMemReservation.getUser() == null) {
String errMsg =
"The specified Reservation with ID "
+ inMemReservation.getReservationId()
+ " is not mapped to any user";
LOG.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
writeLock.lock();
try {
if (reservationTable.containsKey(inMemReservation.getReservationId())) {
String errMsg =
"The specified Reservation with ID "
+ inMemReservation.getReservationId() + " already exists";
LOG.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
// Validate if we can accept this reservation, throws exception if
// validation fails
policy.validate(this, inMemReservation);
// we record here the time in which the allocation has been accepted
reservation.setAcceptanceTimestamp(clock.getTime());
ReservationInterval searchInterval =
new ReservationInterval(inMemReservation.getStartTime(),
inMemReservation.getEndTime());
Set<InMemoryReservationAllocation> reservations =
currentReservations.get(searchInterval);
if (reservations == null) {
reservations = new HashSet<InMemoryReservationAllocation>();
}
if (!reservations.add(inMemReservation)) {
LOG.error("Unable to add reservation: {} to plan.",
inMemReservation.getReservationId());
return false;
}
currentReservations.put(searchInterval, reservations);
reservationTable.put(inMemReservation.getReservationId(),
inMemReservation);
incrementAllocation(inMemReservation);
LOG.info("Sucessfully added reservation: {} to plan.",
inMemReservation.getReservationId());
return true;
} finally {
writeLock.unlock();
}
}
@Override
public boolean updateReservation(ReservationAllocation reservation)
throws PlanningException {
writeLock.lock();
boolean result = false;
try {
ReservationId resId = reservation.getReservationId();
ReservationAllocation currReservation = getReservationById(resId);
if (currReservation == null) {
String errMsg =
"The specified Reservation with ID " + resId
+ " does not exist in the plan";
LOG.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
// validate if we can accept this reservation, throws exception if
// validation fails
policy.validate(this, reservation);
if (!removeReservation(currReservation)) {
LOG.error("Unable to replace reservation: {} from plan.",
reservation.getReservationId());
return result;
}
try {
result = addReservation(reservation);
} catch (PlanningException e) {
LOG.error("Unable to update reservation: {} from plan due to {}.",
reservation.getReservationId(), e.getMessage());
}
if (result) {
LOG.info("Sucessfully updated reservation: {} in plan.",
reservation.getReservationId());
return result;
} else {
// rollback delete
addReservation(currReservation);
LOG.info("Rollbacked update reservation: {} from plan.",
reservation.getReservationId());
return result;
}
} finally {
writeLock.unlock();
}
}
private boolean removeReservation(ReservationAllocation reservation) {
assert (readWriteLock.isWriteLockedByCurrentThread());
ReservationInterval searchInterval =
new ReservationInterval(reservation.getStartTime(),
reservation.getEndTime());
Set<InMemoryReservationAllocation> reservations =
currentReservations.get(searchInterval);
if (reservations != null) {
if (!reservations.remove(reservation)) {
LOG.error("Unable to remove reservation: {} from plan.",
reservation.getReservationId());
return false;
}
if (reservations.isEmpty()) {
currentReservations.remove(searchInterval);
}
} else {
String errMsg =
"The specified Reservation with ID " + reservation.getReservationId()
+ " does not exist in the plan";
LOG.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
reservationTable.remove(reservation.getReservationId());
decrementAllocation(reservation);
LOG.info("Sucessfully deleted reservation: {} in plan.",
reservation.getReservationId());
return true;
}
@Override
public boolean deleteReservation(ReservationId reservationID) {
writeLock.lock();
try {
ReservationAllocation reservation = getReservationById(reservationID);
if (reservation == null) {
String errMsg =
"The specified Reservation with ID " + reservationID
+ " does not exist in the plan";
LOG.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
return removeReservation(reservation);
} finally {
writeLock.unlock();
}
}
@Override
public void archiveCompletedReservations(long tick) {
// Since we are looking for old reservations, read lock is optimal
LOG.debug("Running archival at time: {}", tick);
List<InMemoryReservationAllocation> expiredReservations =
new ArrayList<InMemoryReservationAllocation>();
readLock.lock();
// archive reservations and delete the ones which are beyond
// the reservation policy "window"
try {
long archivalTime = tick - policy.getValidWindow();
ReservationInterval searchInterval =
new ReservationInterval(archivalTime, archivalTime);
SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations =
currentReservations.headMap(searchInterval, true);
if (!reservations.isEmpty()) {
for (Set<InMemoryReservationAllocation> reservationEntries : reservations
.values()) {
for (InMemoryReservationAllocation reservation : reservationEntries) {
if (reservation.getEndTime() <= archivalTime) {
expiredReservations.add(reservation);
}
}
}
}
} finally {
readLock.unlock();
}
if (expiredReservations.isEmpty()) {
return;
}
// Need write lock only if there are any reservations to be deleted
writeLock.lock();
try {
for (InMemoryReservationAllocation expiredReservation : expiredReservations) {
removeReservation(expiredReservation);
}
} finally {
writeLock.unlock();
}
}
@Override
public Set<ReservationAllocation> getReservationsAtTime(long tick) {
ReservationInterval searchInterval =
new ReservationInterval(tick, Long.MAX_VALUE);
readLock.lock();
try {
SortedMap<ReservationInterval, Set<InMemoryReservationAllocation>> reservations =
currentReservations.headMap(searchInterval, true);
if (!reservations.isEmpty()) {
Set<ReservationAllocation> flattenedReservations =
new HashSet<ReservationAllocation>();
for (Set<InMemoryReservationAllocation> reservationEntries : reservations
.values()) {
for (InMemoryReservationAllocation reservation : reservationEntries) {
if (reservation.getEndTime() > tick) {
flattenedReservations.add(reservation);
}
}
}
return Collections.unmodifiableSet(flattenedReservations);
} else {
return Collections.emptySet();
}
} finally {
readLock.unlock();
}
}
@Override
public long getStep() {
return step;
}
@Override
public SharingPolicy getSharingPolicy() {
return policy;
}
@Override
public ReservationAgent getReservationAgent() {
return agent;
}
@Override
public Resource getConsumptionForUser(String user, long t) {
readLock.lock();
try {
RLESparseResourceAllocation userResAlloc = userResourceAlloc.get(user);
if (userResAlloc != null) {
return userResAlloc.getCapacityAtTime(t);
} else {
return Resources.clone(ZERO_RESOURCE);
}
} finally {
readLock.unlock();
}
}
@Override
public Resource getTotalCommittedResources(long t) {
readLock.lock();
try {
return rleSparseVector.getCapacityAtTime(t);
} finally {
readLock.unlock();
}
}
@Override
public ReservationAllocation getReservationById(ReservationId reservationID) {
if (reservationID == null) {
return null;
}
readLock.lock();
try {
return reservationTable.get(reservationID);
} finally {
readLock.unlock();
}
}
@Override
public Resource getTotalCapacity() {
readLock.lock();
try {
return Resources.clone(totalCapacity);
} finally {
readLock.unlock();
}
}
@Override
public Resource getMinimumAllocation() {
return Resources.clone(minAlloc);
}
@Override
public void setTotalCapacity(Resource cap) {
writeLock.lock();
try {
totalCapacity = Resources.clone(cap);
} finally {
writeLock.unlock();
}
}
public long getEarliestStartTime() {
readLock.lock();
try {
return rleSparseVector.getEarliestStartTime();
} finally {
readLock.unlock();
}
}
@Override
public long getLastEndTime() {
readLock.lock();
try {
return rleSparseVector.getLatestEndTime();
} finally {
readLock.unlock();
}
}
@Override
public ResourceCalculator getResourceCalculator() {
return resCalc;
}
@Override
public String getQueueName() {
return queueName;
}
@Override
public Resource getMaximumAllocation() {
return Resources.clone(maxAlloc);
}
public String toCumulativeString() {
readLock.lock();
try {
return rleSparseVector.toString();
} finally {
readLock.unlock();
}
}
@Override
public Planner getReplanner() {
return replanner;
}
@Override
public boolean getMoveOnExpiry() {
return getMoveOnExpiry;
}
@Override
public String toString() {
readLock.lock();
try {
StringBuffer planStr = new StringBuffer("In-memory Plan: ");
planStr.append("Parent Queue: ").append(queueName)
.append("Total Capacity: ").append(totalCapacity).append("Step: ")
.append(step);
for (ReservationAllocation reservation : getAllReservations()) {
planStr.append(reservation);
}
return planStr.toString();
} finally {
readLock.unlock();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.discovery.impl.cluster.voting;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.discovery.commons.providers.util.ResourceHelper;
import org.apache.sling.discovery.impl.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper class for voting
*/
public class VotingHelper {
private final static Logger logger = LoggerFactory
.getLogger(VotingHelper.class);
/**
* List all the votings that are currently 'open' but 'not winning'.
* <p>
* 'Open' means that they have not expired yet, have zero no-votes,
* and match the view that this instance has of the cluster.
* <p>
* 'Not winning' means that a voting still did not receive a vote
* from everybody
* @return the list of matching votings - never returns null
*/
public static List<VotingView> listOpenNonWinningVotings(
final ResourceResolver resourceResolver, final Config config) {
if (config==null) {
logger.info("listOpenNonWinningVotings: config is null, bundle likely deactivated.");
return new ArrayList<VotingView>();
}
final String ongoingVotingsPath = config.getOngoingVotingsPath();
final Resource ongoingVotingsResource = resourceResolver
.getResource(ongoingVotingsPath);
if (ongoingVotingsResource == null) {
// it is legal that at this stage there is no ongoingvotings node yet
// for example when there was never a voting yet
logger.debug("listOpenNonWinningVotings: no ongoing votings parent resource found");
return new ArrayList<VotingView>();
}
final Iterable<Resource> children = ongoingVotingsResource.getChildren();
final Iterator<Resource> it = children.iterator();
final List<VotingView> result = new LinkedList<VotingView>();
if (!it.hasNext()) {
return result;
}
while (it.hasNext()) {
Resource aChild = it.next();
VotingView c = new VotingView(aChild);
String matchesLiveView;
try {
matchesLiveView = c.matchesLiveView(config);
} catch (Exception e) {
logger.error("listOpenNonWinningVotings: could not compare voting with live view: "+e, e);
continue;
}
boolean ongoingVoting = c.isOngoingVoting(config);
boolean hasNoVotes = c.hasNoVotes();
boolean isWinning = c.isWinning();
if (matchesLiveView == null
&& ongoingVoting && !hasNoVotes
&& !isWinning) {
if (logger.isDebugEnabled()) {
logger.debug("listOpenNonWinningVotings: found an open voting: "
+ aChild
+ ", properties="
+ ResourceHelper.getPropertiesForLogging(aChild));
}
result.add(c);
} else {
if (logger.isDebugEnabled()) {
logger.debug("listOpenNonWinningVotings: a non-open voting: "
+ aChild
+ ", matches live: " + matchesLiveView
+ ", is ongoing: " + ongoingVoting
+ ", has no votes: " + hasNoVotes
+ ", is winning: " + isWinning
+ ", properties="
+ ResourceHelper.getPropertiesForLogging(aChild));
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("listOpenNonWinningVotings: votings found: "
+ result.size());
}
return result;
}
/**
* List all the votings that have timed out
* @return the list of matching votings
*/
public static List<VotingView> listTimedoutVotings(
final ResourceResolver resourceResolver, final Config config) {
final String ongoingVotingsPath = config.getOngoingVotingsPath();
final Resource ongoingVotingsResource = resourceResolver
.getResource(ongoingVotingsPath);
if (ongoingVotingsResource == null) {
logger.info("listTimedoutVotings: no ongoing votings parent resource found"); // TOOD - is this expected?
return new ArrayList<VotingView>();
}
final Iterable<Resource> children = ongoingVotingsResource.getChildren();
final Iterator<Resource> it = children.iterator();
final List<VotingView> result = new LinkedList<VotingView>();
if (!it.hasNext()) {
return result;
}
while (it.hasNext()) {
Resource aChild = it.next();
VotingView c = new VotingView(aChild);
if (c.isTimedoutVoting(config)) {
if (logger.isDebugEnabled()) {
logger.debug("listTimedoutVotings: found a timed-out voting: "
+ aChild
+ ", properties="
+ ResourceHelper.getPropertiesForLogging(aChild));
}
result.add(c);
}
}
if (logger.isDebugEnabled()) {
logger.debug("listTimedoutVotings: votings found: "
+ result.size());
}
return result;
}
/**
* Return the still valid (ongoing) and winning (received a yes vote
* from everybody) voting
* @return the valid and winning voting
*/
public static VotingView getWinningVoting(
final ResourceResolver resourceResolver, final Config config) {
String ongoingVotingsPath = config.getOngoingVotingsPath();
Resource ongoingVotingsResource = resourceResolver
.getResource(ongoingVotingsPath);
if (ongoingVotingsResource == null) {
// it is legal that at this stage there is no ongoingvotings node yet
// for example when there was never a voting yet
logger.debug("getWinningVoting: no ongoing votings parent resource found");
return null;
}
Iterable<Resource> children = ongoingVotingsResource.getChildren();
Iterator<Resource> it = children.iterator();
List<VotingView> result = new LinkedList<VotingView>();
while (it.hasNext()) {
Resource aChild = it.next();
VotingView c = new VotingView(aChild);
boolean ongoing = c.isOngoingVoting(config);
boolean winning = c.isWinning();
if (ongoing && winning) {
if (logger.isDebugEnabled()) {
logger.debug("getWinningVoting: a winning voting: " + aChild);
}
result.add(c);
} else {
logger.debug("getWinningVote: not winning: vote="+aChild+" is ongoing="+ongoing+", winning="+winning);
}
}
if (result.size() == 1) {
return result.get(0);
} else {
return null;
}
}
/**
* Returns the voting for which the given slingId has vote yes or was the
* initiator (which is equal to yes).
* @param slingId the instance for which its yes vote should be looked up
* @return the voting for which the given slingId has votes yes or was the
* initiator
*/
public static List<VotingView> getYesVotingsOf(final ResourceResolver resourceResolver,
final Config config,
final String slingId) {
if (resourceResolver == null) {
throw new IllegalArgumentException("resourceResolver must not be null");
}
if (config == null) {
throw new IllegalArgumentException("config must not be null");
}
if (slingId == null || slingId.length() == 0) {
throw new IllegalArgumentException("slingId must not be null or empty");
}
final String ongoingVotingsPath = config.getOngoingVotingsPath();
final Resource ongoingVotingsResource = resourceResolver
.getResource(ongoingVotingsPath);
if (ongoingVotingsResource == null) {
return null;
}
final Iterable<Resource> children = ongoingVotingsResource.getChildren();
if (children == null) {
return null;
}
final Iterator<Resource> it = children.iterator();
final List<VotingView> result = new LinkedList<VotingView>();
while (it.hasNext()) {
Resource aChild = it.next();
VotingView c = new VotingView(aChild);
if (c.hasVotedYes(slingId)) {
result.add(c);
}
}
if (result.size() >= 1) {
// if result.size() is higher than 1, that means that there is more
// than 1 yes vote
// which can happen if the local instance is initiator of one
// and has voted on another voting
return result;
} else {
return null;
}
}
public static List<VotingView> listVotings(ResourceResolver resourceResolver, Config config) {
if (config==null) {
logger.info("listVotings: config is null, bundle likely deactivated.");
return new ArrayList<VotingView>();
}
final String ongoingVotingsPath = config.getOngoingVotingsPath();
final Resource ongoingVotingsResource = resourceResolver
.getResource(ongoingVotingsPath);
if (ongoingVotingsResource == null) {
// it is legal that at this stage there is no ongoingvotings node yet
// for example when there was never a voting yet
logger.debug("listVotings: no ongoing votings parent resource found");
return new ArrayList<VotingView>();
}
final Iterable<Resource> children = ongoingVotingsResource.getChildren();
final Iterator<Resource> it = children.iterator();
final List<VotingView> result = new LinkedList<VotingView>();
while (it.hasNext()) {
Resource aChild = it.next();
VotingView c = new VotingView(aChild);
result.add(c);
}
if (logger.isDebugEnabled()) {
logger.debug("listVotings: votings found: "
+ result.size());
}
return result;
}
}
| |
/**
* Data-Structures-In-Java
* DoublyLinkedList.java
*/
package com.deepak.data.structures.LinkedList;
/**
* Implementation of Doubly linked list
*
* <br> Operations supported are :
* - Inserting a element in the list - This can be at beginning, at end or at a given position.
* - Traversing through linked list. - This can happen in any direction with doubly linked list
* - Check the size of the list.
* - Check if list is empty.
* - Search an element by index.
* - Search an element by value.
* - Delete an element from the list - This can again be at beginning, at end or at given position.
* - Converting a Array from linked list.
* </br>
*
* @author Deepak
*
* @param <E>
*/
public class DoublyLinkedList<E> {
/* Head is needed to keep track of first node */
private Node<E> head;
/* Tail is needed to keep track of last node */
private Node<E> tail;
/* Size to keep track of number of elements in list.
* This should be increased by 1 when a element is added
* and should be reduced by 1 when a element is deleted */
private int size = 0;
/**
* Inserts a element into a linked list at head position.
* This does not require traversal through entire list.
*
* <br> Complexity :
* Since there is no traversal involved here, and insertion
* always happens at the head, this can be done in constant
* time. Hence, complexity comes out to be O(1)
* </br>
*
* @param value
*/
public void insertAtHead(E value) {
Node<E> newNode = new Node<E>(value);
if (null == head) {
/* If list is empty */
newNode.next = null;
newNode.prev = null;
head = newNode;
tail = newNode;
size++;
} else {
newNode.next = head;
newNode.prev = null;
head.prev = newNode;
head = newNode;
size++;
}
}
/**
* Inserts a element into a linked list at tail position.
* This does not needs traversal through entire list before insertion happens.
*
* <br> Complexity :
* Since, traversal through entire list is NOT involved here before
* new node gets inserted, and let's assume list has n elements,
* so insertion at tail will take O(1) time
* </br>
*
* @param value
*/
public void insertAtTail(E value) {
Node<E> newNode = new Node<E>(value);
if (null == tail) {
/* If list is empty */
newNode.next = null;
newNode.prev = null;
head = newNode;
tail = newNode;
size++;
} else {
tail.next = newNode;
newNode.next = null;
newNode.prev = tail;
tail = newNode;
size++;
}
}
/**
* Inserts a element into a linked list at a given position.
* This needs traversal through the linked list till the given position.
*
* <br> Complexity :
* This insertion can possibly happen at last node, means we will have complexity
* as O(1) as explained above.
* we may have to traverse entire linked list. On an average case with
* linked list having n elements, this will take n/2 time and after ignoring
* the constant term, complexity comes out to be O(n)
* </br>
*
* @param value
* @param position
*/
public void insertAtPosition(E value, int position) {
if (position < 0 || position > size) {
throw new IllegalArgumentException("Position is Invalid");
}
/* Conditions check passed, let's insert the node */
if (position == 0) {
/* Insertion should happen at head */
insertAtHead(value);
} else if (position == size -1) {
/* Insertion should happen at tail */
insertAtTail(value);
} else {
/* Insertion is happening somewhere in middle */
Node<E> currentNode = head;
for (int i = 0; i < position; i++) {
currentNode = currentNode.next;
}
Node<E> previousNode = currentNode.prev;
/* Insertion of new node will happen in
* between previous node and current node */
Node<E> newNode = new Node<E>(value);
newNode.next = currentNode;
newNode.prev = previousNode;
previousNode.next = newNode;
currentNode.prev = newNode;
size++;
}
}
/**
* Traverse the linked list in forward direction and print the items
*/
public void traverseForward() {
Node<E> temp = head;
while (temp != null) {
System.out.println(temp.item);
temp = temp.next;
}
}
/**
* Traverse the linked list in backward direction and print the items
*/
public void traverseBackward() {
Node<E> temp = tail;
while (temp != null) {
System.out.println(temp.item);
temp = temp.prev;
}
}
/**
* Returns the size of the linked list
*
* @return {@link int}
*/
public int size() {
return size;
}
/**
* Returns true, if linked list is empty
*
* @return {@link boolean}
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the Node containing data item after searching
* for a given index. If invalid index is passed, proper
* exception is thrown.
*
* @param index
* @return {@link Node<E>}
*/
public Node<E> searchByIndex(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Invalid index passed while searching for a value");
}
/* Validation passed, let's search for value using the index */
Node<E> temp = head;
for (int i = 0; i < index; i++) {
/* Start from 0 and go till one less then index
* because we are jumping to next node inside the loop */
temp = temp.next;
}
return temp;
}
/**
* Returns the node containing data item after searching
* for a given value. If there are multiple same values
* in linked list, first one will be returned.
*
* @param value
* @return {@link Node<E>}
*/
public Node<E> searchByValue(E value) {
/* Traverse through each node until this value is found */
Node<E> temp = head;
while (null != temp.next && temp.item != value) {
temp = temp.next;
}
if (temp.item == value) {
return temp;
}
return null;
}
/**
* Delete's the element present at head node
*/
public void deleteFromHead() {
/* If list is empty, return */
if (null == head) {
return;
}
Node<E> temp = head;
head = temp.next;
head.prev = null;
size--;
}
/**
* Delete's the element present at tail node
*/
public void deleteFromTail() {
/* If list is empty, return */
if (null == tail) {
return;
}
Node<E> temp = tail;
tail = temp.prev;
tail.next = null;
size--;
}
/**
* Delete's the element present at given position
*
* @param position
*/
public void deleteFromPosition(int position) {
if (position < 0 || position >= size) {
throw new IllegalArgumentException("Position is Invalid");
}
/* Conditions check passed, let's delete the node */
Node<E> nodeToBeDeleted = head;
for (int i = 0; i < position; i++) {
nodeToBeDeleted = nodeToBeDeleted.next;
}
Node<E> previousNode = nodeToBeDeleted.prev;
Node<E> nextNode = nodeToBeDeleted.next;
previousNode.next = nextNode;
nextNode.prev = previousNode;
size--;
}
/**
* Returns a array containing each element
* from the list from start to end
*
* @return
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = head; x != null; x = x.next) {
result[i++] = x.item;
}
return result;
}
/**
* Node class of a linked list
* This is needed since entire linked list is a collection
* of nodes connected to each other through links
*
* <br> We are keeping it generic so that it can be used with
* Integer, String or something else </br>
*
* <br> Each node contains a data item, a pointer to next node
* and pointer to previous node.
* Since this is a Doubly linked list and each node points in
* both directions i.e forward and backward.
* We maintain two pointers, one to next node and one to previous node </br>
*
* @author Deepak
*
* @param <T>
*/
public class Node<T> {
/* Data item in the node */
T item;
/* Pointer to next node */
Node<T> next;
/* Pointer to previous node */
Node<T> prev;
/* Constructor to create a node */
public Node(T item) {
this.item = item;
}
/* toString implementation to print just the data */
@Override
public String toString() {
return String.valueOf(item);
}
}
}
| |
/*
* =============================================================================
*
* Copyright (c) 2009, The JAVARUNTYPE team (http://www.javaruntype.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.javaruntype.type;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;
import org.javaruntype.exceptions.TypeRecognitionException;
import org.javaruntype.exceptions.TypeValidationException;
import org.javaruntype.type.parser.TypeLexer;
import org.javaruntype.type.parser.TypeParser;
import org.javaruntype.typedef.BoundedTypeDefVariable;
import org.javaruntype.typedef.InnerClassTypeDefVariable;
import org.javaruntype.typedef.InnerNamedTypeDefVariable;
import org.javaruntype.typedef.InnerParameterizedTypeTypeDefVariable;
import org.javaruntype.typedef.InnerTypeDefVariable;
import org.javaruntype.typedef.InnerWildcardTypeDefVariable;
import org.javaruntype.typedef.NamedTypeDefVariable;
import org.javaruntype.typedef.TypeDef;
import org.javaruntype.typedef.TypeDefVariable;
import org.javaruntype.typedef.TypeDefs;
import org.javaruntype.util.Utils;
/*
* (non-javadoc)
*
* This class contains internal algorithms for Type processing and
* handling.
*
* @since 1.0
*
* @author Daniel Fernández
*
*/
final class TypeUtil {
static Type<?> forName(final String typeName) {
try {
final String parsedTypeName =
(typeName.startsWith("class "))?
typeName.substring("class ".length()) :
(typeName.startsWith("interface "))?
typeName.substring("interface ".length()) :
typeName;
final TypeLexer lex = new TypeLexer(new ANTLRStringStream(parsedTypeName));
final CommonTokenStream tokens = new CommonTokenStream(lex);
final TypeParser parser = new TypeParser(tokens);
final CommonTree tree = (CommonTree) parser.type().getTree();
return createTypeFromTree(tree);
} catch (Exception e) {
throw new TypeRecognitionException(typeName, e);
}
}
@SuppressWarnings("unchecked")
private static Type<?> createTypeFromTree(final Tree tree)
throws ClassNotFoundException {
if (tree.getType() != TypeLexer.CLASSNAME) {
throw new TypeRecognitionException(
"A class name was expected (was: " + tree.getType() + ")");
}
final String className = tree.getText();
Class<?> typeClass = null;
try {
typeClass = Utils.getClass(className);
} catch (ClassNotFoundException e1) {
try {
typeClass = Utils.getClass(TypeNaming.TYPE_PACKAGE_LANG + className);
} catch (ClassNotFoundException e2) {
try {
typeClass = Utils.getClass(TypeNaming.TYPE_PACKAGE_UTIL + className);
} catch (ClassNotFoundException e3) {
try {
typeClass = Utils.getClass(TypeNaming.TYPE_PACKAGE_IO + className);
} catch (ClassNotFoundException e4) {
try {
typeClass = Utils.getClass(TypeNaming.TYPE_PACKAGE_MATH + className);
} catch (ClassNotFoundException e5) {
throw new ClassNotFoundException(className);
}
}
}
}
}
final List<TypeParameter<?>> typeParameters = new LinkedList<TypeParameter<?>>();
int arrayDimensions = 0;
for (int i = 0; i < tree.getChildCount(); i++) {
final Tree child = tree.getChild(i);
if (child.getType() == TypeLexer.ARRAY) {
arrayDimensions++;
} else {
switch (child.getType()) {
case TypeLexer.UNKNOWN:
typeParameters.add(WildcardTypeParameter.UNKNOWN);
break;
case TypeLexer.EXT:
Type<?> extendedType = createTypeFromTree(child.getChild(0));
typeParameters.add(new ExtendsTypeParameter<Object>((Type<Object>) extendedType));
break;
case TypeLexer.SUP:
Type<?> superType = createTypeFromTree(child.getChild(0));
typeParameters.add(new SuperTypeParameter<Object>((Type<Object>) superType));
break;
default:
Type<?> type = createTypeFromTree(child);
typeParameters.add(new StandardTypeParameter<Object>((Type<Object>) type));
}
}
}
// Maybe the type has been specified as raw without the wildcards
if (typeParameters.size() == 0) {
for (int i = 0; i < typeClass.getTypeParameters().length; i++) {
typeParameters.add(WildcardTypeParameter.UNKNOWN);
}
}
final TypeParameter[] typeParametersArray =
typeParameters.toArray(new TypeParameter[typeParameters.size()]);
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getType(typeClass, typeParametersArray, arrayDimensions);
}
static Class<?> computeRawClass(
final Class<?> componentClass, final int arrayDimensions) {
if (arrayDimensions == 0) {
return componentClass;
}
final int[] zeroDims = new int[arrayDimensions];
Arrays.fill(zeroDims, 0);
return Array.newInstance(componentClass, zeroDims).getClass();
}
static String createName(final Class<?> componentClass,
final TypeParameter<?>[] typeParameters, final int arrayDimensions) {
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(componentClass.getName());
if (typeParameters.length > 0) {
strBuilder.append(TypeNaming.TYPE_NAME_PARAMETERS_START);
strBuilder.append(
Utils.join(typeParameters, TypeNaming.TYPE_NAME_PARAMETERS_SEPARATOR));
strBuilder.append(TypeNaming.TYPE_NAME_PARAMETERS_END);
}
for (int i = 0; i < arrayDimensions; i++) {
strBuilder.append(TypeNaming.TYPE_NAME_ARRAY);
}
return strBuilder.toString().intern();
}
static String createSimpleName(final Class<?> componentClass,
final TypeParameter<?>[] typeParameters, final int arrayDimensions) {
final StringBuilder strBuilder = new StringBuilder();
strBuilder.append(componentClass.getSimpleName());
if (typeParameters.length > 0) {
strBuilder.append(TypeNaming.TYPE_NAME_PARAMETERS_START);
strBuilder.append(
Utils.join(typeParameters, TypeNaming.TYPE_NAME_PARAMETERS_SEPARATOR));
strBuilder.append(TypeNaming.TYPE_NAME_PARAMETERS_END);
}
for (int i = 0; i < arrayDimensions; i++) {
strBuilder.append(TypeNaming.TYPE_NAME_ARRAY);
}
return strBuilder.toString().intern();
}
@SuppressWarnings("unchecked")
static <T> Type<T> decreaseArrayDimensions(final Type<T[]> type) {
if (!type.isArray()) {
throw new IllegalStateException(
"Cannot get an array component type from a non-array type: " + type.getName());
}
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return (Type<T>) typeRegistry.getType(type.getComponentClass(), type.getTypeParametersArray(),(type.getArrayDimensions() - 1));
}
@SuppressWarnings("unchecked")
static <T> Type<T[]> increaseArrayDimensions(final Type<T> type) {
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return (Type<T[]>) typeRegistry.getType(type.getComponentClass(), type.getTypeParametersArray(),(type.getArrayDimensions() + 1));
}
static void validateTypeParameters(final Type<?> type) {
if (!isTypeParametersValid(type)) {
throw new TypeValidationException(
type.getName() + " is not a valid type " +
"according to definition " + type.getTypeDef());
}
}
private static boolean isTypeParametersValid(final Type<?> type) {
final TypeDefVariable[] typeDefVariables = type.getTypeDef().getVariables();
final TypeParameter<?>[] typeParameters = type.getTypeParametersArray();
if (typeDefVariables.length != typeParameters.length) {
return false;
}
final Map<String,TypeParameter<?>> checkedTypeParametersByName =
new HashMap<String, TypeParameter<?>>();
for (int i = 0; i < typeDefVariables.length; i++) {
if (typeParameters[i] == null) {
return false;
}
if (typeDefVariables[i] instanceof NamedTypeDefVariable) {
checkedTypeParametersByName.put(
typeDefVariables[i].getVariableName(),
typeParameters[i]);
} else { // typeDefVariables[i] instanceof BoundedTypeDefVariable
final BoundedTypeDefVariable boundedVar =
(BoundedTypeDefVariable) typeDefVariables[i];
final String variableName = boundedVar.getVariableName();
final InnerTypeDefVariable[] innerVariables = boundedVar.getBounds();
// A wildcard will always be checked. For the rest of types,
// we will need to resolve
if (!(typeParameters[i] instanceof WildcardTypeParameter)) {
final List<Type<?>> extendedTypes = resolveFormalExtendedTypes(
checkedTypeParametersByName, variableName,
typeParameters[i], innerVariables);
// If there was an error resolving inner types, return false
if (extendedTypes == null) {
return false;
}
for (Type<?> extendedType : extendedTypes) {
if (!extendedType.isAssignableFrom(typeParameters[i].getType())) {
return false;
}
}
}
// If we have not returned false, the type parameter can be
// considered checked
checkedTypeParametersByName.put(
typeDefVariables[i].getVariableName(),
typeParameters[i]);
}
}
return true;
}
private static List<Type<?>> resolveFormalExtendedTypes(
final Map<String, TypeParameter<?>> checkedTypeParametersByName,
final String currentVariableName, final TypeParameter<?> currentTypeParameter,
final InnerTypeDefVariable[] innerVariables) {
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
final List<Type<?>> types = new LinkedList<Type<?>>();
for (int i = 0; i < innerVariables.length; i++) {
if (innerVariables[i] instanceof InnerClassTypeDefVariable) {
/*
* We simply get the raw type (as it is not
* an InnerParameterizedTypeDefVariable) and add it to the
* types array.
*/
final InnerClassTypeDefVariable classVariable =
(InnerClassTypeDefVariable) innerVariables[i];
final Type<?> innerType =
getRawTypeForClass(
classVariable.getComponentClass(),
classVariable.getArrayDimensions());
types.add(innerType);
} else if (innerVariables[i] instanceof InnerNamedTypeDefVariable) {
/*
* We will check the variables which already have an assigned
* type parameter (checkedTypeParameters).
*/
final InnerNamedTypeDefVariable innerVariable =
(InnerNamedTypeDefVariable) innerVariables[i];
// We check if the variable has already been defined and checked
final TypeParameter<?> linkedTypeParameter =
checkedTypeParametersByName.get(
innerVariable.getVariableName());
// If variable has not been set before, return null
if (linkedTypeParameter == null) {
return null;
}
/*
* Basing on the linked type parameter, add the
* types which must conform
*/
if (linkedTypeParameter instanceof WildcardTypeParameter) {
// No types to be added, any type would be valid
} else if (linkedTypeParameter instanceof StandardTypeParameter<?>) {
types.add(linkedTypeParameter.getType());
} else if (linkedTypeParameter instanceof ExtendsTypeParameter<?>) {
types.add(linkedTypeParameter.getType());
} else { // linkedTypeParameter instanceof SuperTypeParameter
// No types to be added, any type would be valid
}
} else if (innerVariables[i] instanceof InnerWildcardTypeDefVariable) {
// This can never happen, as a Wildcard is not allowed here
throw new IllegalStateException("Wildcard should not appear " +
"at first level of 'extends' clause in type definition");
} else { // innerVariables[i] instanceof InnerParameterizedTypeTypeDefVariable
final InnerParameterizedTypeTypeDefVariable parameterizedVariable =
(InnerParameterizedTypeTypeDefVariable) innerVariables[i];
final TypeParameter<?>[] typeParameters =
resolveInnerParameterizedType(checkedTypeParametersByName,
currentVariableName, currentTypeParameter,
parameterizedVariable.getVariables());
if (typeParameters == null) {
// We have tried to solve a non-existing variable
return null;
}
final Class<?> componentClass =
parameterizedVariable.getComponentClass();
final int arrayDimensions = parameterizedVariable.getArrayDimensions();
final Type<?> parameterizedType =
typeRegistry.getTypeWithoutValidation(
componentClass, typeParameters, arrayDimensions);
types.add(parameterizedType);
}
}
return types;
}
@SuppressWarnings("unchecked")
private static TypeParameter<?>[] resolveInnerParameterizedType(
final Map<String, TypeParameter<?>> checkedTypeParametersByName,
final String currentVariableName, final TypeParameter<?> currentTypeParameter,
final InnerTypeDefVariable[] innerVariables) {
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
final TypeParameter<?>[] typeParameters =
new TypeParameter<?>[innerVariables.length];
for (int i = 0; i < innerVariables.length; i++) {
if (innerVariables[i] instanceof InnerClassTypeDefVariable) {
final InnerClassTypeDefVariable classVariable =
(InnerClassTypeDefVariable) innerVariables[i];
final Type<?> innerType =
getRawTypeForClass(
classVariable.getComponentClass(),
classVariable.getArrayDimensions());
typeParameters[i] =
new StandardTypeParameter(innerType);
} else if (innerVariables[i] instanceof InnerNamedTypeDefVariable) {
final InnerNamedTypeDefVariable innerVariable =
(InnerNamedTypeDefVariable) innerVariables[i];
// We check if the variable has already been defined and checked
TypeParameter<?> linkedTypeParameter =
checkedTypeParametersByName.get(
innerVariable.getVariableName());
// If variable has not been set before, check if we are
// linking to the current variable itself. If not, return null.
if (linkedTypeParameter == null) {
if (innerVariable.getVariableName().equals(currentVariableName)) {
linkedTypeParameter = currentTypeParameter;
} else {
return null;
}
}
// We need to take care of the array dimensions, and if it is
// more than 0, no wildcard-based type parameters will be
// allowed
if ((linkedTypeParameter instanceof WildcardTypeParameter) ||
(linkedTypeParameter instanceof ExtendsTypeParameter<?>) ||
(linkedTypeParameter instanceof SuperTypeParameter<?>)) {
return null;
}
// If it is allowed, compute the arrayDimensions
final Type<?> containedType = linkedTypeParameter.getType();
int newArrayDimensions =
containedType.getArrayDimensions() +
innerVariable.getArrayDimensions();
final Type<?> newType =
typeRegistry.getTypeWithoutValidation(
containedType.getComponentClass(),
containedType.getTypeParametersArray(),
newArrayDimensions);
typeParameters[i] = new StandardTypeParameter(newType);
} else if (innerVariables[i] instanceof InnerWildcardTypeDefVariable) {
final InnerWildcardTypeDefVariable wildcardVariable =
(InnerWildcardTypeDefVariable) innerVariables[i];
if (wildcardVariable.isUnbound()) {
typeParameters[i] = WildcardTypeParameter.UNKNOWN;
} else {
/*
* We need to recursively obtain the inner type
*/
InnerTypeDefVariable bound = null;
if (wildcardVariable.hasUpperBound()) {
bound = wildcardVariable.getUpperBound();
} else { // wildcardVariable.hasLowerBound() == true
bound = wildcardVariable.getLowerBound();
}
final TypeParameter<?>[] resolvedTypeParameters =
resolveInnerParameterizedType(checkedTypeParametersByName,
currentVariableName, currentTypeParameter,
new InnerTypeDefVariable[] { bound });
if (resolvedTypeParameters == null) {
return null;
}
if (resolvedTypeParameters.length != 1) {
throw new IllegalStateException("Wildcard variable " +
"is supposed to have a resolvable upper bound");
}
if (!(resolvedTypeParameters[0] instanceof StandardTypeParameter<?>)) {
throw new IllegalStateException("Wildcard variable " +
"is supposed to have a resolvable upper bound " +
"in the form of a Standard Type parameter");
}
final Type<?> type =
((StandardTypeParameter<?>) resolvedTypeParameters[0]).getType();
if (wildcardVariable.hasUpperBound()) {
typeParameters[i] = new ExtendsTypeParameter(type);
} else { // unknownVariable.hasLowerBound() == true
typeParameters[i] = new SuperTypeParameter(type);
}
}
} else { // innerVariables[i] instanceof InnerParameterizedTypeTypeDefVariable
final InnerParameterizedTypeTypeDefVariable parameterizedVariable =
(InnerParameterizedTypeTypeDefVariable) innerVariables[i];
final TypeParameter<?>[] innerTypeParameters =
resolveInnerParameterizedType(checkedTypeParametersByName,
currentVariableName, currentTypeParameter,
parameterizedVariable.getVariables());
if (innerTypeParameters == null) {
// We have tried to solve a non-existing variable
return null;
}
final Class<?> componentClass =
parameterizedVariable.getComponentClass();
final int arrayDimensions = parameterizedVariable.getArrayDimensions();
final Type<?> parameterizedType =
typeRegistry.getTypeWithoutValidation(
componentClass, innerTypeParameters, arrayDimensions);
typeParameters[i] = new StandardTypeParameter(parameterizedType);
}
}
return typeParameters;
}
static Type<?> getRawTypeForClass(final Class<?> typeClass) {
return getRawTypeForClass(typeClass, 0);
}
private static Type<?> getRawTypeForClass(
final Class<?> typeClass, final int arrayDimensions) {
Class<?> componentClass = typeClass;
int newArrayDimensions = arrayDimensions;
while (componentClass.isArray()) {
componentClass = componentClass.getComponentType();
newArrayDimensions++;
}
final TypeDef typeDef = TypeDefs.forClass(componentClass);
final TypeDefVariable[] variables = typeDef.getVariables();
final TypeParameter<?>[] typeParameters = new TypeParameter<?>[variables.length];
for (int i = 0; i < variables.length; i++) {
typeParameters[i] = WildcardTypeParameter.UNKNOWN;
}
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getType(componentClass, typeParameters, newArrayDimensions);
}
static Set<Type<?>> getExtendedTypes(final Type<?> type) {
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
final Set<Type<?>> equivalenceSet = new HashSet<Type<?>>();
if (Object.class.equals(type.getComponentClass())) {
// If we reached the Object class, then we only need to add
// all the Object-based classes down to array dimension zero.
int currentArrayDim = type.getArrayDimensions();
while (currentArrayDim > 0) {
currentArrayDim--;
equivalenceSet.add(
typeRegistry.getTypeWithoutValidation(Object.class, new TypeParameter<?>[0], currentArrayDim));
}
return equivalenceSet;
}
if (type.isInterface()) {
equivalenceSet.add(typeRegistry.getRawTypeForClass(Object.class));
}
final Class<?> componentClass = type.getComponentClass();
final java.lang.reflect.Type superclassTypeDeclaration =
componentClass.getGenericSuperclass();
if (superclassTypeDeclaration != null) {
final Type<?> superclassType = resolveExtendedTypeByDeclaration(type, superclassTypeDeclaration);
equivalenceSet.add(superclassType);
equivalenceSet.addAll(typeRegistry.getExtendedTypes(superclassType));
}
for (java.lang.reflect.Type interfaceTypeDeclaration : componentClass.getGenericInterfaces()) {
final Type<?> interfaceType = resolveExtendedTypeByDeclaration(type, interfaceTypeDeclaration);
equivalenceSet.add(interfaceType);
equivalenceSet.addAll(typeRegistry.getExtendedTypes(interfaceType));
}
return Collections.unmodifiableSet(equivalenceSet);
}
private static Type<?> resolveExtendedTypeByDeclaration(
final Type<?> originalType, final java.lang.reflect.Type typeDeclaration) {
final Map<String,TypeParameter<?>> typeParametersMap =
new HashMap<String, TypeParameter<?>>();
Class<?> componentClass = null;
if (typeDeclaration instanceof ParameterizedType) {
/*
* If the declaration is for a parameterized type and its
* declaration specifies values for its type parameters
* (like "<T,F>"), we will add the corresponding TypeParameter<?>
* objects to the type, using the own TypeParameter<?> objects of
* the containing (original) class.
*/
final ParameterizedType parameterizedTypeDeclaration =
(ParameterizedType) typeDeclaration;
// Get the type argument declarations as they appear in the
// original type (eg: "class Original implements Map<A,B>" ->
// "[A,B]")
final java.lang.reflect.Type[] parameterizedTypeDeclarationArguments =
parameterizedTypeDeclaration.getActualTypeArguments();
componentClass =
(Class<?>) parameterizedTypeDeclaration.getRawType();
// Get the type arguments as they are declared in the type declared
// itself as argument of the original type (eg: "class Map<K,V>" ->
// "[K,V]")
final TypeVariable<?>[] componentClassTypeParameters =
componentClass.getTypeParameters();
for (int i = 0; i < parameterizedTypeDeclarationArguments.length; i++) {
final TypeParameter<?> typeParameter =
resolveEquivalentTypeParameterByDeclaration(
originalType,
parameterizedTypeDeclarationArguments[i], 0);
typeParametersMap.put(
componentClassTypeParameters[i].getName(),
typeParameter);
}
} else {
/*
* If the declaration is not parameterized, it can mean either that
* the type has no type parameters or that it has type parameters
* but these have not been specified (raw type).
* In the first case, the type class is simply set as component
* class. In the second case, the type parameters are filled with
* wildcards (eg: "implements List" -> "implements List<?>").
*/
componentClass = (Class<?>) typeDeclaration;
for (int i = 0; i < componentClass.getTypeParameters().length; i++) {
typeParametersMap.put(
componentClass.getTypeParameters()[i].getName(),
WildcardTypeParameter.UNKNOWN);
}
}
final TypeDef typeDef = TypeDefs.forClass(componentClass);
final TypeParameter<?>[] typeParameters =
new TypeParameter<?>[typeDef.getVariables().length];
for (int i = 0; i < typeDef.getVariables().length; i++) {
typeParameters[i] =
typeParametersMap.get(typeDef.getVariables()[i].getVariableName());
}
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getTypeWithoutValidation(
componentClass, typeParameters, originalType.getArrayDimensions());
}
@SuppressWarnings("unchecked")
private static TypeParameter<?> resolveEquivalentTypeParameterByDeclaration(
final Type<?> originalType, final java.lang.reflect.Type typeDeclaration,
final int arrayDimensions) {
if (typeDeclaration instanceof TypeVariable<?>) {
/*
* The type argument is a variable, as in "List<E>"
*/
final String argumentName = ((TypeVariable<?>) typeDeclaration).getName();
// Return a type with the suitable array dimensions
final TypeParameter<?> typeParameter =
originalType.getTypeParameterForVariable(argumentName);
// For returning a TypeParameter<?>, we will have to make sure that
// the array dimensions of the type referred by the TypeParameter<?>
// correspond with the dimensions we are being requested plus
// the ones at the original type parameter.
if (typeParameter instanceof WildcardTypeParameter) {
// If it is a wildcard, simply return it
return typeParameter;
}
// If it is not a wildcard, we will extract the referred
// type and return the same type of TypeParameter<?>, but
// with the original arrayDimensions in the type plus
// the dimensions we are currently using.
if (arrayDimensions == 0) {
return typeParameter;
}
final Type<?> containedType = typeParameter.getType();
final int newArrayDimensions =
containedType.getArrayDimensions() + arrayDimensions;
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
final Type<?> newType =
typeRegistry.getTypeWithoutValidation(
containedType.getComponentClass(),
containedType.getTypeParametersArray(),
newArrayDimensions);
if (typeParameter instanceof StandardTypeParameter<?>) {
return new StandardTypeParameter(newType);
} else if (typeParameter instanceof ExtendsTypeParameter<?>){
return new ExtendsTypeParameter(newType);
} else { // typeParameter instanceof SuperTypeParameter
return new SuperTypeParameter(newType);
}
} else if (typeDeclaration instanceof GenericArrayType) {
final GenericArrayType genericArrayType =
(GenericArrayType) typeDeclaration;
return resolveEquivalentTypeParameterByDeclaration(
originalType, genericArrayType.getGenericComponentType(),
(arrayDimensions + 1));
} else {
/*
* The type argument is a specific type, as in "List<String>"
* It could be parameterized ("List<Comparable<E>>")
* or not ("List<String>")
*/
// We should propagate the new array dimensions
Type<?> baseType = originalType;
if (baseType.isArray()) {
TypeRegistry typeRegistry = TypeRegistry.getInstance();
baseType =
typeRegistry.getType(
baseType.getComponentClass(),
baseType.getTypeParametersArray(),
arrayDimensions);
}
// Create the appropiate type recursively
final Type<?> parameterizedTypeDeclarationArgumentType =
resolveExtendedTypeByDeclaration(baseType, typeDeclaration);
return new StandardTypeParameter(parameterizedTypeDeclarationArgumentType);
}
}
static Type<?> getTypeWithParameters(final Class<?> componentClass, final TypeParameter<?>... typeParameters) {
int arrayDimensions = 0;
Class<?> newTypeComponentClass = componentClass;
while (newTypeComponentClass.isArray()) {
arrayDimensions++;
newTypeComponentClass = newTypeComponentClass.getComponentType();
}
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getType(newTypeComponentClass, typeParameters, arrayDimensions);
}
static boolean isAssignableFrom(final Type<?> type, final Type<?> fromType) {
if (type.equals(fromType)) {
return true;
}
if (type.getComponentClass().equals(Object.class) &&
type.getArrayDimensions() <= fromType.getArrayDimensions()) {
return true;
}
if (isTypeAssignableFrom(type,fromType)) {
return true;
}
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
final Set<Type<?>> extendedTypes = typeRegistry.getExtendedTypes(fromType);
for (Type<?> extendedType : extendedTypes) {
if (isTypeAssignableFrom(type,extendedType)) {
return true;
}
}
return false;
}
private static boolean isTypeAssignableFrom(final Type<?> type, final Type<?> fromType) {
if (type.getArrayDimensions() != fromType.getArrayDimensions()) {
return false;
}
if (!type.getComponentClass().isAssignableFrom(fromType.getComponentClass())) {
return false;
}
if (type.getTypeParametersArray().length != fromType.getTypeParametersArray().length) {
return false;
}
for (int i = 0; i < type.getTypeParametersArray().length; i++) {
if (!type.getTypeParametersArray()[i].isAssignableFrom(fromType.getTypeParametersArray()[i])) {
return false;
}
}
return true;
}
static Type<?> getRawTypeForType(final Type<?> type) {
return getRawTypeForClass(type.getComponentClass(), type.getArrayDimensions());
}
public static TypeParameter<?> createFromJavaLangReflectTypeParameter(
final java.lang.reflect.Type originalType, final java.lang.reflect.Type type,
final Map<String,Type<?>> variableSubstitutions) {
return createFromJavaLangReflectTypeParameter(originalType, type, variableSubstitutions,
new HashSet<TypeVariable<?>>());
}
private static TypeParameter<?> createFromJavaLangReflectTypeParameter(
final java.lang.reflect.Type originalType, final java.lang.reflect.Type type,
final Map<String, Type<?>> variableSubstitutions, final Set<TypeVariable<?>> validatedTypeVars) {
if (type instanceof Class<?>) {
return TypeParameters.forType(
createFromJavaLangReflectType(originalType, type, variableSubstitutions, validatedTypeVars));
}
if (type instanceof GenericArrayType) {
return TypeParameters.forType(
createFromJavaLangReflectType(originalType, type, variableSubstitutions, validatedTypeVars));
}
if (type instanceof ParameterizedType) {
return TypeParameters.forType(
createFromJavaLangReflectType(originalType, type, variableSubstitutions, validatedTypeVars));
}
if (type instanceof TypeVariable<?>) {
final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
final java.lang.reflect.Type[] bounds = typeVariable.getBounds();
final Type<?> correspondingType =
variableSubstitutions.get(typeVariable.getName());
if (correspondingType == null) {
throw new TypeValidationException("No variable substitution established for variable " +
"\"" + typeVariable.getName() + "\" in type \"" + originalType + "\"");
} else if (!validatedTypeVars.contains(typeVariable)) {
validatedTypeVars.add(typeVariable);
} else {
return TypeParameters.forType(correspondingType);
}
/*
* Bounds here refer to declarations like:
* public <E extends Serializable> List<E> method() { ... }
* ...and thus variable substitutions will have to be validated
* against these bounds.
*/
for (java.lang.reflect.Type bound : bounds) {
final Type<?> boundType =
createFromJavaLangReflectType(originalType, bound, variableSubstitutions, validatedTypeVars);
if (!boundType.isAssignableFrom(correspondingType)) {
throw new TypeValidationException("Variable substitution established for variable " +
"\"" + typeVariable.getName() + "\" in type \"" + originalType + "\" is " +
"\"" + correspondingType + "\", which does not conform to upper bound \"extends " +
boundType + "\"");
}
}
return TypeParameters.forType(correspondingType);
}
if (type instanceof WildcardType) {
final WildcardType wildcardType = (WildcardType) type;
if (wildcardType.getLowerBounds() != null && wildcardType.getLowerBounds().length > 0) {
final java.lang.reflect.Type[] lowerBounds = wildcardType.getLowerBounds();
if (lowerBounds.length > 1) {
throw new TypeValidationException("Type parameter \"" + type + "\" cannot " +
"have more than one bound at this point in type \"" + originalType + "\"");
}
return TypeParameters.forSuperType(
createFromJavaLangReflectType(originalType, lowerBounds[0], variableSubstitutions,
validatedTypeVars));
} else if (wildcardType.getUpperBounds() != null && wildcardType.getUpperBounds().length > 0) {
final java.lang.reflect.Type[] upperBounds = wildcardType.getUpperBounds();
if (upperBounds.length > 1) {
throw new TypeValidationException("Type parameter \"" + type + "\" cannot " +
"have more than one bound at this point in type \"" + originalType + "\"");
}
return TypeParameters.forExtendsType(
createFromJavaLangReflectType(originalType, upperBounds[0], variableSubstitutions,
validatedTypeVars));
} else {
return TypeParameters.forUnknown();
}
}
throw new TypeValidationException("Specified \"" + type + "\" in type \"" + originalType +
"\" is of class \"" + type.getClass() + "\", which is " +
"not a recognized java.lang.reflect.Type implementation.");
}
public static Type<?> createFromJavaLangReflectType(
final java.lang.reflect.Type originalType, final java.lang.reflect.Type type,
final Map<String,Type<?>> variableSubstitutions) {
return createFromJavaLangReflectType(originalType, type, variableSubstitutions,
new HashSet<TypeVariable<?>>());
}
private static Type<?> createFromJavaLangReflectType(
final java.lang.reflect.Type originalType, final java.lang.reflect.Type type,
final Map<String, Type<?>> variableSubstitutions, final Set<TypeVariable<?>> validatedTypeVars) {
if (type instanceof Class<?>) {
final Class<?> classType = (Class<?>) type;
return Types.forClass(classType);
}
if (type instanceof GenericArrayType) {
final GenericArrayType genericArrayType = (GenericArrayType) type;
final Type<?> componentType =
createFromJavaLangReflectType(originalType, genericArrayType.getGenericComponentType(),
variableSubstitutions, validatedTypeVars);
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getType(componentType.getComponentClass(), componentType.getTypeParametersArray(),
componentType.getArrayDimensions() + 1);
}
if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) type;
final java.lang.reflect.Type[] actualTypeParameters = parameterizedType.getActualTypeArguments();
final TypeParameter<?>[] typeParameters = new TypeParameter<?>[actualTypeParameters.length];
for (int i = 0; i < actualTypeParameters.length; i++) {
typeParameters[i] =
createFromJavaLangReflectTypeParameter(originalType, actualTypeParameters[i],
variableSubstitutions, validatedTypeVars);
}
final Type<?> rawType = createFromJavaLangReflectType(originalType, parameterizedType.getRawType(),
variableSubstitutions, validatedTypeVars);
final TypeRegistry typeRegistry = TypeRegistry.getInstance();
return typeRegistry.getType(rawType.getComponentClass(), typeParameters, rawType.getArrayDimensions());
}
if (type instanceof TypeVariable<?>) {
final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
final java.lang.reflect.Type[] bounds = typeVariable.getBounds();
final Type<?> correspondingType =
variableSubstitutions.get(typeVariable.getName());
if (correspondingType == null) {
throw new TypeValidationException("No variable substitution established for variable " +
"\"" + typeVariable.getName() + "\" in type \"" + originalType + "\"");
} else if (!validatedTypeVars.contains(typeVariable)) {
validatedTypeVars.add(typeVariable);
} else {
return correspondingType;
}
/*
* Bounds here refer to declarations like:
* public <E extends Serializable> E method() { ... }
* ...and thus variable substitutions will have to be validated
* against these bounds.
*/
for (java.lang.reflect.Type bound : bounds) {
final Type<?> boundType =
createFromJavaLangReflectType(originalType, bound, variableSubstitutions, validatedTypeVars);
if (!boundType.isAssignableFrom(correspondingType)) {
throw new TypeValidationException("Variable substitution established for variable " +
"\"" + typeVariable.getName() + "\" in type \"" + originalType + "\" is " +
"\"" + correspondingType + "\", which does not conform to upper bound \"extends " +
boundType + "\"");
}
}
return correspondingType;
}
if (type instanceof WildcardType) {
throw new TypeValidationException("Cannot convert wildcard \"" + type + "\" in type \"" + originalType +
"\" into a javaRuntype type.");
}
throw new TypeValidationException("Specified \"" + type + "\" in type \"" + originalType +
"\" is of class \"" + type.getClass() + "\", which is " +
"not a recognized java.lang.reflect.Type implementation.");
}
private TypeUtil() {
super();
}
}
| |
/**
* Copyright (c) 2015 FeedHenry Ltd, All Rights Reserved.
*
* Please refer to your contract with FeedHenry for the software license agreement.
* If you do not have a contract, you do not have a license to use this software.
*/
package com.feedhenry.sdk.sync;
import java.util.Date;
import org.json.fh.JSONObject;
public class FHSyncPendingRecord {
private boolean inFight;
private Date inFlightDate;
private boolean crashed;
private boolean delayed = false;
private String action;
private long timestamp;
private String uid;
private FHSyncDataRecord preData;
private FHSyncDataRecord postData;
private String hashValue;
private int crashedCount;
private static final String KEY_INFLIGHT = "inFlight";
private static final String KEY_ACTION = "action";
private static final String KEY_TIMESTAMP = "timestamp";
private static final String KEY_UID = "uid";
private static final String KEY_PRE = "pre";
private static final String KEY_PRE_HASH = "preHash";
private static final String KEY_POST = "post";
private static final String KEY_POST_HASH = "postHash";
private static final String KEY_INFLIGHT_DATE = "inFlightDate";
private static final String KEY_CRASHED = "crashed";
private static final String KEY_DELAYED = "delayed";
private static final String KEY_WAITING_FOR = "waitingFor";
private static final String KEY_HASH = "hash";
private String waitingFor;
public FHSyncPendingRecord() {
this.timestamp = new Date().getTime();
}
public JSONObject getJSON() {
JSONObject ret = new JSONObject();
ret.put(KEY_INFLIGHT, this.inFight);
ret.put(KEY_CRASHED, this.crashed);
ret.put(KEY_DELAYED, this.delayed);
ret.put(KEY_TIMESTAMP, this.timestamp);
if (this.inFlightDate != null) {
ret.put(KEY_INFLIGHT_DATE, this.inFlightDate.getTime());
}
if (this.action != null) {
ret.put(KEY_ACTION, this.action);
}
if (this.uid != null) {
ret.put(KEY_UID, this.uid);
}
if (this.preData != null) {
ret.put(KEY_PRE, this.preData.getData());
ret.put(KEY_PRE_HASH, this.preData.getHashValue());
}
if (this.postData != null) {
ret.put(KEY_POST, this.postData.getData());
ret.put(KEY_POST_HASH, this.postData.getHashValue());
}
if (this.waitingFor != null) {
ret.put(KEY_WAITING_FOR, waitingFor);
}
return ret;
}
public static FHSyncPendingRecord fromJSON(JSONObject pObj) {
FHSyncPendingRecord record = new FHSyncPendingRecord();
if (pObj.has(KEY_INFLIGHT)) {
record.setInFlight(pObj.getBoolean(KEY_INFLIGHT));
}
if (pObj.has(KEY_INFLIGHT_DATE)) {
record.setInFlightDate(new Date(pObj.getLong(KEY_INFLIGHT_DATE)));
}
if (pObj.has(KEY_CRASHED)) {
record.setCrashed(pObj.getBoolean(KEY_CRASHED));
}
if (pObj.has(KEY_TIMESTAMP)) {
record.setTimestamp(pObj.getLong(KEY_TIMESTAMP));
}
if (pObj.has(KEY_ACTION)) {
record.setAction(pObj.getString(KEY_ACTION));
}
if (pObj.has(KEY_UID)) {
record.setUid(pObj.getString(KEY_UID));
}
if (pObj.has(KEY_PRE)) {
FHSyncDataRecord preData = new FHSyncDataRecord();
preData.setData(pObj.getJSONObject(KEY_PRE));
preData.setHashValue(pObj.getString(KEY_PRE_HASH));
record.setPreData(preData);
}
if (pObj.has(KEY_POST)) {
FHSyncDataRecord postData = new FHSyncDataRecord();
postData.setData(pObj.getJSONObject(KEY_POST));
postData.setHashValue(pObj.getString(KEY_POST_HASH));
record.setPostData(postData);
}
if (pObj.has(KEY_DELAYED)) {
record.delayed = pObj.getBoolean(KEY_DELAYED);
}
if (pObj.has(KEY_WAITING_FOR)) {
record.waitingFor = pObj.getString(KEY_WAITING_FOR);
}
return record;
}
public boolean equals(Object pThat) {
if (this == pThat) {
return true;
}
if (pThat instanceof FHSyncPendingRecord) {
FHSyncPendingRecord that = (FHSyncPendingRecord) pThat;
return this.getHashValue().equals(that.getHashValue());
} else {
return false;
}
}
public String toString() {
return this.getJSON().toString();
}
public boolean isInFlight() {
return inFight;
}
public void setInFlight(boolean inFight) {
this.inFight = inFight;
}
public Date getInFlightDate() {
return inFlightDate;
}
public void setInFlightDate(Date inFlightDate) {
this.inFlightDate = inFlightDate;
}
public boolean isCrashed() {
return crashed;
}
public void setCrashed(boolean crashed) {
this.crashed = crashed;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public FHSyncDataRecord getPreData() {
return preData;
}
public void setPreData(FHSyncDataRecord preData) {
this.preData = preData;
}
public FHSyncDataRecord getPostData() {
return postData;
}
public void setPostData(FHSyncDataRecord postData) {
this.postData = postData;
}
public String getHashValue() {
if (this.hashValue == null) {
JSONObject jsonobj = this.getJSON();
this.hashValue = FHSyncUtils.generateObjectHash(jsonobj);
}
return this.hashValue;
}
public void setHashValue(String hashValue) {
this.hashValue = hashValue;
}
public int getCrashedCount() {
return crashedCount;
}
public void incrementCrashCount() {
crashedCount++;
}
public void setCrashedCount(int crashedCount) {
this.crashedCount = crashedCount;
}
public boolean isDelayed() {
return this.delayed;
}
public void setDelayed(boolean delayed) {
this.delayed = delayed;
}
public String getWaitingFor() {
return waitingFor;
}
public void setWaitingFor(String waitingFor) {
this.waitingFor = waitingFor;
}
}
| |
/*
* @(#)HashMap.java 1.38 00/02/02
*
* Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package wrl.java.util;
//import java.io.*;
/**
* Hash table based implementation of the <tt>Map</tt> interface. This
* implementation provides all of the optional map operations, and permits
* <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
* class is roughly equivalent to <tt>Hashtable</tt>, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.<p>
*
* This implementation provides constant-time performance for the basic
* operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function
* disperses the elements properly among the buckets. Iteration over
* collection views requires time proportional to the "capacity" of the
* <tt>HashMap</tt> instance (the number of buckets) plus its size (the number
* of key-value mappings). Thus, it's very important not to set the intial
* capacity too high (or the load factor too low) if iteration performance is
* important.<p>
*
* An instance of <tt>HashMap</tt> has two parameters that affect its
* performance: <i>initial capacity</i> and <i>load factor</i>. The
* <i>capacity</i> is the number of buckets in the hash table, and the initial
* capacity is simply the capacity at the time the hash table is created. The
* <i>load factor</i> is a measure of how full the hash table is allowed to
* get before its capacity is automatically increased. When the number of
* entries in the hash table exceeds the product of the load factor and the
* current capacity, the capacity is roughly doubled by calling the
* <tt>rehash</tt> method.<p>
*
* As a general rule, the default load factor (.75) offers a good tradeoff
* between time and space costs. Higher values decrease the space overhead
* but increase the lookup cost (reflected in most of the operations of the
* <tt>HashMap</tt> class, including <tt>get</tt> and <tt>put</tt>). The
* expected number of entries in the map and its load factor should be taken
* into account when setting its initial capacity, so as to minimize the
* number of <tt>rehash</tt> operations. If the initial capacity is greater
* than the maximum number of entries divided by the load factor, no
* <tt>rehash</tt> operations will ever occur.<p>
*
* If many mappings are to be stored in a <tt>HashMap</tt> instance, creating
* it with a sufficiently large capacity will allow the mappings to be stored
* more efficiently than letting it perform automatic rehashing as needed to
* grow the table.<p>
*
* <b>Note that this implementation is not synchronized.</b> If multiple
* threads access this map concurrently, and at least one of the threads
* modifies the map structurally, it <i>must</i> be synchronized externally.
* (A structural modification is any operation that adds or deletes one or
* more mappings; merely changing the value associated with a key that an
* instance already contains is not a structural modification.) This is
* typically accomplished by synchronizing on some object that naturally
* encapsulates the map. If no such object exists, the map should be
* "wrapped" using the <tt>Collections.synchronizedMap</tt> method. This is
* best done at creation time, to prevent accidental unsynchronized access to
* the map: <pre> Map m = Collections.synchronizedMap(new HashMap(...));
* </pre><p>
*
* The iterators returned by all of this class's "collection view methods" are
* <i>fail-fast</i>: if the map is structurally modified at any time after the
* iterator is created, in any way except through the iterator's own
* <tt>remove</tt> or <tt>add</tt> methods, the iterator will throw a
* <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
*
* @author Josh Bloch
* @author Arthur van Hoff
* @version 1.38, 02/02/00
* @see Object#hashCode()
* @see Collection
* @see Map
* @see TreeMap
* @see Hashtable
* @since 1.2
*/
public class HashMap extends AbstractMap implements Map, Cloneable //,
/*java.io.Serializable*/ {
/**
* The hash table data.
*/
private transient Entry table[];
/**
* The total number of mappings in the hash table.
*/
private transient int count;
/**
* The table is rehashed when its size exceeds this threshold. (The
* value of this field is (int)(capacity * loadFactor).)
*
* @serial
*/
private int threshold;
/**
* The load factor for the hashtable.
*
* @serial
*/
private float loadFactor;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
private transient int modCount = 0;
/**
* Constructs a new, empty map with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the HashMap.
* @param loadFactor the load factor of the HashMap
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive.
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Initial Capacity: "+
initialCapacity);
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal Load factor: "+
loadFactor);
if (initialCapacity==0)
initialCapacity = 1;
this.loadFactor = loadFactor;
table = new Entry[initialCapacity];
threshold = (int)(initialCapacity * loadFactor);
}
/**
* Constructs a new, empty map with the specified initial capacity
* and default load factor, which is <tt>0.75</tt>.
*
* @param initialCapacity the initial capacity of the HashMap.
* @throws IllegalArgumentException if the initial capacity is less
* than zero.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, 0.75f);
}
/**
* Constructs a new, empty map with a default capacity and load
* factor, which is <tt>0.75</tt>.
*/
public HashMap() {
this(11, 0.75f);
}
/**
* Constructs a new map with the same mappings as the given map. The
* map is created with a capacity of twice the number of mappings in
* the given map or 11 (whichever is greater), and a default load factor,
* which is <tt>0.75</tt>.
*
* @param t the map whose mappings are to be placed in this map.
*/
public HashMap(Map t) {
this(Math.max(2*t.size(), 11), 0.75f);
putAll(t);
}
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map.
*/
public int size() {
return count;
}
/**
* Returns <tt>true</tt> if this map contains no key-value mappings.
*
* @return <tt>true</tt> if this map contains no key-value mappings.
*/
public boolean isEmpty() {
return count == 0;
}
/**
* Returns <tt>true</tt> if this map maps one or more keys to the
* specified value.
*
* @param value value whose presence in this map is to be tested.
* @return <tt>true</tt> if this map maps one or more keys to the
* specified value.
*/
public boolean containsValue(Object value) {
Entry tab[] = table;
if (value==null) {
for (int i = tab.length ; i-- > 0 ;)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value==null)
return true;
} else {
for (int i = tab.length ; i-- > 0 ;)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
}
return false;
}
/**
* Returns <tt>true</tt> if this map contains a mapping for the specified
* key.
*
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
* @param key key whose presence in this Map is to be tested.
*/
public boolean containsKey(Object key) {
Entry tab[] = table;
if (key != null) {
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if (e.hash==hash && key.equals(e.key))
return true;
} else {
for (Entry e = tab[0]; e != null; e = e.next)
if (e.key==null)
return true;
}
return false;
}
/**
* Returns the value to which this map maps the specified key. Returns
* <tt>null</tt> if the map contains no mapping for this key. A return
* value of <tt>null</tt> does not <i>necessarily</i> indicate that the
* map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
* operation may be used to distinguish these two cases.
*
* @return the value to which this map maps the specified key.
* @param key key whose associated value is to be returned.
*/
public Object get(Object key) {
Entry tab[] = table;
if (key != null) {
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if ((e.hash == hash) && key.equals(e.key))
return e.value;
} else {
for (Entry e = tab[0]; e != null; e = e.next)
if (e.key==null)
return e.value;
}
return null;
}
/**
* Rehashes the contents of this map into a new <tt>HashMap</tt> instance
* with a larger capacity. This method is called automatically when the
* number of keys in this map exceeds its capacity and load factor.
*/
private void rehash() {
int oldCapacity = table.length;
Entry oldMap[] = table;
int newCapacity = oldCapacity * 2 + 1;
Entry newMap[] = new Entry[newCapacity];
modCount++;
threshold = (int)(newCapacity * loadFactor);
table = newMap;
for (int i = oldCapacity ; i-- > 0 ;) {
for (Entry old = oldMap[i] ; old != null ; ) {
Entry e = old;
old = old.next;
int index = (e.hash & 0x7FFFFFFF) % newCapacity;
e.next = newMap[index];
newMap[index] = e;
}
}
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for this key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key. A <tt>null</tt> return can
* also indicate that the HashMap previously associated
* <tt>null</tt> with the specified key.
*/
public Object put(Object key, Object value) {
// Makes sure the key is not already in the HashMap.
Entry tab[] = table;
int hash = 0;
int index = 0;
if (key != null) {
hash = key.hashCode();
index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && key.equals(e.key)) {
Object old = e.value;
e.value = value;
return old;
}
}
} else {
for (Entry e = tab[0] ; e != null ; e = e.next) {
if (e.key == null) {
Object old = e.value;
e.value = value;
return old;
}
}
}
modCount++;
if (count >= threshold) {
// Rehash the table if the threshold is exceeded
rehash();
tab = table;
index = (hash & 0x7FFFFFFF) % tab.length;
}
// Creates the new entry.
Entry e = new Entry(hash, key, value, tab[index]);
tab[index] = e;
count++;
return null;
}
/**
* Removes the mapping for this key from this map if present.
*
* @param key key whose mapping is to be removed from the map.
* @return previous value associated with specified key, or <tt>null</tt>
* if there was no mapping for key. A <tt>null</tt> return can
* also indicate that the map previously associated <tt>null</tt>
* with the specified key.
*/
public Object remove(Object key) {
Entry tab[] = table;
if (key != null) {
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if ((e.hash == hash) && key.equals(e.key)) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count--;
Object oldValue = e.value;
e.value = null;
return oldValue;
}
}
} else {
for (Entry e = tab[0], prev = null; e != null;
prev = e, e = e.next) {
if (e.key == null) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[0] = e.next;
count--;
Object oldValue = e.value;
e.value = null;
return oldValue;
}
}
}
return null;
}
/**
* Copies all of the mappings from the specified map to this one.
*
* These mappings replace any mappings that this map had for any of the
* keys currently in the specified Map.
*
* @param t Mappings to be stored in this map.
*/
public void putAll(Map t) {
Iterator i = t.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry) i.next();
put(e.getKey(), e.getValue());
}
}
/**
* Removes all mappings from this map.
*/
public void clear() {
Entry tab[] = table;
modCount++;
for (int index = tab.length; --index >= 0; )
tab[index] = null;
count = 0;
}
/**
* Returns a shallow copy of this <tt>HashMap</tt> instance: the keys and
* values themselves are not cloned.
*
* @return a shallow copy of this map.
*/
public Object clone() {
try {
HashMap t = (HashMap)super.clone();
t.table = new Entry[table.length];
for (int i = table.length ; i-- > 0 ; ) {
t.table[i] = (table[i] != null)
? (Entry)table[i].clone() : null;
}
t.keySet = null;
t.entrySet = null;
t.values = null;
t.modCount = 0;
return t;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
// Views
private transient Set keySet = null;
private transient Set entrySet = null;
private transient Collection values = null;
/**
* Returns a set view of the keys contained in this map. The set is
* backed by the map, so changes to the map are reflected in the set, and
* vice-versa. The set supports element removal, which removes the
* corresponding mapping from this map, via the <tt>Iterator.remove</tt>,
* <tt>Set.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt>, and
* <tt>clear</tt> operations. It does not support the <tt>add</tt> or
* <tt>addAll</tt> operations.
*
* @return a set view of the keys contained in this map.
*/
public Set keySet() {
if (keySet == null) {
keySet = new AbstractSet() {
public Iterator iterator() {
return getHashIterator(KEYS);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
int oldSize = count;
HashMap.this.remove(o);
return count != oldSize;
}
public void clear() {
HashMap.this.clear();
}
};
}
return keySet;
}
/**
* Returns a collection view of the values contained in this map. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from this map, via the
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the values contained in this map.
*/
public Collection values() {
if (values==null) {
values = new AbstractCollection() {
public Iterator iterator() {
return getHashIterator(VALUES);
}
public int size() {
return count;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
HashMap.this.clear();
}
};
}
return values;
}
/**
* Returns a collection view of the mappings contained in this map. Each
* element in the returned collection is a <tt>Map.Entry</tt>. The
* collection is backed by the map, so changes to the map are reflected in
* the collection, and vice-versa. The collection supports element
* removal, which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Collection.remove</tt>,
* <tt>removeAll</tt>, <tt>retainAll</tt>, and <tt>clear</tt> operations.
* It does not support the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a collection view of the mappings contained in this map.
* @see Map.Entry
*/
public Set entrySet() {
if (entrySet==null) {
entrySet = new AbstractSet() {
public Iterator iterator() {
return getHashIterator(ENTRIES);
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
int hash = (key==null ? 0 : key.hashCode());
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index]; e != null; e = e.next)
if (e.hash==hash && e.equals(entry))
return true;
return false;
}
public boolean remove(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry entry = (Map.Entry)o;
Object key = entry.getKey();
Entry tab[] = table;
int hash = (key==null ? 0 : key.hashCode());
int index = (hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e.hash==hash && e.equals(entry)) {
modCount++;
if (prev != null)
prev.next = e.next;
else
tab[index] = e.next;
count--;
e.value = null;
return true;
}
}
return false;
}
public int size() {
return count;
}
public void clear() {
HashMap.this.clear();
}
};
}
return entrySet;
}
private Iterator getHashIterator(int type) {
if (count == 0) {
return emptyHashIterator;
} else {
return new HashIterator(type);
}
}
/**
* HashMap collision list entry.
*/
private static class Entry implements Map.Entry {
int hash;
Object key;
Object value;
Entry next;
Entry(int hash, Object key, Object value, Entry next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
protected Object clone() {
return new Entry(hash, key, value,
(next==null ? null : (Entry)next.clone()));
}
// Map.Entry Ops
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
public Object setValue(Object value) {
Object oldValue = this.value;
this.value = value;
return oldValue;
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
(value==null ? e.getValue()==null : value.equals(e.getValue()));
}
public int hashCode() {
return hash ^ (value==null ? 0 : value.hashCode());
}
public String toString() {
return key+"="+value;
}
}
// Types of Iterators
private static final int KEYS = 0;
private static final int VALUES = 1;
private static final int ENTRIES = 2;
private static EmptyHashIterator emptyHashIterator
= new EmptyHashIterator();
private static class EmptyHashIterator implements Iterator {
EmptyHashIterator() {
}
public boolean hasNext() {
return false;
}
public Object next() {
throw new NoSuchElementException();
}
public void remove() {
throw new IllegalStateException();
}
}
private class HashIterator implements Iterator {
Entry[] table = HashMap.this.table;
int index = table.length;
Entry entry = null;
Entry lastReturned = null;
int type;
/**
* The modCount value that the iterator believes that the backing
* List should have. If this expectation is violated, the iterator
* has detected concurrent modification.
*/
private int expectedModCount = modCount;
HashIterator(int type) {
this.type = type;
}
public boolean hasNext() {
Entry e = entry;
int i = index;
Entry t[] = table;
/* Use locals for faster loop iteration */
while (e == null && i > 0)
e = t[--i];
entry = e;
index = i;
return e != null;
}
public Object next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry et = entry;
int i = index;
Entry t[] = table;
/* Use locals for faster loop iteration */
while (et == null && i > 0)
et = t[--i];
entry = et;
index = i;
if (et != null) {
Entry e = lastReturned = entry;
entry = e.next;
return type == KEYS ? e.key : (type == VALUES ? e.value : e);
}
throw new NoSuchElementException();
}
public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry[] tab = HashMap.this.table;
int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
for (Entry e = tab[index], prev = null; e != null;
prev = e, e = e.next) {
if (e == lastReturned) {
modCount++;
expectedModCount++;
if (prev == null)
tab[index] = e.next;
else
prev.next = e.next;
count--;
lastReturned = null;
return;
}
}
throw new ConcurrentModificationException();
}
}
/**
* Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>capacity</i> of the HashMap (the length of the
* bucket array) is emitted (int), followed by the
* <i>size</i> of the HashMap (the number of key-value
* mappings), followed by the key (Object) and value (Object)
* for each key-value mapping represented by the HashMap
* The key-value mappings are emitted in no particular order.
*/
/* private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
s.writeInt(table.length);
// Write out size (number of Mappings)
s.writeInt(count);
// Write out keys and values (alternating)
for (int index = table.length-1; index >= 0; index--) {
Entry entry = table[index];
while (entry != null) {
s.writeObject(entry.key);
s.writeObject(entry.value);
entry = entry.next;
}
}
}
*/
// private static final long serialVersionUID = 362498820763181265L;
/**
* Reconstitute the <tt>HashMap</tt> instance from a stream (i.e.,
* deserialize it).
*/
/* private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();
// Read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();
table = new Entry[numBuckets];
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the HashMap
for (int i=0; i<size; i++) {
Object key = s.readObject();
Object value = s.readObject();
put(key, value);
}
}
*/
int capacity() {
return table.length;
}
float loadFactor() {
return loadFactor;
}
}
| |
/*
* Copyright (c) 2012 - 2016 Jadler contributors
* This program is made available under the terms of the MIT License.
*/
package net.jadler;
import java.nio.charset.Charset;
import net.jadler.exception.JadlerException;
import net.jadler.mocking.VerificationException;
import net.jadler.mocking.Verifying;
import net.jadler.stubbing.RequestStubbing;
import net.jadler.stubbing.server.StubHttpServerManager;
import net.jadler.stubbing.server.StubHttpServer;
import net.jadler.stubbing.ResponseStubbing;
/**
* <p>This class is a gateway to the whole Jadler library. Jadler is a powerful yet simple to use
* http mocking library for writing integration tests in the http environment. It provides a convenient way
* to create a stub http server which serves all http requests sent during a test execution
* by returning stub responses according to defined rules.</p>
*
* <h3>Jadler Usage Basics</h3>
*
* <p>Let's have a simple component with one operation: </p>
*
* <pre>
* public interface AccountManager {
* Account getAccount(String id);
* }
* </pre>
*
* <p>An implementation of the {@code getAccount} operation is supposed to send a GET http request to
* {@code /accounts/{id}} where {@code {id}} stands for the method {@code id} parameter, deserialize the http response
* to an {@code Account} instance and return it. If there is no such account (the GET request returned 404),
* {@code null} must be returned. If some problem occurs (50x http response), a runtime exception must be thrown.</p>
*
* <p>For the integration testing of this component it would be great to have a way to start a stub http server
* which would return predefined stub responses. This is where Jadler comes to help.</p>
*
* <p>Let's write such an integration test using <a href="http://junit.org" target="_blank">jUnit</a>:</p>
*
* <pre>
* ...
* import static net.jadler.Jadler.*;
* ...
*
* public class AccountManagerImplTest {
*
* private static final String ID = "123";
* private static final String ACCOUNT_JSON = "{\"account\":{\"id\": \"123\"}}";
*
*
* {@literal @}Before
* public void setUp() {
* initJadler();
* }
*
* {@literal @}After
* public void tearDown() {
* closeJadler();
* }
*
* {@literal @}Test
* public void getAccount() {
* onRequest()
* .havingMethodEqualTo("GET")
* .havingPathEqualTo("/accounts/" + ID)
* .respond()
* .withBody(ACCOUNT_JSON)
* .withStatus(200);
*
* final AccountManager am = new AccountManagerImpl("http", "localhost", port());
*
* final Account account = ag.getAccount(ID);
*
* assertThat(account, is(notNullValue()));
* assertThat(account.getId(), is(ID));
* }
* }
* </pre>
*
* <p>There are three main parts of this test. The <em>setUp</em> phase just initializes Jadler (which includes
* starting a stub http server), while the <em>tearDown</em> phase just closes all resources. Nothing
* interesting so far.</p>
*
* <p>All the magic happens in the test method. New http stub is defined, in the <em>THEN</em> part
* the http stub server is instructed to return a specific http response
* (200 http status with a body defined in the {@code ACCOUNT_JSON} constant) if the incoming http request
* fits the given conditions defined in the <em>WHEN</em> part (must be a GET request to {@code /accounts/123}).</p>
*
* <p>In order to communicate with the http stub server instead of the real web service, the tested instance
* must be configured to access {@code localhost} using the http protocol (https will be supported
* in a latter version of Jadler) connecting to a port which can be retrieved using the {@link Jadler#port()} method.</p>
*
* <p>The rest of the test method is business as usual. The {@code getAccount(String)} is executed and some
* assertions are evaluated.</p>
*
* <p>Now lets write two more test methods to test the 404 and 500 scenarios:</p>
*
* <pre>
* {@literal @}Test
* public void getAccountNotFound() {
* onRequest()
* .havingMethodEqualTo("GET")
* .havingPathEqualTo("/accounts/" + ID)
* .respond()
* .withStatus(404);
*
* final AccountManager am = new AccountManagerImpl("http", "localhost", port());
*
* Account account = am.getAccount(ID);
*
* assertThat(account, is(nullValue()));
* }
*
*
* {@literal @}Test(expected=RuntimeException.class)
* public void getAccountError() {
* onRequest()
* .havingMethodEqualTo("GET")
* .havingPathEqualTo("/accounts/" + ID)
* .respond()
* .withStatus(500);
*
* final AccountManager am = new AccountManagerImpl("http", "localhost", port());
*
* am.getAccount(ID);
* }
* </pre>
*
* <p>The first test method checks the {@code getAccount(String)} method returns {@code null} if 404 is returned
* from the server. The second one tests a runtime exception is thrown upon 500 http response.</p>
*
*
* <h3>Multiple responses definition</h3>
* <p>Sometimes you need to define more subsequent messages in your testing scenario. Let's test here
* your code can recover from an unexpected 500 response and retry the POST receiving 201 this time:</p>
*
* <pre>
* onRequest()
* .havingPathEqualTo("/accounts")
* .havingMethodEqualTo("POST")
* .respond()
* .withStatus(500)
* .thenRespond()
* .withStatus(201);
* </pre>
*
* <p>The stub server will return a stub http response with 500 response status for the first request
* which suits the stub rule. A stub response with 201 response status will be returned for the second request
* (and all subsequent requests as well).</p>
*
* <h3>More suitable stub rules</h3>
*
* <p>It's not uncommon that more stub rules can be applied (the incoming request fits more than one <em>WHEN</em>
* part). Let's have the following example: </p>
*
* <pre>
* onRequest()
* .havingPathEqualTo("/accounts")
* .respond()
* .withStatus(201);
*
* onRequest()
* .havingMethodEqualTo("POST")
* .respond()
* .withStatus(202);
* </pre>
*
* <p>If a POST http request was sent to {@code /accounts} both rules would be applicable. However, the latter stub
* gets priority over the former one. In this example, an http response with {@code 202} status code would be
* returned.</p>
*
* <h3>Advanced http stubbing</h3>
* <h4 id="stubbing">The <em>WHEN</em> part</h4>
* <p>So far two {@code having*} methods have been introduced,
* {@link RequestStubbing#havingMethodEqualTo(java.lang.String)} to check the http method equality and
* {@link RequestStubbing#havingPathEqualTo(java.lang.String)} to check the path equality. But there's more!</p>
*
* <p>You can use {@link RequestStubbing#havingBodyEqualTo(java.lang.String)} and
* {@link RequestStubbing#havingRawBodyEqualTo(byte[])}} to check the request body equality
* (either as a string or as an array of bytes).</p>
*
* <p>Feel free to to use {@link RequestStubbing#havingQueryStringEqualTo(java.lang.String)}
* to test the query string value.</p>
*
* <p>And finally don't hesitate to use {@link RequestStubbing#havingParameterEqualTo(java.lang.String, java.lang.String)}
* or {@link RequestStubbing#havingHeaderEqualTo(java.lang.String, java.lang.String)}
* for a check whether there is an http parameter / header in the incoming request with a given value.
* If an existence check is sufficient you can use {@link RequestStubbing#havingParameter(java.lang.String)},
* {@link RequestStubbing#havingParameters(java.lang.String[])} or
* {@link RequestStubbing#havingHeader(java.lang.String)}, {@link RequestStubbing#havingHeaders(java.lang.String[])}
* instead.</p>
*
* <p>So let's write some advanced http stub here: </p>
*
* <pre>
* onRequest()
* .havingMethodEqualTo("POST")
* .havingPathEqualTo("/accounts")
* .havingBodyEqualTo("{\"account\":{}}")
* .havingHeaderEqualTo("Content-Type", "application/json")
* .havingParameterEqualTo("force", "1")
* .respond()
* .withStatus(201);
* </pre>
*
* <p>The 201 stub response will be returned if the incoming request was a {@code POST} request to {@code /accounts}
* with the specified body, {@code application/json} content type header and a {@code force} http parameter set to
* {@code 1}.</p>
*
* <h4>The <em>THEN</em> part</h4>
* <p>There are much more options than just setting the http response status using the
* {@link net.jadler.stubbing.ResponseStubbing#withStatus(int)} in the <em>THEN</em> part of an http stub.</p>
*
* <p>You will probably have to define the stub response body as a string very often. That's what the
* {@link net.jadler.stubbing.ResponseStubbing#withBody(java.lang.String)} and
* {@link net.jadler.stubbing.ResponseStubbing#withBody(java.io.Reader)} methods are for. These
* are very often used in conjunction of
* {@link net.jadler.stubbing.ResponseStubbing#withEncoding(java.nio.charset.Charset)} to define the
* encoding of the response body</p>
*
* <p>If you'd like to define the stub response body binary, feel free to use either
* {@link net.jadler.stubbing.ResponseStubbing#withBody(byte[])} or
* {@link net.jadler.stubbing.ResponseStubbing#withBody(java.io.InputStream)}.</p>
*
* <p>Setting a stub response header is another common http stubbing use case. Just call
* {@link net.jadler.stubbing.ResponseStubbing#withHeader(java.lang.String, java.lang.String)} to
* set such header. For setting the {@code Content-Type} header you can use specially tailored
* {@link net.jadler.stubbing.ResponseStubbing#withContentType(java.lang.String)} method.</p>
*
* <p>And finally sometimes you would like to simulate a network latency. To do so just call the
* {@link net.jadler.stubbing.ResponseStubbing#withDelay(long, java.util.concurrent.TimeUnit)} method.
* The stub response will be returned after the specified amount of time or later.</p>
*
* <p>Let's define the <em>THEN</em> part precisely:</p>
*
* <pre>
* onRequest()
* .havingMethodEqualTo("POST")
* .havingPathEqualTo("/accounts")
* .havingBodyEqualTo("{\"account\":{}}")
* .havingHeaderEqualTo("Content-Type", "application/json")
* .havingParameterEqualTo("force", "1")
* .respond()
* .withDelay(2, SECONDS)
* .withStatus(201)
* .withBody("{\"account\":{\"id\" : 1}}")
* .withEncoding(Charset.forName("UTF-8"))
* .withContentType("application/json; charset=UTF-8")
* .withHeader("Location", "/accounts/1");
* </pre>
*
* <p>If the incoming http request fulfills the <em>WHEN</em> part, a stub response will be returned after at least
* 2 seconds. The response will have 201 status code, defined json body encoded using UTF-8 and both
* {@code Content-Type} and {@code Location} headers set to proper values.</p>
*
*
* <h3> Even more advanced http stubbing</h3>
*
* <h4>Fine-tuning the <em>WHEN</em> part using predicates</h4>
* <p>So far we have been using the equality check to define the <em>WHEN</em> part. However it's quite useful
* to be able to use other predicates (<em>non empty string</em>, <em>contains string</em>, ...) then just
* the request value equality.</p>
*
* <p>Jadler uses <a href="http://hamcrest.org" target="_blank">Hamcrest</a> as a predicates library. Not only
* it provides many already implemented predicates (called matchers) but also a simple way to implement
* your own ones if necessary. More on Hamcrest usage to be found in this
* <a href="http://code.google.com/p/hamcrest/wiki/Tutorial" target="_blank">tutorial</a>.</p>
*
* <p>So let's write the following stub: if an incoming request has a non-empty body and the request method
* is not PUT and the path value starts with <em>/accounts</em> then return an empty response
* with the 200 http status:</p>
*
* <pre>
* onRequest()
* .havingBody(not(isEmptyOrNullString()))
* .havingPath(startsWith("/accounts"))
* .havingMethod(not(equalToIgnoringCase("PUT")))
* .respond()
* .withStatus(200);
* </pre>
*
* <p>You can use following <em>having*</em> methods for defining the <em>WHEN</em> part
* using a Hamcrest string matcher: </p>
*
* <ul>
* <li>{@link RequestStubbing#havingBody(org.hamcrest.Matcher)}</li>
* <li>{@link RequestStubbing#havingMethod(org.hamcrest.Matcher)}</li>
* <li>{@link RequestStubbing#havingQueryString(org.hamcrest.Matcher)}</li>
* <li>{@link RequestStubbing#havingPath(org.hamcrest.Matcher)}</li>
* </ul>
*
* <p>For adding predicates about request parameters and headers use
* {@link RequestStubbing#havingHeader(java.lang.String, org.hamcrest.Matcher)} and
* {@link RequestStubbing#havingParameter(java.lang.String, org.hamcrest.Matcher)} methods. Since a request header or
* parameter can have more than one value, these methods accept a list of strings predicates.</p>
*
* <p>All introduced methods allow user to add a predicate about a part of an http request (body, method, ...).
* If you need to add a predicate about the whole request object (of type {@link Request}),
* you can use the {@link RequestStubbing#that(org.hamcrest.Matcher)} method: </p>
*
* <pre>
* //meetsCriteria() is some factory method returning a Matcher<Request> instance
*
* onRequest()
* .that(meetsCriteria())
* .respond()
* .withStatus(204);
* </pre>
*
*
* <h4>Fine-tuning the <em>THEN</em> part using defaults</h4>
*
* <p>It's pretty common many <em>THEN</em> parts share similar settings. Let's have two or more stubs returning
* an http response with 200 http status. Instead of calling {@link ResponseStubbing#withStatus(int)} during
* every stubbing Jadler can be instructed to use 200 as a default http status: </p>
*
* <pre>
* {@literal @}Before
* public void setUp() {
* initJadler()
* .withDefaultResponseStatus(200);
* }
* </pre>
*
* <p>This particular test setup configures Jadler to return http stub responses with 200 http
* status by default. This default can always be overwritten by calling the {@link ResponseStubbing#withStatus(int)}
* method in the particular stubbing.</p>
*
* <p>The following example demonstrates all response defaults options: </p>
*
* <pre>
* {@literal @}Before
* public void setUp() {
* initJadler()
* .withDefaultResponseStatus(202)
* .withDefaultResponseContentType("text/plain")
* .withDefaultResponseEncoding(Charset.forName("ISO-8859-1"))
* .withDefaultResponseHeader("X-DEFAULT-HEADER", "default_value");
* }
* </pre>
*
* <p>If not redefined in the particular stubbing, every stub response will have 202 http status, {@code Content-Type}
* header set to {@code text/plain}, response body encoded using {@code ISO-8859-1} and a header named
* {@code X-DEFAULT-HEADER} set to {@code default_value}.</p>
*
* <p>And finally if no default nor stubbing-specific status code is defined 200 will be used. And if no default
* nor stubbing-specific response body encoding is defined, {@code UTF-8} will be used by default.</p>
*
*
* <h3>Generating a stub response dynamically</h3>
*
* <p>In some integration testing scenarios it's necessary to generate a stub http response dynamically. This
* is a case where the {@code with*} methods aren't sufficient. However Jadler comes to help here with with
* the {@link net.jadler.stubbing.Responder} interface which allows to define the stub response dynamically
* according to the received request: </p>
*
* <pre>
* onRequest()
* .havingMethodEqualTo("POST")
* .havingPathEqualTo("/accounts")
* .respondUsing(new Responder() {
*
* private final AtomicInteger cnt = new AtomicInteger(1);
*
* {@literal @}Override
* public StubResponse nextResponse(final Request request) {
* final int current = cnt.getAndIncrement();
* final String headerValue = request.getHeaders().getValue("x-custom-request-header");
* return StubResponse.builder()
* .status(current % 2 == 0 ? 200 : 500)
* .header("x-custom-response-header", headerValue)
* .build();
* }
* });
* </pre>
*
* <p>The intention to define the stub response dynamically is expressed by using
* {@link net.jadler.stubbing.RequestStubbing#respondUsing(net.jadler.stubbing.Responder)}. This method takes
* a {@link net.jadler.stubbing.Responder} implementation as a parameter, Jadler subsequently uses the
* {@link net.jadler.stubbing.Responder#nextResponse(net.jadler.Request)} method to generate stub responses for
* all requests fitting the given <em>WHEN</em> part.</p>
*
* <p>In the previous example the http status of a stub response is {@code 200} for even requests and {@code 500}
* for odd requests. And the value of the {@code x-custom-request-header} request header is used as
* a response header.</p>
*
* <p>As you can see in the example this {@link net.jadler.stubbing.Responder} implementation is thread-safe
* (by using {@link java.util.concurrent.atomic.AtomicInteger} here). This is important for tests of parallel nature
* (more than one client can send requests fitting the <em>WHEN</em> part in parallel). Of course if requests are sent
* in a serial way (which is the most common case) there is no need for the thread-safety of the implementation.</p>
*
* <p>Please note this dynamic way of defining stub responses should be used as rarely as possible as
* it very often signalizes a problem either with test granularity or somewhere in the tested code. However there
* could be very specific testing scenarios where this functionality might be handy.</p>
*
*
* <h3>Request Receipt Verification</h3>
*
* <p>While the Jadler library is invaluable in supporting your test scenarios by providing a stub http server,
* it has even more to offer.</p>
*
* <p>Very often it's necessary not only to provide a stub http response but also to verify that a specific
* http request was received during a test execution. Let's add a removal operation to the already introduced
* {@code AccountManager} interface: </p>
*
* <pre>
* public interface AccountManager {
* Account getAccount(String id);
*
* void deleteAccount(String id);
* }
* </pre>
*
* <p>The {@code deleteAccount} operation is supposed to delete an account by sending a {@code DELETE} http request
* to {@code /accounts/{id}} where {@code {id}} stands for the operation {@code id} parameter. If the response status is
* 204 the removal is considered successful and the execution is finished successfully. Let's write an integration
* test for this scenario:</p>
*
* <pre>
* ...
* import static net.jadler.Jadler.*;
* ...
*
* public class AccountManagerImplTest {
*
* private static final String ID = "123";
*
* {@literal @}Before
* public void setUp() {
* initJadler();
* }
*
* {@literal @}After
* public void tearDown() {
* closeJadler();
* }
*
* {@literal @}Test
* public void deleteAccount() {
* onRequest()
* .havingMethodEqualTo("DELETE")
* .havingPathEqualTo("/accounts/" + ID)
* .respond()
* .withStatus(204);
*
* final AccountManager am = new AccountManagerImpl("http", "localhost", port());
*
* final Account account = am.deleteAccount(ID);
*
* verifyThatRequest()
* .havingMethodEqualTo("DELETE")
* .havingPathEqualTo("/accounts/" + ID)
.receivedOnce();
* }
* }
* </pre>
*
* <p>The first part of this test is business as usual. An http stub is created and the tested method
* {@code deleteAccount} is invoked. However in this test case we would like to test whether the {@code DELETE} http
* request was really sent during the execution of the method.</p>
*
* <p>This is where Jadler comes again to help. Calling {@link #verifyThatRequest()} signalizes an intention to
* verify a number of requests received so far meeting the given criteria. The criteria is defined using exactly
* the same {@code having*} methods which has been already described in the <a href="#stubbing">stubbing section</a>
* (the methods are defined in the {@link RequestMatching} interface).</p>
*
* <p>The request definition must be followed by calling one of the {@code received*} methods. The already
* introduced {@link Verifying#receivedOnce()} method verifies there has been received exactly one request meeting
* the given criteria so far. If the verification fails a {@link VerificationException} instance is thrown and
* the exact reason is logged on the {@code INFO} level.</p>
*
* <p>There are three more verification methods. {@link Verifying#receivedNever()} verifies there has not been
* received any request meeting the given criteria so far. {@link Verifying#receivedTimes(int)} allows to define
* the exact number of requests meeting the given criteria. And finally
* {@link Verifying#receivedTimes(org.hamcrest.Matcher)} allows to apply a Hamcrest matcher on the number of
* requests meeting the given criteria. The following example shows how to verify there have been at most
* 3 DELETE requests sent so far:</p>
*
* <pre>
* verifyThatRequest()
* .havingMethodEqualTo("DELETE")
* .receivedTimes(lessThan(4));
* </pre>
*
* <p>This verification feature is implemented by recording all incoming http requests (including their bodies). In
* some very specific corner cases this implementation can cause troubles. For example imagine a long running
* performance test using Jadler for stubbing some remote http service. Since such a test can issue thousands
* or even millions of requests the memory consumption probably would affect the test results (either
* by a performance slowdown or even crashes). In this specific scenarios you should consider disabling
* the incoming requests recording:</p>
*
* <pre>
* {@literal @}Before
* public void setUp() {
* initJadler()
* .withRequestsRecordingDisabled();
* }
* </pre>
*
* <p>Once the request recording has been disabled, calling {@link net.jadler.mocking.Mocker#verifyThatRequest()}
* will result in {@link IllegalStateException}.</p>
*
* <p>Please note you should ignore this option almost every time you use Jadler unless you are really
* convinced about it. Because premature optimization is the root of all evil, you know.</p>
*
* <h3>Jadler Lifecycle</h3>
*
* <p>As already demonstrated, the standard Jadler lifecycle consists of the following steps: </p>
*
* <ol>
* <li>starting Jadler including the underlying http server (by calling one of the {@code initJadler*} methods of the
* {@link Jadler} facade) in the <em>setUp</em> phase of a test</li>
*
* <li>stubbing using the {@link Jadler#onRequest()} method at the beginning of the test method</li>
*
* <li>calling the code to be tested</li>
*
* <li>doing some verification using {@link Jadler#verifyThatRequest()} if necessary</li>
*
* <li>closing Jadler including the underlying http server (by calling the {@link Jadler#closeJadler()}) method
* in the <em>tearDown</em> phase of a test</li>
* </ol>
*
* <p>These steps are then repeated for every test in a test suite. This lifecycle is fully covered by the static
* {@link Jadler} facade which encapsulates and manages an instance of the core {@link JadlerMocker} component.</p>
*
* <h4>Creating mocker instances manually</h4>
*
* <p>There are few specific scenarios when creating {@link JadlerMocker} instances manually (instead of using the
* {@link Jadler} facade) can be handy. Some specific integration tests may require starting more than just one mocker
* on different ports (simulating requesting multiple different http servers). If this is the case,
* all the mocker instances have to be created manually (since the facade encapsulates just one mocker instance).</p>
*
* <p>To achieve this each mocker must be created and disposed before and after every test: </p>
*
* <pre>
* public class ManualTest {
*
* private JadlerMocker mocker;
* private int port;
*
* {@literal @}Before
* public void setUp() {
* mocker = new JadlerMocker(new JettyStubHttpServer());
* mocker.start();
* port = getStubHttpServerPort();
* }
*
* {@literal @}After
* public void tearDown() {
* mocker.close();
* }
*
* {@literal @}Test
* public void testSomething() {
* mocker.onRequest().respond().withStatus(404);
*
* //call the code to be tested here
*
* mocker.verifyThatRequest().receivedOnce();
* }
* }
* </pre>
*
*
* <h4>Simplified Jadler Lifecycle Management</h4>
*
* <p>In all previous examples the jUnit {@literal @}Before and {@literal @}After sections were used to manage
* the Jadler lifecycle. If jUnit 4.11 (or newer) is on the classpath a simple Jadler
* <a href="https://github.com/junit-team/junit/wiki/Rules">rule</a> {@link net.jadler.junit.rule.JadlerRule}
* can be used instead:</p>
*
* <pre>
* public class AccountManagerImplTest {
*
* {@literal @}Rule
* public JadlerRule jadlerRule = new JadlerRule();
*
* ...
* }
* </pre>
*
* <p>This piece of code starts Jadler on a random port at the beginning of each test and closes it at the end.
* A specific port can be defined as well: {@code new JadlerRule(12345);}. Please note this is exactly the same as
* calling {@link Jadler#initJadler()} and {@link Jadler#closeJadler()} in the {@code setUp} and {@code tearDown}
* methods.</p>
*
* <p>To use this rule the {@code jadler-junit} artifact must be on the classpath.</p>
*/
public class Jadler {
//since jUnit might execute tests in a thread other than the thread executing the setup and teardown methods
//when specific conditions are met (a timeout value is specified for the given
//test, see http://junit.org/apidocs/org/junit/Test.html for details), the thread local container
//is inheritable so the content is copied automatically to the child thread
private static final ThreadLocal<JadlerMocker> jadlerMockerContainer = new InheritableThreadLocal<JadlerMocker>();
private static final String JETTY_SERVER_CLASS = "net.jadler.stubbing.server.jetty.JettyStubHttpServer";
private Jadler() {
//gtfo
}
/**
* <p>Initializes Jadler and starts a default stub server {@link net.jadler.stubbing.server.jetty.JettyStubHttpServer}
* serving the http protocol listening on any free port. The port number can be retrieved using {@link #port()}.</p>
*
* <p>This should be preferably called in the {@code setUp} method of the test suite.</p>
*
* @return {@link OngoingConfiguration} instance for additional configuration and tweaking
* (use its {@code with*} methods)
*/
public static OngoingConfiguration initJadler() {
return initInternal(new JadlerMocker(getJettyServer()));
}
/**
* <p>Initializes Jadler and starts a default stub server {@link net.jadler.stubbing.server.jetty.JettyStubHttpServer}
* serving the http protocol listening on the given port.</p>
*
* <p>This should be preferably called in the {@code setUp} method of the test suite.</p>
*
* @param port port the stub server will be listening on
* @return {@link OngoingConfiguration} instance for additional configuration and tweaking
* (use its {@code with*} methods)
*/
public static OngoingConfiguration initJadlerListeningOn(final int port) {
return initInternal(new JadlerMocker(getJettyServer(port)));
}
/**
* <p>Initializes Jadler and starts the given {@link StubHttpServer}.</p>
*
* <p>This should be preferably called in the {@code setUp} method of the test suite</p>
*
* @param server stub http server instance
* @return {@link OngoingConfiguration} instance for additional configuration and tweaking
* (use its {@code with*} methods)
*/
public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) {
return initInternal(new JadlerMocker(server));
}
/**
* <p>Stops the underlying {@link StubHttpServer} and closes Jadler.</p>
*
* <p>This should be preferably called in the {@code tearDown} method of a test suite.</p>
*/
public static void closeJadler() {
final StubHttpServerManager serverManager = jadlerMockerContainer.get();
if (serverManager != null && serverManager.isStarted()) {
serverManager.close();
}
jadlerMockerContainer.set(null);
}
/**
* <p>Resets Jadler by clearing all previously created stubs as well as stored received requests.</p>
*
* <p>While the standard Jadler lifecycle consists of initializing Jadler and starting the
* underlying stub server (using {@link #initJadler()}) in the <em>setUp</em> section of a test and stopping
* the server (using {@link #closeJadler()}) in the <em>tearDown</em> section, in some specific scenarios
* it could be useful to reuse initialized Jadler in all tests instead.</p>
*
* <p>Here's an example code using jUnit which demonstrates usage of this method in a test lifecycle:</p>
*
* <pre>
* public class JadlerResetIntegrationTest {
*
* {@literal @}BeforeClass
* public static void beforeTests() {
* initJadler();
* }
*
* {@literal @}AfterClass
* public static void afterTests() {
* closeJadler();
* }
*
* {@literal @}After
* public void reset() {
* resetJadler();
* }
*
* {@literal @}Test
* public void test1() {
* mocker.onRequest().respond().withStatus(201);
*
* //do an http request here, 201 should be returned from the stub server
*
* verifyThatRequest().receivedOnce();
* }
*
* {@literal @}Test
* public void test2() {
* mocker.onRequest().respond().withStatus(400);
*
* //do an http request here, 400 should be returned from the stub server
*
* verifyThatRequest().receivedOnce();
* }
* }
* </pre>
*
* <p>Please note the standard lifecycle should be always preferred since it ensures a full independence
* of all tests in a suite. However performance issues may appear theoretically while starting and stopping
* the server as a part of each test. If this is your case the alternative lifecycle might be handy.</p>
*
* <p>Also note that calling this method in a test body <strong>always</strong> signalizes a poorly written test
* with a problem with the granularity. In this case consider writing more fine grained tests instead of using this
* method.</p>
*
* @see JadlerMocker#reset()
*/
public static void resetJadler() {
final JadlerMocker mocker = jadlerMockerContainer.get();
if (mocker != null) {
mocker.reset();
}
}
/**
* Use this method to retrieve the port the underlying http stub server is listening on
* @return the port the underlying http stub server is listening on
* @throws IllegalStateException if Jadler has not been initialized yet
*/
public static int port() {
checkInitialized();
return jadlerMockerContainer.get().getStubHttpServerPort();
}
/**
* Starts new http stubbing (defining new <i>WHEN</i>-<i>THEN</i> rule).
* @return stubbing object for ongoing stubbing
*/
public static RequestStubbing onRequest() {
checkInitialized();
return jadlerMockerContainer.get().onRequest();
}
/**
* Starts new verification (checking that an http request with given properties was or was not received)
* @return verifying object for ongoing verifying
*/
public static Verifying verifyThatRequest() {
checkInitialized();
return jadlerMockerContainer.get().verifyThatRequest();
}
private static void checkInitialized() {
if (jadlerMockerContainer.get() == null) {
throw new IllegalStateException("Jadler has not been initialized yet.");
}
}
private static OngoingConfiguration initInternal(final JadlerMocker jadlerMocker) {
if (jadlerMockerContainer.get() != null) {
throw new IllegalStateException("Jadler seems to have been initialized already.");
}
jadlerMockerContainer.set(jadlerMocker);
jadlerMocker.start();
return OngoingConfiguration.INSTANCE;
}
private static StubHttpServer getJettyServer() {
final Class<?> clazz = getJettyStubHttpServerClass();
try {
return (StubHttpServer) clazz.newInstance();
}
catch (final Exception e) {
throw new JadlerException("Cannot instantiate default Jetty stub server", e);
}
}
private static StubHttpServer getJettyServer(final int port) {
final Class<?> clazz = getJettyStubHttpServerClass();
try {
return (StubHttpServer) clazz.getConstructor(int.class).newInstance(port);
}
catch (final Exception e) {
throw new JadlerException("Cannot instantiate default Jetty stub server with the given port", e);
}
}
private static Class<?> getJettyStubHttpServerClass() {
try {
return Class.forName(JETTY_SERVER_CLASS);
}
catch (final ClassNotFoundException e) {
throw new JadlerException("Class " + JETTY_SERVER_CLASS + " cannot be found. "
+ "Either add jadler-jetty to your classpath or use the initJadlerUsing method to specify the "
+ "stub server explicitly.", e);
}
}
/**
* This class serves as a DSL support for additional Jadler configuration.
*/
public static class OngoingConfiguration implements JadlerConfiguration {
private static final OngoingConfiguration INSTANCE = new OngoingConfiguration();
private OngoingConfiguration() {
//private constructor, instances of this class should never be created directly
}
/**
* @return this ongoing configuration
* @deprecated added just for backward compatibility reasons, does nothing but returning this ongoing
* configuration instance. Use the configuration methods of this instance directly instead.
*/
@Deprecated
public OngoingConfiguration that() {
return this;
}
/**
* @deprecated use {@link #withDefaultResponseStatus(int)} instead
*
* Sets the default http response status. This value will be used for all stub responses with no
* specific http status defined. (see {@link ResponseStubbing#withStatus(int)})
* @param defaultStatus default http response status
* @return this ongoing configuration
*/
@Deprecated
public OngoingConfiguration respondsWithDefaultStatus(final int defaultStatus) {
return this.withDefaultResponseStatus(defaultStatus);
}
/**
* {@inheritDoc}
*/
@Override
public OngoingConfiguration withDefaultResponseStatus(final int defaultStatus) {
jadlerMockerContainer.get().setDefaultStatus(defaultStatus);
return this;
}
/**
* @deprecated use {@link #withDefaultResponseHeader(java.lang.String, java.lang.String)} instead
*
* Defines a response header that will be sent in every http stub response.
* Can be called repeatedly to define more headers.
* @param name name of the header
* @param value header value
* @return this ongoing configuration
*/
@Deprecated
public OngoingConfiguration respondsWithDefaultHeader(final String name, final String value) {
return this.withDefaultResponseHeader(name, value);
}
/**
* {@inheritDoc}
*/
@Override
public OngoingConfiguration withDefaultResponseHeader(final String name, final String value) {
jadlerMockerContainer.get().addDefaultHeader(name, value);
return this;
}
/**
* @deprecated use {@link #withDefaultResponseEncoding(java.nio.charset.Charset)} instead
*
* Defines a default encoding of every stub http response. This value will be used for all stub responses
* with no specific encoding defined. (see {@link ResponseStubbing#withEncoding(java.nio.charset.Charset)})
* @param defaultEncoding default stub response encoding
* @return this ongoing configuration
*/
@Deprecated
public OngoingConfiguration respondsWithDefaultEncoding(final Charset defaultEncoding) {
return this.withDefaultResponseEncoding(defaultEncoding);
}
/**
* {@inheritDoc}
*/
@Override
public OngoingConfiguration withDefaultResponseEncoding(final Charset defaultEncoding) {
jadlerMockerContainer.get().setDefaultEncoding(defaultEncoding);
return this;
}
/**
* @deprecated use {@link #withRequestsRecordingDisabled()} instead
*
* <p>Disables incoming http requests recording.</p>
*
* <p>Jadler mocking (verification) capabilities are implemented by storing all incoming requests (including their
* bodies). This could cause troubles in some very specific testing scenarios, for further explanation jump
* straight to {@link JadlerMocker#setRecordRequests(boolean)}.</p>
*
* <p>Please note this method should be used very rarely and definitely should not be treated as a default.</p>
*
* @see JadlerMocker#setRecordRequests(boolean)
* @return this ongoing configuration
*/
@Deprecated
public OngoingConfiguration skipsRequestsRecording() {
return this.withRequestsRecordingDisabled();
}
/**
* {@inheritDoc}
*/
@Override
public OngoingConfiguration withRequestsRecordingDisabled() {
jadlerMockerContainer.get().setRecordRequests(false);
return this;
}
/**
* @deprecated use {@link #withDefaultResponseContentType(java.lang.String)} instead
*
* Defines a default content type of every stub http response. This value will be used for all stub responses
* with no specific content type defined. (see {@link ResponseStubbing#withContentType(java.lang.String)})
* @param defaultContentType default {@code Content-Type} header of every http stub response
* @return this ongoing configuration
*/
@Deprecated
public OngoingConfiguration respondsWithDefaultContentType(final String defaultContentType) {
return this.withDefaultResponseContentType(defaultContentType);
}
/**
* {@inheritDoc}
*/
@Override
public OngoingConfiguration withDefaultResponseContentType(final String defaultContentType) {
return this.withDefaultResponseHeader("Content-Type", defaultContentType);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.