answer
stringlengths 17
10.2M
|
|---|
package org.eclipse.birt.chart.reportitem;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.birt.chart.computation.withaxes.SharedScaleContext;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.factory.Generator;
import org.eclipse.birt.chart.factory.IExternalizer;
import org.eclipse.birt.chart.factory.IResourceFinder;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.log.Logger;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.attribute.Anchor;
import org.eclipse.birt.chart.model.attribute.ChartDimension;
import org.eclipse.birt.chart.model.attribute.DataPointComponent;
import org.eclipse.birt.chart.model.attribute.FormatSpecifier;
import org.eclipse.birt.chart.model.attribute.LegendItemType;
import org.eclipse.birt.chart.model.attribute.NumberFormatSpecifier;
import org.eclipse.birt.chart.model.attribute.Position;
import org.eclipse.birt.chart.model.attribute.impl.FormatSpecifierImpl;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.model.component.impl.LabelImpl;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.impl.ChartImpl;
import org.eclipse.birt.chart.model.impl.SerializerImpl;
import org.eclipse.birt.chart.reportitem.i18n.Messages;
import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin;
import org.eclipse.birt.chart.script.IChartEventHandler;
import org.eclipse.birt.chart.script.internal.ChartWithAxesImpl;
import org.eclipse.birt.chart.script.internal.ChartWithoutAxesImpl;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.ModuleUtil;
import org.eclipse.birt.report.model.api.MultiViewsHandle;
import org.eclipse.birt.report.model.api.extension.ExtendedElementException;
import org.eclipse.birt.report.model.api.extension.IChoiceDefinition;
import org.eclipse.birt.report.model.api.extension.ICompatibleReportItem;
import org.eclipse.birt.report.model.api.extension.IElementCommand;
import org.eclipse.birt.report.model.api.extension.IPropertyDefinition;
import org.eclipse.birt.report.model.api.extension.IReportItem;
import org.eclipse.birt.report.model.api.extension.ReportItem;
import org.eclipse.birt.report.model.api.metadata.IMethodInfo;
import org.eclipse.birt.report.model.api.metadata.IPropertyType;
import org.eclipse.emf.common.util.EList;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.RhinoException;
import com.ibm.icu.util.ULocale;
/**
* ChartReportItemImpl
*/
public final class ChartReportItemImpl extends ReportItem implements
ICompatibleReportItem,
IResourceFinder,
IExternalizer
{
private Chart cm = null;
private Object oDesignerRepresentation = null;
private static final List<IChoiceDefinition> liLegendPositions = new LinkedList<IChoiceDefinition>( );
private static final List<IChoiceDefinition> liLegendAnchors = new LinkedList<IChoiceDefinition>( );
private static final List<IChoiceDefinition> liChartDimensions = new LinkedList<IChoiceDefinition>( );
private transient ExtendedItemHandle handle = null;
private transient SharedScaleContext sharedScale = null;
private transient boolean bCopied = false;
private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$
static
{
// SUPPRESS EVERYTHING EXCEPT FOR ERRORS
// DefaultLoggerImpl.instance().setVerboseLevel(ILogger.ERROR);
// SETUP LEGEND POSITION CHOICE LIST
List li = Position.VALUES;
Iterator it = li.iterator( );
IChoiceDefinition icd;
String sName, sLowercaseName;
while ( it.hasNext( ) )
{
sName = ( (Position) it.next( ) ).getName( );
sLowercaseName = sName.toLowerCase( Locale.US );
if ( sLowercaseName.equals( "outside" ) ) //$NON-NLS-1$
{
continue;
}
icd = new ChartChoiceDefinitionImpl( "choice.legend.position." + sLowercaseName, sName, null ); //$NON-NLS-1$
liLegendPositions.add( icd );
}
// SETUP LEGEND ANCHOR CHOICE LIST
li = Anchor.VALUES;
it = li.iterator( );
while ( it.hasNext( ) )
{
sName = ( (Anchor) it.next( ) ).getName( );
sLowercaseName = sName.toLowerCase( Locale.US );
icd = new ChartChoiceDefinitionImpl( "choice.legend.anchor." + sLowercaseName, sName, null ); //$NON-NLS-1$
liLegendAnchors.add( icd );
}
// SETUP CHART DIMENSION CHOICE LIST
li = ChartDimension.VALUES;
it = li.iterator( );
while ( it.hasNext( ) )
{
sName = ( (ChartDimension) it.next( ) ).getName( );
sLowercaseName = sName.toLowerCase( Locale.US );
icd = new ChartChoiceDefinitionImpl( "choice.chart.dimension." + sLowercaseName, sName, null ); //$NON-NLS-1$
liChartDimensions.add( icd );
}
};
/**
* The construcotor.
*/
public ChartReportItemImpl( ExtendedItemHandle handle )
{
this.handle = handle;
}
/**
* Set the chart directly (no command)
*/
public void setModel( Chart chart )
{
this.cm = chart;
}
/**
* Set the shared scale directly (no command)
*/
public void setSharedScale( SharedScaleContext sharedScale )
{
this.sharedScale = sharedScale;
}
/**
* Returns the design element handle.
*/
public ExtendedItemHandle getHandle( )
{
return this.handle;
}
/**
* Sets the design element handle.
*/
public void setHandle( ExtendedItemHandle handle )
{
if ( this.handle != handle )
{
this.handle = handle;
}
else
{
// When two handles are equal, hostChart reference should be
// updated, so copy state should clean.
this.bCopied = false;
}
}
public void executeSetSimplePropertyCommand( DesignElementHandle eih,
String propName, Object oldValue, Object newValue )
{
if ( handle == null )
{
return;
}
IElementCommand command = new ChartSimplePropertyCommandImpl( eih,
this,
propName,
newValue,
oldValue );
this.handle.getModuleHandle( ).getCommandStack( ).execute( command );
}
/**
* Set the new chart through a command for command stack integration
*/
public void executeSetModelCommand( ExtendedItemHandle eih, Chart oldChart,
Chart newChart )
{
if ( handle == null )
{
return;
}
IElementCommand command = new ChartElementCommandImpl( eih,
this,
oldChart,
newChart );
this.handle.getModuleHandle( ).getCommandStack( ).execute( command );
}
/**
* @param oDesignerRepresentation
*/
public final void setDesignerRepresentation( Object oDesignerRepresentation )
{
this.oDesignerRepresentation = oDesignerRepresentation;
}
public final Object getDesignerRepresentation( )
{
return oDesignerRepresentation;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#serialize(java.lang.String)
*/
public ByteArrayOutputStream serialize( String propName )
{
if ( propName != null
&& propName.equalsIgnoreCase( ChartReportItemUtil.PROPERTY_XMLPRESENTATION ) )
{
if ( !ChartXTabUtil.isAxisChart( handle ) )
{
// Do not serialize axis chart, since it always uses reference
// as chart model
try
{
return SerializerImpl.instance( ).asXml( cm, true );
}
catch ( Exception e )
{
logger.log( e );
return new ByteArrayOutputStream( );
}
}
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#deserialize(java.lang.String,
* java.io.ByteArrayInputStream)
*/
public void deserialize( String propName, ByteArrayInputStream data )
throws ExtendedElementException
{
if ( propName != null
&& propName.equalsIgnoreCase( ChartReportItemUtil.PROPERTY_XMLPRESENTATION ) )
{
try
{
cm = SerializerImpl.instance( ).fromXml( data, true );
doCompatibility( cm );
// This fix is only for SCR 95978, for the version 3.2.10 of
// report design file and previous version.
String reportVer = handle.getModuleHandle( ).getVersion( );
adjustNumberFormat( reportVer );
}
catch ( IOException e )
{
logger.log( e );
cm = null;
}
}
}
private void doCompatibility( Chart cm )
{
// we use the base series' format specifier for category legend
// before.
// for compatibility after the fix of #237578
if ( cm.getLegend( ).getItemType( ) == LegendItemType.CATEGORIES_LITERAL )
{
SeriesDefinition sdBase = ChartUtil.getBaseSeriesDefinitions( cm )
.get( 0 );
if ( cm.getLegend( ).getFormatSpecifier( ) == null
&& sdBase.getFormatSpecifier( ) != null )
{
cm.getLegend( )
.setFormatSpecifier( FormatSpecifierImpl.copyInstance( sdBase.getFormatSpecifier( ) ) );
}
}
// Create a default emptymessage if there is no.
// Thus old report will behave just like before.
if ( cm.getEmptyMessage( ) == null )
{
Label la = LabelImpl.create( );
la.setVisible( false );
cm.setEmptyMessage( la );
}
}
/**
* Adjust number format specifier for old version number.
*
* @param reportVer
* the version number of report.
*/
private void adjustNumberFormat( String reportVer )
{
// If the version of report design file is less than 3.2.10, use old
// logic to make the multiplier to multiple 100 for % suffix.
if ( reportVer == null || compareVersion( reportVer, "3.2.9" ) > 0 ) //$NON-NLS-1$
{
// Version is larger than 3.2.9, directly return.
return;
}
// Version is older than 3.2.10, change Number format to use old logic
// format multiplier of 0.01.
if ( cm instanceof ChartWithAxes )
{
ChartWithAxes cwa = (ChartWithAxes) cm;
Axis[] baseAxis = cwa.getBaseAxes( );
if ( baseAxis.length <= 0 )
{
return;
}
adjustSingleNumberFormat( baseAxis[0].getFormatSpecifier( ) );
Axis[] yAxis = cwa.getOrthogonalAxes( baseAxis[0], true );
if ( yAxis.length <= 0 )
{
return;
}
for ( int i = 0; i < yAxis.length; i++ )
{
adjustSingleNumberFormat( yAxis[i].getFormatSpecifier( ) );
EList sds = yAxis[i].getSeriesDefinitions( );
for ( int j = 0; j < sds.size( ); j++ )
{
SeriesDefinition sd = (SeriesDefinition) sds.get( j );
adjustSingleNumberFormat( sd.getFormatSpecifier( ) );
EList dpcs = sd.getDesignTimeSeries( )
.getDataPoint( )
.getComponents( );
for ( int k = 0; k < dpcs.size( ); k++ )
{
adjustSingleNumberFormat( ( (DataPointComponent) dpcs.get( k ) ).getFormatSpecifier( ) );
}
}
}
}
else if ( cm instanceof ChartWithoutAxes )
{
ChartWithoutAxes cwa = (ChartWithoutAxes) cm;
EList categories = cwa.getSeriesDefinitions( );
if ( categories.size( ) > 0 )
{
EList sds = ( (SeriesDefinition) categories.get( 0 ) ).getSeriesDefinitions( );
for ( int j = 0; j < sds.size( ); j++ )
{
SeriesDefinition sd = (SeriesDefinition) sds.get( j );
adjustSingleNumberFormat( sd.getFormatSpecifier( ) );
EList dpcs = sd.getDesignTimeSeries( )
.getDataPoint( )
.getComponents( );
for ( int k = 0; k < dpcs.size( ); k++ )
{
adjustSingleNumberFormat( ( (DataPointComponent) dpcs.get( k ) ).getFormatSpecifier( ) );
}
}
}
}
}
private void adjustSingleNumberFormat( FormatSpecifier fs )
{
if ( !( fs instanceof NumberFormatSpecifier ) )
{
return;
}
NumberFormatSpecifier nfs = (NumberFormatSpecifier) fs;
String suffix = nfs.getSuffix( );
if ( "%".equals( suffix ) ) //$NON-NLS-1$
{
double multiplier = nfs.getMultiplier( );
if ( !Double.isNaN( multiplier ) && multiplier == 0.01 )
{
nfs.setMultiplier( 100 * multiplier );
}
}
}
/**
* Compare version number, the format of version number should be X.X.X
* style.
*
* @param va
* version number 1.
* @param vb
* version number 2.
* @return
*/
private static int compareVersion( String va, String vb )
{
return ChartUtil.compareVersion( va, vb );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.api.extension.IReportItem#getScriptPropertyDefinition()
*/
public IPropertyDefinition getScriptPropertyDefinition( )
{
if ( cm == null )
{
logger.log( ILogger.WARNING,
Messages.getString( "ChartReportItemImpl.log.RequestForScriptPropertyDefn" ) ); //$NON-NLS-1$
return null;
}
return new ChartPropertyDefinitionImpl( null,
"script", "property.script", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.STRING_TYPE,
null,
null,
null );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#getPropertyDefinitions()
*/
public IPropertyDefinition[] getPropertyDefinitions( )
{
if ( cm == null )
{
return null;
}
return new IPropertyDefinition[]{
new ChartPropertyDefinitionImpl( null,
"title.value", "property.label.title.value", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.STRING_TYPE,
null,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"title.font.rotation", "property.label.title.font.rotation", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.FLOAT_TYPE,
null,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"legend.position", "property.label.legend.position", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.CHOICE_TYPE,
liLegendPositions,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"legend.anchor", "property.label.legend.anchor", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.CHOICE_TYPE,
liLegendAnchors,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"chart.dimension", "property.label.chart.dimension", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.CHOICE_TYPE,
liChartDimensions,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"plot.transposed", "property.label.chart.plot.transposed", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.BOOLEAN_TYPE,
null,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"script", "property.script", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.STRING_TYPE,
null,
null,
null ),
new ChartPropertyDefinitionImpl( null,
"onRender", "property.onRender", false, //$NON-NLS-1$ //$NON-NLS-2$
IPropertyType.SCRIPT_TYPE,
null,
null,
null,
new ChartPropertyMethodInfo( "onRender", //$NON-NLS-1$
null,
null,
null,
null,
false,
false ) ),
};
}
public IMethodInfo[] getMethods( String scriptName )
{
if ( scriptName != null
&& scriptName.equals( ChartReportItemUtil.PROPERTY_ONRENDER ) )
{
ScriptClassInfo info = new ScriptClassInfo( IChartEventHandler.class );
List list = info.getMethods( );
Collections.sort( list, new Comparator( ) {
public int compare( Object arg0, Object arg1 )
{
if ( arg0 instanceof IMethodInfo
&& arg1 instanceof IMethodInfo )
{
String name0 = ( (IMethodInfo) arg0 ).getName( );
String name1 = ( (IMethodInfo) arg1 ).getName( );
if ( name0.startsWith( "before" ) && name1.startsWith( "after" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return -1;
}
if ( name0.startsWith( "after" ) && name1.startsWith( "before" ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return 1;
}
return ( name0.compareToIgnoreCase( name1 ) );
}
else
return -1;
}
} );
return (IMethodInfo[]) list.toArray( new IMethodInfo[list.size( )] );
}
else
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#getProperty(java.lang.String)
*/
public final Object getProperty( String propName )
{
if ( cm == null )
{
// Try to get host chart as model
initHostChart( );
if ( cm == null )
{
return null;
}
}
if ( propName.equals( "title.value" ) ) //$NON-NLS-1$
{
return cm.getTitle( ).getLabel( ).getCaption( ).getValue( );
}
else if ( propName.equals( "title.font.rotation" ) ) //$NON-NLS-1$
{
return new Double( cm.getTitle( )
.getLabel( )
.getCaption( )
.getFont( )
.getRotation( ) );
}
else if ( propName.equals( "legend.position" ) ) //$NON-NLS-1$
{
return cm.getLegend( ).getPosition( ).getName( );
}
else if ( propName.equals( "legend.anchor" ) ) //$NON-NLS-1$
{
return cm.getLegend( ).getAnchor( ).getName( );
}
else if ( propName.equals( "chart.dimension" ) ) //$NON-NLS-1$
{
return cm.getDimension( ).getName( );
}
else if ( propName.equals( "plot.transposed" ) ) //$NON-NLS-1$
{
return Boolean.valueOf( ( cm instanceof ChartWithAxes ) ? ( (ChartWithAxes) cm ).isTransposed( )
: false );
}
else if ( propName.equals( ChartReportItemUtil.PROPERTY_SCRIPT )
|| propName.equals( ChartReportItemUtil.PROPERTY_ONRENDER ) )
{
return cm.getScript( );
}
else if ( propName.equals( ChartReportItemUtil.PROPERTY_CHART ) )
{
return cm;
}
else if ( propName.equals( ChartReportItemUtil.PROPERTY_SCALE ) )
{
return sharedScale;
}
return null;
}
private void initHostChart( )
{
if ( ChartXTabUtil.isAxisChart( handle ) )
{
ExtendedItemHandle hostChartHandle = (ExtendedItemHandle) handle.getElementProperty( ChartReportItemUtil.PROPERTY_HOST_CHART );
if ( hostChartHandle == null || hostChartHandle == handle )
{
return;
}
// Use the reference if it references host chart
cm = ChartReportItemUtil.getChartFromHandle( hostChartHandle );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#checkProperty(java.lang.String,
* java.lang.Object)
*/
public void checkProperty( String propName, Object value )
throws ExtendedElementException
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemImpl.log.checkProperty", new Object[]{propName, value} ) ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#setProperty(java.lang.String,
* java.lang.Object)
*/
public void setProperty( String propName, Object value )
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemImpl.log.setProperty", new Object[]{propName, value} ) ); //$NON-NLS-1$
executeSetSimplePropertyCommand( handle,
propName,
getProperty( propName ),
value );
}
void basicSetProperty( String propName, Object value )
{
if ( propName.equals( "title.value" ) ) //$NON-NLS-1$
{
cm.getTitle( ).getLabel( ).getCaption( ).setValue( (String) value );
}
else if ( propName.equals( "title.font.rotation" ) ) //$NON-NLS-1$
{
cm.getTitle( )
.getLabel( )
.getCaption( )
.getFont( )
.setRotation( ( (Double) value ).doubleValue( ) );
}
else if ( propName.equals( "legend.position" ) ) //$NON-NLS-1$
{
cm.getLegend( ).setPosition( Position.get( (String) value ) );
}
else if ( propName.equals( "legend.anchor" ) ) //$NON-NLS-1$
{
cm.getLegend( ).setAnchor( Anchor.get( (String) value ) );
}
else if ( propName.equals( "chart.dimension" ) ) //$NON-NLS-1$
{
cm.setDimension( ChartDimension.get( (String) value ) );
}
else if ( propName.equals( "plot.transposed" ) ) //$NON-NLS-1$
{
if ( cm instanceof ChartWithAxes )
{
( (ChartWithAxes) cm ).setTransposed( ( (Boolean) value ).booleanValue( ) );
}
else
{
logger.log( ILogger.ERROR,
Messages.getString( "ChartReportItemImpl.log.CannotSetState" ) ); //$NON-NLS-1$
}
}
else if ( propName.equals( ChartReportItemUtil.PROPERTY_SCRIPT )
|| propName.equals( ChartReportItemUtil.PROPERTY_ONRENDER ) )
{
cm.setScript( (String) value );
}
else if ( propName.equals( ChartReportItemUtil.PROPERTY_CHART ) )
{
this.cm = (Chart) value;
}
}
protected void checkScriptSyntax( String string ) throws RhinoException
{
if ( string == null )
return;
if ( !isJavaClassName( string ) )
{
try
{
Context cx = Context.enter( );
cx.compileString( string, "chartScript", 1, null ); //$NON-NLS-1$
}
finally
{
Context.exit( );
}
}
}
protected boolean isJavaClassName( String string )
{
return ( string.matches( "\\w+(\\.\\w*)*" ) ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#validate()
*/
public List validate( )
{
logger.log( ILogger.INFORMATION,
Messages.getString( "ChartReportItemImpl.log.validate" ) ); //$NON-NLS-1$
List list = new ArrayList( );
if ( cm != null )
{
try
{
checkScriptSyntax( cm.getScript( ) );
}
catch ( RhinoException e )
{
logger.log( e );
ExtendedElementException extendedException = new ExtendedElementException( this.getHandle( )
.getElement( ),
ChartReportItemPlugin.ID,
"exception.script.syntaxError",//$NON-NLS-1$
new Object[]{
e.getLocalizedMessage( )
},
Messages.getResourceBundle( ) );
extendedException.setProperty( ExtendedElementException.LINE_NUMBER,
String.valueOf( e.lineNumber( ) ) );
extendedException.setProperty( ExtendedElementException.SUB_EDITOR,
"script" );//$NON-NLS-1$
list.add( extendedException );
}
}
return list;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#copy()
*/
public final IReportItem copy( )
{
final ChartReportItemImpl crii = new ChartReportItemImpl( handle );
crii.bCopied = true;
// Do not copy model for axis chart since it uses reference
if ( !ChartXTabUtil.isAxisChart( handle ) )
{
crii.cm = cm == null ? null : ChartImpl.copyInstance( cm );
}
return crii;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.extension.IElement#refreshPropertyDefinition()
*/
public boolean refreshPropertyDefinition( )
{
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.api.extension.ICompatibleReportItem#getRowExpressions()
*/
public List getRowExpressions( )
{
try
{
boolean needChangeValueExpr = true;
if ( handle.getDataBindingReference( ) != null
|| handle.getContainer( ) instanceof MultiViewsHandle )
{
needChangeValueExpr = false;
}
return Generator.instance( ).getRowExpressions( cm,
new BIRTActionEvaluator( ),
needChangeValueExpr );
}
catch ( ChartException e )
{
logger.log( e );
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.model.api.extension.ICompatibleReportItem#updateRowExpressions(java.util.Map)
*/
public void updateRowExpressions( Map newExpressions )
{
CompatibleExpressionUpdater.update( cm, newExpressions );
}
public org.eclipse.birt.report.model.api.simpleapi.IReportItem getSimpleElement( )
{
try
{
if ( cm instanceof ChartWithAxes )
{
return new ChartWithAxesImpl( handle, (ChartWithAxes) cm );
}
if ( cm instanceof ChartWithoutAxes )
{
return new ChartWithoutAxesImpl( handle, (ChartWithoutAxes) cm );
}
return null;
}
catch ( Exception e )
{
logger.log( e );
return null;
}
}
/**
* Returns if current report item is just copied
*
* @since 2.3
*/
public boolean isCopied( )
{
return this.bCopied;
}
public URL findResource( String fileName )
{
if ( handle != null )
{
return handle.getModule( ).findResource( fileName, 0 );
}
return null;
}
public String externalizedMessage( String sKey, String sDefaultValue,
ULocale locale )
{
return ModuleUtil.getExternalizedValue( handle,
sKey,
sDefaultValue,
locale );
}
@Override
public boolean canExport( )
{
// If chart is from multi-view or xtab part, do not allow to
// export to library.
if ( handle.getContainer( ) instanceof MultiViewsHandle
|| ChartXTabUtil.isPlotChart( handle )
|| ChartXTabUtil.isAxisChart( handle ) )
{
return false;
}
return true;
}
/**
* Since model does not differentiate Layout-RTL and Text-RTL, but chart
* does. Currently we always retrieve the Layout-RTL from container.
*
* @return
*/
public boolean isLayoutDirectionRTL( )
{
if ( handle.getContainer( ) == null )
{
return false;
}
return handle.getContainer( ).isDirectionRTL( );
}
}
|
package org.eclipse.birt.chart.reportitem;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.attribute.DataType;
import org.eclipse.birt.chart.model.attribute.GroupingUnitType;
import org.eclipse.birt.chart.model.attribute.SortOption;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.IGroupDefinition;
import org.eclipse.birt.report.engine.extension.IBaseResultSet;
import org.eclipse.birt.report.engine.extension.IQueryResultSet;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
/**
* Utility class for Chart integration as report item
*/
public class ChartReportItemUtil
{
/**
* Specified the query expression of min aggregation binding
*/
public static final String QUERY_MIN = "chart__min"; //$NON-NLS-1$
/**
* Specified the query expression of max aggregation binding
*/
public static final String QUERY_MAX = "chart__max"; //$NON-NLS-1$
/**
* Specified property names defined in ExtendedItemHandle or IReportItem
*/
public static final String PROPERTY_XMLPRESENTATION = "xmlRepresentation"; //$NON-NLS-1$
public static final String PROPERTY_CHART = "chart.instance"; //$NON-NLS-1$
public static final String PROPERTY_SCALE = "chart.scale"; //$NON-NLS-1$
public static final String PROPERTY_SCRIPT = "script"; //$NON-NLS-1$
public static final String PROPERTY_ONRENDER = "onRender"; //$NON-NLS-1$
public static final String PROPERTY_OUTPUT = "outputFormat"; //$NON-NLS-1$
/**
* Checks current chart is within cross tab.
*
* @param chartHandle
* the handle holding chart
* @return true means within cross tab, false means not
*/
public static boolean isChartInXTab( DesignElementHandle chartHandle )
{
DesignElementHandle container = chartHandle.getContainer( );
if ( container instanceof ExtendedItemHandle )
{
String exName = ( (ExtendedItemHandle) container ).getExtensionName( );
if ( ICrosstabConstants.CROSSTAB_CELL_EXTENSION_NAME.equals( exName ) )
{
return true;
}
}
return false;
}
/**
* Returns the element handle which can save binding columns the given
* element
*
* @param handle
* the handle of the element which needs binding columns
* @return the holder for the element,or itself if no holder available
*/
public static ReportItemHandle getBindingHolder( DesignElementHandle handle )
{
if ( handle instanceof ReportElementHandle )
{
if ( handle instanceof ListingHandle )
{
return (ReportItemHandle) handle;
}
if ( handle instanceof ReportItemHandle )
{
if ( ( (ReportItemHandle) handle ).getDataBindingReference( ) != null
|| ( (ReportItemHandle) handle ).getCube( ) != null
|| ( (ReportItemHandle) handle ).getDataSet( ) != null
|| ( (ReportItemHandle) handle ).columnBindingsIterator( )
.hasNext( ) )
{
return (ReportItemHandle) handle;
}
}
ReportItemHandle result = getBindingHolder( handle.getContainer( ) );
if ( result == null
&& handle instanceof ReportItemHandle
&& !( handle instanceof GridHandle ) )
{
result = (ReportItemHandle) handle;
}
return result;
}
return null;
}
/**
* Checks if shared scale is needed when computation
*
* @param eih
* handle
* @param cm
* chart model
* @return shared binding needed or not
*/
public static boolean canScaleShared( ExtendedItemHandle eih, Chart cm )
{
// TODO enable shared scale later
return false;
// return cm instanceof ChartWithAxes
// && eih.getDataSet( ) == null && getBindingHolder( eih ) != null;
}
/**
* @return Returns if current eclipse environment is RtL.
*/
public static boolean isRtl( )
{
// get -dir rtl option
boolean rtl = false;
String eclipseCommands = System.getProperty( "eclipse.commands" ); //$NON-NLS-1$
if ( eclipseCommands != null )
{
String[] options = eclipseCommands.split( "-" ); //$NON-NLS-1$
String regex = "[\\s]*[dD][iI][rR][\\s]*[rR][tT][lL][\\s]*"; //$NON-NLS-1$
Pattern pattern = Pattern.compile( regex );
for ( int i = 0; i < options.length; i++ )
{
String option = options[i];
if ( pattern.matcher( option ).matches( ) )
{
rtl = true;
break;
}
}
}
return rtl;
}
/**
* Gets all column bindings from handle and its container
*
* @param itemHandle
* handle
* @return Iterator of all bindings
*/
public static Iterator getColumnDataBindings( ReportItemHandle itemHandle )
{
if ( itemHandle.getDataSet( ) != null )
{
return itemHandle.columnBindingsIterator( );
}
DesignElementHandle handle = getBindingHolder( itemHandle );
if ( handle instanceof ReportItemHandle )
{
ArrayList list = new ArrayList( );
Iterator i = ( (ReportItemHandle) handle ).columnBindingsIterator( );
while ( i.hasNext( ) )
{
list.add( i.next( ) );
}
i = itemHandle.columnBindingsIterator( );
while ( i.hasNext( ) )
{
list.add( i.next( ) );
}
return list.iterator( );
}
return null;
}
/**
* Convert group unit type from Chart's to DtE's.
*
* @param dataType
* @param groupUnitType
* @return
*/
public static int convertToDtEGroupUnit( DataType dataType,
GroupingUnitType groupUnitType )
{
if ( dataType == DataType.NUMERIC_LITERAL )
{
return IGroupDefinition.NUMERIC_INTERVAL;
}
else if ( dataType == DataType.DATE_TIME_LITERAL )
{
switch ( groupUnitType.getValue( ) )
{
case GroupingUnitType.SECONDS :
return IGroupDefinition.SECOND_INTERVAL;
case GroupingUnitType.MINUTES :
return IGroupDefinition.MINUTE_INTERVAL;
case GroupingUnitType.HOURS :
return IGroupDefinition.HOUR_INTERVAL;
case GroupingUnitType.DAYS :
return IGroupDefinition.DAY_INTERVAL;
case GroupingUnitType.MONTHS :
return IGroupDefinition.MONTH_INTERVAL;
case GroupingUnitType.QUARTERS :
return IGroupDefinition.QUARTER_INTERVAL;
case GroupingUnitType.YEARS :
return IGroupDefinition.YEAR_INTERVAL;
}
}
return IGroupDefinition.NO_INTERVAL;
}
/**
* Convert interval range from Chart's to DtE's.
*
* @param intervalRange
* @return
*/
public static double convertToDtEIntervalRange( DataType dataType, double intervalRange )
{
double range = intervalRange;
if ( Double.isNaN( intervalRange ) )
{
range = 0;
}
if ( dataType == DataType.DATE_TIME_LITERAL && range <= 0) {
range = 1;
}
return range;
}
/**
* Convert sort direction from Chart's to DtE's.
*
* @param sortOption
* @return
*/
public static int convertToDtESortDirection( SortOption sortOption )
{
if ( sortOption == SortOption.ASCENDING_LITERAL )
{
return IGroupDefinition.SORT_ASC;
}
else if ( sortOption == SortOption.DESCENDING_LITERAL )
{
return IGroupDefinition.SORT_DESC;
}
return IGroupDefinition.NO_SORT;
}
/**
* Convert aggregation name from Chart's to DtE's.
*
* @param agg
* @return
*/
public static String convertToDtEAggFunction( String agg ) {
if ( "Sum".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_SUM;
} else if ( "Average".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_AVERAGE;
} else if ( "Count".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_COUNT;
} else if ( "DistinctCount".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_COUNTDISTINCT;
} else if ( "First".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_FIRST;
} else if ( "Last".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_LAST;
} else if ( "Min".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_MIN;
} else if ( "Max".equals( agg )) { //$NON-NLS-1$
return DesignChoiceConstants.AGGREGATION_FUNCTION_MAX;
}
return null;
}
/**
* Checks if result set is empty
*
* @param set
* result set
* @throws BirtException
* @since 2.3
*/
public static boolean isEmpty( IBaseResultSet set ) throws BirtException
{
if ( set instanceof IQueryResultSet )
{
return ( (IQueryResultSet) set ).isEmpty( );
}
// TODO add code to check empty for ICubeResultSet
return false;
}
/**
* Check if Y grouping is defined.
*
* @param orthSeriesDefinition
* @return
*/
public static boolean yGroupingDefined(SeriesDefinition orthSeriesDefinition) {
if ( orthSeriesDefinition == null )
{
return false;
}
String yGroupExpr = null;
if ( orthSeriesDefinition.getQuery( ) != null )
{
yGroupExpr = orthSeriesDefinition.getQuery( ).getDefinition( );
}
return yGroupExpr != null && !"".equals( yGroupExpr ); //$NON-NLS-1$
}
/**
* Check if base series grouping is defined.
*
* @param baseSD
* @return
*/
public static boolean baseGroupingDefined(SeriesDefinition baseSD) {
if ( baseSD.getGrouping( ) != null && baseSD.getGrouping( ).isEnabled( ) )
{
return true;
}
return false;
}
/**
* Check if current chart has defined grouping.
*
* @param cm
* @return
*/
public static boolean containsGrouping( Chart cm )
{
SeriesDefinition baseSD = null;
SeriesDefinition orthSD = null;
Object[] orthAxisArray = null;
if ( cm instanceof ChartWithAxes )
{
ChartWithAxes cwa = (ChartWithAxes) cm;
baseSD = (SeriesDefinition) cwa.getBaseAxes( )[0].getSeriesDefinitions( )
.get( 0 );
orthAxisArray = cwa.getOrthogonalAxes( cwa.getBaseAxes( )[0], true );
orthSD = (SeriesDefinition) ( (Axis) orthAxisArray[0] ).getSeriesDefinitions( )
.get( 0 );
}
else if ( cm instanceof ChartWithoutAxes )
{
ChartWithoutAxes cwoa = (ChartWithoutAxes) cm;
baseSD = (SeriesDefinition) cwoa.getSeriesDefinitions( ).get( 0 );
orthSD = (SeriesDefinition) baseSD.getSeriesDefinitions( ).get( 0 );
}
if ( baseGroupingDefined( baseSD ) || yGroupingDefined( orthSD ) )
{
return true;
}
return false;
}
}
|
package org.eclipse.birt.chart.ui.swt.wizard;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Vector;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.attribute.AxisType;
import org.eclipse.birt.chart.model.attribute.ChartDimension;
import org.eclipse.birt.chart.model.attribute.DataType;
import org.eclipse.birt.chart.model.attribute.Orientation;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.component.MarkerLine;
import org.eclipse.birt.chart.model.component.MarkerRange;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.BaseSampleData;
import org.eclipse.birt.chart.model.data.OrthogonalSampleData;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.type.AreaSeries;
import org.eclipse.birt.chart.model.type.BarSeries;
import org.eclipse.birt.chart.model.util.ChartDefaultValueUtil;
import org.eclipse.birt.chart.model.util.ChartValueUpdater;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ChartCheckbox;
import org.eclipse.birt.chart.ui.swt.ChartCombo;
import org.eclipse.birt.chart.ui.swt.ChartPreviewPainter;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartPreviewPainter;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartSubType;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartType;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ISeriesUIProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskChangeListener;
import org.eclipse.birt.chart.ui.swt.interfaces.ITaskPreviewable;
import org.eclipse.birt.chart.ui.swt.wizard.preview.ChartLivePreviewThread;
import org.eclipse.birt.chart.ui.swt.wizard.preview.LivePreviewTask;
import org.eclipse.birt.chart.ui.util.ChartCacheManager;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIExtensionUtil;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.ui.util.UIHelper;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.birt.core.ui.frameworks.taskwizard.interfaces.IWizardContext;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EContentAdapter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
/**
* TaskSelectType
*/
public class TaskSelectType extends SimpleTask implements
SelectionListener,
ITaskChangeListener,
ITaskPreviewable
{
private static final ChartValueUpdater chartValueUpdater = new ChartValueUpdater( );
/**
*
* TaskSelectTypeUIDescriptor is used to create UI in misc area according to
* the order of index
*/
public abstract class TaskSelectTypeUIDescriptor
{
private boolean bVisible = true;
public boolean isVisible( )
{
return bVisible;
}
public void setVisible( boolean bVisible )
{
this.bVisible = bVisible;
}
public abstract int getIndex( );
public abstract void createControl( Composite parent );
}
protected Chart chartModel = null;
protected ChartAdapter adapter = null;
protected Composite cmpType = null;
protected Composite cmpMisc = null;
private Composite cmpRight = null;
protected Composite cmpLeft = null;
private Composite cmpTypeButtons = null;
private Composite cmpSubTypes = null;
protected IChartPreviewPainter previewPainter = null;
private Canvas previewCanvas = null;
protected String sSubType = null;
protected String sType = null;
protected String sOldType = null;
// Stored in IChartType
protected String sDimension = null;
protected Table table = null;
private Vector<String> vSubTypeNames = null;
protected Orientation orientation = null;
protected Label lblOrientation = null;
protected ChartCheckbox btnOrientation = null;
protected Label lblMultipleY = null;
protected Combo cbMultipleY = null;
protected Label lblSeriesType = null;
protected Combo cbSeriesType = null;
protected Label lblDimension;
protected ChartCombo cbDimension = null;
protected Label lblOutput;
protected Combo cbOutput;
protected SashForm foSashForm;
protected int pageMargin = 80;
protected static final String LEADING_BLANKS = " "; //$NON-NLS-1$
protected static Hashtable<String, Series> htSeriesNames = null;
protected static String[] outputFormats, outputDisplayNames;
static
{
try
{
outputFormats = ChartUtil.getSupportedOutputFormats( );
outputDisplayNames = ChartUtil.getSupportedOutputDisplayNames( );
}
catch ( ChartException e )
{
WizardBase.displayException( e );
outputFormats = new String[0];
outputDisplayNames = new String[0];
}
}
protected List<TaskSelectTypeUIDescriptor> lstDescriptor = new LinkedList<TaskSelectTypeUIDescriptor>( );
public TaskSelectType( )
{
super( Messages.getString( "TaskSelectType.TaskExp" ) ); //$NON-NLS-1$
setDescription( Messages.getString( "TaskSelectType.Task.Description" ) ); //$NON-NLS-1$
if ( chartModel != null )
{
sType = chartModel.getType( );
sOldType = sType;
sSubType = chartModel.getSubType( );
if ( chartModel.isSetDimension( ) )
{
sDimension = translateDimensionString( chartModel.getDimension( )
.getName( ) );
ChartCacheManager.getInstance( ).cacheDimension( sType,
sDimension );
}
if ( chartModel instanceof ChartWithAxes )
{
orientation = ( (ChartWithAxes) chartModel ).isSetOrientation( ) ? ( (ChartWithAxes) chartModel ).getOrientation( )
: null;
ChartCacheManager.getInstance( ).cacheOrientation( sType,
orientation );
}
}
}
public void createControl( Composite parent )
{
if ( topControl == null || topControl.isDisposed( ) )
{
if ( context != null )
{
chartModel = ( (ChartWizardContext) context ).getModel( );
}
topControl = new Composite( parent, SWT.NONE );
GridLayout gridLayout = new GridLayout( 2, false );
gridLayout.marginWidth = pageMargin;
topControl.setLayout( gridLayout );
topControl.setLayoutData( new GridData( GridData.GRAB_HORIZONTAL
| GridData.GRAB_VERTICAL ) );
placeComponents( );
updateAdapters( );
updateComponentsState( false );
}
else
{
updateComponentsState( true );
}
// Update dimension combo and related sub-types in case of axes changed
// outside
updateDimensionCombo( sType );
if ( getContext( ).isMoreAxesSupported( ) )
{
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
cmpMisc.layout( );
}
updateSelection( );
doPreview( );
bindHelp( );
}
protected void updateComponentsState( boolean isUpdateUI )
{
// Do nothing.
}
protected void bindHelp( )
{
ChartUIUtil.bindHelp( getControl( ),
ChartHelpContextIds.TASK_SELECT_TYPE );
}
protected void placeComponents( )
{
foSashForm = new SashForm( topControl, SWT.VERTICAL );
{
GridLayout layout = new GridLayout( );
foSashForm.setLayout( layout );
GridData gridData = new GridData( GridData.FILL_BOTH );
// TODO verify Bug 194391 in Linux
gridData.heightHint = 570;
foSashForm.setLayoutData( gridData );
}
createTopPreviewArea( foSashForm );
createBottomTypeArea( foSashForm );
initUIPropertiesAndData( );
}
protected void initUIPropertiesAndData( )
{
setDefaultTypeSelection( );
if ( chartModel == null )
{
// Do not reset model when it exists.
createChartModel( );
}
populateSeriesTypesList( );
if ( btnOrientation != null )
{
Orientation defOrientation = ChartDefaultValueUtil.getDefaultOrientation( getContext( ).getModel( ) );
btnOrientation.setDefaultSelection( defOrientation == null ? false
: defOrientation == Orientation.VERTICAL_LITERAL );
}
}
protected void createChartModel( )
{
refreshChart( sType, sSubType );
}
protected void createTopPreviewArea( Composite parent )
{
Composite cmpPreview = new Composite( parent, SWT.NONE );
cmpPreview.setLayout( new GridLayout( ) );
GridData gridData = new GridData( GridData.FILL_BOTH );
gridData.horizontalSpan = 2;
gridData.heightHint = 270;
cmpPreview.setLayoutData( gridData );
Label label = new Label( cmpPreview, SWT.NONE );
{
label.setText( getChartPreviewTitle( ) );
}
previewCanvas = new Canvas( cmpPreview, SWT.BORDER );
previewCanvas.setLayoutData( new GridData( GridData.FILL_BOTH ) );
previewCanvas.setBackground( Display.getDefault( )
.getSystemColor( SWT.COLOR_WIDGET_BACKGROUND ) );
previewPainter = createPreviewPainter( );
}
protected String getChartPreviewTitle( )
{
return Messages.getString( "TaskSelectType.Label.Preview" ); //$NON-NLS-1$
}
protected void createBottomTypeArea( Composite parent )
{
ScrolledComposite sc = new ScrolledComposite( parent, SWT.V_SCROLL
| SWT.H_SCROLL );
{
GridLayout layout = new GridLayout( );
sc.setLayout( layout );
GridData gridData = new GridData( GridData.FILL_BOTH );
sc.setLayoutData( gridData );
sc.setExpandHorizontal( true );
sc.setExpandVertical( true );
}
cmpType = new Composite( sc, SWT.NONE );
cmpType.setLayout( new GridLayout( 2, false ) );
cmpType.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
sc.setContent( cmpType );
createLeftTypeTable( cmpType );
populateChartTypes( );
createRightDetails( cmpType );
Point size = cmpType.computeSize( SWT.DEFAULT, SWT.DEFAULT );
sc.setMinSize( size );
}
private void createRightDetails( Composite parent )
{
cmpRight = new Composite( parent, SWT.NONE );
cmpRight.setLayout( new GridLayout( ) );
cmpRight.setLayoutData( new GridData( GridData.FILL_BOTH ) );
createComposite( new Vector<IChartSubType>( ) );
createMiscArea( cmpRight );
}
private void createMiscArea( Composite parent )
{
cmpMisc = new Composite( parent, SWT.NONE );
cmpMisc.setLayout( new GridLayout( 4, false ) );
cmpMisc.setLayoutData( new GridData( GridData.FILL_BOTH ) );
addDimensionUI( );
addMultipleAxesUI( );
addSeriesTypeUI( );
addOrientationUI( );
addOptionalUIDescriptor( );
createUIDescriptors( cmpMisc );
}
protected void addSeriesTypeUI( )
{
addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) {
public int getIndex( )
{
return 40;
}
public void createControl( Composite parent )
{
lblSeriesType = new Label( parent, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalIndent = 10;
lblSeriesType.setLayoutData( gd );
lblSeriesType.setText( Messages.getString( "TaskSelectType.Label.SeriesType" ) ); //$NON-NLS-1$
lblSeriesType.setEnabled( false );
}
// Add the ComboBox for Series Type
cbSeriesType = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cbSeriesType.setLayoutData( gd );
cbSeriesType.setEnabled( false );
cbSeriesType.addSelectionListener( TaskSelectType.this );
}
}
} );
}
protected void addMultipleAxesUI( )
{
addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) {
public int getIndex( )
{
return 30;
}
public void createControl( Composite parent )
{
lblMultipleY = new Label( parent, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
lblMultipleY.setLayoutData( gd );
lblMultipleY.setText( Messages.getString( "TaskSelectType.Label.MultipleYAxis" ) ); //$NON-NLS-1$
}
// Add the checkBox for Multiple Y Axis
cbMultipleY = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY );
{
cbMultipleY.setItems( getMultipleYComboItems( ) );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cbMultipleY.setLayoutData( gd );
cbMultipleY.addSelectionListener( TaskSelectType.this );
int axisNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel );
selectMultipleAxis( axisNum );
}
}
} );
}
protected String[] getMultipleYComboItems( )
{
return new String[]{
Messages.getString( "TaskSelectType.Selection.None" ), //$NON-NLS-1$
Messages.getString( "TaskSelectType.Selection.SecondaryAxis" ), //$NON-NLS-1$
Messages.getString( "TaskSelectType.Selection.MoreAxes" ) //$NON-NLS-1$
};
}
protected void addDimensionUI( )
{
addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) {
public int getIndex( )
{
return 10;
}
public void createControl( Composite parent )
{
lblDimension = new Label( parent, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
lblDimension.setLayoutData( gd );
lblDimension.setText( Messages.getString( "TaskSelectType.Label.Dimension" ) ); //$NON-NLS-1$
}
// Add the ComboBox for Dimensions
cbDimension = getContext( ).getUIFactory( )
.createChartCombo( parent,
SWT.DROP_DOWN | SWT.READ_ONLY,
getContext( ).getModel( ),
"dimension", //$NON-NLS-1$
null );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cbDimension.setLayoutData( gd );
cbDimension.addSelectionListener( TaskSelectType.this );
}
}
} );
}
protected void addOrientationUI( )
{
addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) {
public int getIndex( )
{
return 50;
}
public void createControl( Composite parent )
{
lblOrientation = new Label( parent, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
lblOrientation.setLayoutData( gd );
lblOrientation.setText( Messages.getString( "TaskSelectType.Label.Oritention" ) ); //$NON-NLS-1$
}
// Add the CheckBox for Orientation
btnOrientation = getContext( ).getUIFactory( )
.createChartCheckbox( parent,
SWT.NONE, false );
{
btnOrientation.setText( Messages.getString( "TaskSelectType.Label.FlipAxis" ) ); //$NON-NLS-1$
GridData gd = new GridData( );
btnOrientation.setLayoutData( gd );
btnOrientation.addSelectionListener( TaskSelectType.this );
}
updateOrientationUIState( );
}
} );
}
protected void updateOrientationUIState( )
{
if ( btnOrientation == null )
{
return;
}
if ( orientation == null )
{
btnOrientation.setSelectionState( ChartCheckbox.STATE_GRAYED );
}
else if ( orientation == Orientation.HORIZONTAL_LITERAL )
{
btnOrientation.setSelectionState( ChartCheckbox.STATE_SELECTED );
}
else
{
btnOrientation.setSelectionState( ChartCheckbox.STATE_UNSELECTED );
}
}
/**
* This method initializes table
*
*/
protected void createLeftTypeTable( Composite parent )
{
cmpLeft = new Composite( parent, SWT.NONE );
cmpLeft.setLayout( new GridLayout( ) );
cmpLeft.setLayoutData( new GridData( GridData.FILL_BOTH ) );
Label lblTypes = new Label( cmpLeft, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
lblTypes.setLayoutData( gd );
lblTypes.setText( Messages.getString( "TaskSelectType.Label.SelectChartType" ) ); //$NON-NLS-1$
}
table = new Table( cmpLeft, SWT.BORDER );
{
GridData gd = new GridData( GridData.FILL_BOTH );
table.setLayoutData( gd );
table.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartTypes" ) ); //$NON-NLS-1$
table.addSelectionListener( this );
}
}
protected void populateChartTypes( )
{
ChartUIUtil.populateTypeTable( getContext( ) );
Iterator<String> iter = ChartUIUtil.getChartTypeNameIterator( );
while ( iter.hasNext( ) )
{
String sTypeTmp = iter.next( );
TableItem tItem = new TableItem( table, SWT.NONE );
tItem.setText( LEADING_BLANKS
+ ( ChartUIUtil.getChartType( sTypeTmp ) ).getDisplayName( ) );
tItem.setData( ( ChartUIUtil.getChartType( sTypeTmp ) ).getName( ) );
tItem.setImage( ( ChartUIUtil.getChartType( sTypeTmp ) ).getImage( ) );
}
}
protected Chart getChartModel( )
{
return chartModel;
}
/**
* This method initializes cmpSubTypes
*
*/
protected void createComposite( Vector<IChartSubType> vSubTypes )
{
Label lblSubtypes = new Label( cmpRight, SWT.NO_FOCUS );
{
lblSubtypes.setText( Messages.getString( "TaskSelectType.Label.SelectSubtype" ) ); //$NON-NLS-1$
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalIndent = 5;
lblSubtypes.setLayoutData( gd );
}
GridData gdTypes = new GridData( GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_FILL );
cmpSubTypes = new Composite( cmpRight, SWT.NONE );
createSubtypeBtnGroups( vSubTypes );
cmpSubTypes.setLayoutData( gdTypes );
cmpSubTypes.setToolTipText( Messages.getString( "TaskSelectType.Label.ChartSubtypes" ) ); //$NON-NLS-1$
cmpSubTypes.setLayout( new GridLayout( ) );
cmpSubTypes.setVisible( true );
}
/**
* This method initializes cmpTypeButtons
*
*/
protected void createSubtypeBtnGroups( Vector<IChartSubType> vSubTypes )
{
vSubTypeNames = new Vector<String>( );
if ( cmpTypeButtons != null && !cmpTypeButtons.isDisposed( ) )
{
// Remove existing buttons
cmpTypeButtons.dispose( );
}
cmpTypeButtons = new Composite( cmpSubTypes, SWT.NONE );
cmpTypeButtons.setLayoutData( new GridData( GridData.FILL_BOTH ) );
GridLayout rowLayout = new GridLayout( vSubTypes.size( ), false );
rowLayout.marginTop = 0;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 12;
rowLayout.marginRight = 12;
rowLayout.horizontalSpacing = 4;
cmpTypeButtons.setLayout( rowLayout );
// Add new buttons for this type
for ( int iC = 0; iC < vSubTypes.size( ); iC++ )
{
IChartSubType subType = vSubTypes.get( iC );
vSubTypeNames.add( subType.getName( ) );
Button btnType = new Button( cmpTypeButtons, SWT.TOGGLE | SWT.FLAT );
btnType.setData( subType.getName( ) );
btnType.setImage( subType.getImage( ) );
GridData gd = new GridData( );
gd.widthHint = 80;
gd.heightHint = 80;
btnType.setLayoutData( gd );
btnType.addSelectionListener( this );
btnType.setToolTipText( subType.getDescription( ) );
btnType.getImage( ).setBackground( btnType.getBackground( ) );
btnType.setVisible( true );
cmpTypeButtons.layout( true );
if ( getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ) )
{
// Only support the first sub-type in xtab part case.
break;
}
}
cmpSubTypes.layout( true );
}
/*
* This method translates the dimension string from the model to that
* maintained by the UI (for readability).
*/
private String translateDimensionString( String sDimensionValue )
{
String dimensionName = ""; //$NON-NLS-1$
if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_LITERAL.getName( ) ) )
{
dimensionName = IChartType.TWO_DIMENSION_TYPE;
}
else if ( sDimensionValue.equals( ChartDimension.TWO_DIMENSIONAL_WITH_DEPTH_LITERAL.getName( ) ) )
{
dimensionName = IChartType.TWO_DIMENSION_WITH_DEPTH_TYPE;
}
else if ( sDimensionValue.equals( ChartDimension.THREE_DIMENSIONAL_LITERAL.getName( ) ) )
{
dimensionName = IChartType.THREE_DIMENSION_TYPE;
}
return dimensionName;
}
public void widgetDefaultSelected( SelectionEvent e )
{
}
public void widgetSelected( SelectionEvent e )
{
// Indicates whether need to update chart model
boolean needUpdateModel = false;
Object oSelected = e.getSource( );
needUpdateModel = handleWidgetSelected( e );
// Following operations need new model
if ( needUpdateModel )
{
// Update apply button
refreshChartAndPreview( oSelected );
}
}
protected boolean handleWidgetSelected( SelectionEvent e )
{
boolean needUpdateModel = false;
Object oSelected = e.getSource( );
if ( e.widget == btnOrientation )
{
needUpdateModel = true;
handleOrientationBtnSelected( );
}
else if ( oSelected.getClass( ).equals( Button.class ) )
{
needUpdateModel = true;
handleSubtypeBtnSelected( e );
}
else if ( oSelected.getClass( ).equals( Table.class ) )
{
needUpdateModel = handleTableItemSelected( e );
}
else if ( oSelected.equals( cbMultipleY ) )
{
needUpdateModel = handleMultipleAxesComboSelected( );
}
else if ( oSelected.equals( cbDimension ) )
{
needUpdateModel = handleDimensionComboSelected( );
}
else if ( oSelected.equals( cbSeriesType ) )
{
needUpdateModel = handleSeriesTypeComboSelected( );
}
return needUpdateModel;
}
protected boolean handleSeriesTypeComboSelected( )
{
boolean needUpdateModel;
// if ( !cbSeriesType.getText( ).equals( oldSeriesName ) )
needUpdateModel = true;
changeOverlaySeriesType( );
updateDimensionCombo( sType );
return needUpdateModel;
}
protected boolean handleDimensionComboSelected( )
{
String newDimension = null;
newDimension = cbDimension.getSelectedItemData( );
if ( newDimension == null && sDimension == null )
{
return false;
}
if ( ( newDimension != null && !newDimension.equals( sDimension ) )
|| ( sDimension != null && !sDimension.equals( newDimension ) ) )
{
handleDimensionBtnSelected( newDimension );
return true;
}
return false;
}
protected boolean handleMultipleAxesComboSelected( )
{
boolean needUpdateModel;
needUpdateModel = true;
lblSeriesType.setEnabled( isTwoAxesEnabled( ) );
Axis xAxis = ( (ChartWithAxes) chartModel ).getAxes( ).get( 0 );
getContext( ).setMoreAxesSupported( cbMultipleY.getSelectionIndex( ) == 2 );
if ( chartModel instanceof ChartWithoutAxes )
{
throw new IllegalArgumentException( Messages.getString( "TaskSelectType.Exception.CannotSupportAxes" ) ); //$NON-NLS-1$
}
// Prevent notifications rendering preview
ChartAdapter.beginIgnoreNotifications( );
int iAxisNumber = ChartUIUtil.getOrthogonalAxisNumber( chartModel );
if ( cbMultipleY.getSelectionIndex( ) == 0 )
{
// Remove series type cache
ChartCacheManager.getInstance( ).cacheSeriesType( null );
// Keeps one axis
if ( iAxisNumber > 1 )
{
ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel,
iAxisNumber - 1 );
}
}
else if ( cbMultipleY.getSelectionIndex( ) == 1 )
{
// Keeps two axes
if ( iAxisNumber == 1 )
{
ChartUIUtil.addAxis( (ChartWithAxes) chartModel );
}
else if ( iAxisNumber > 2 )
{
ChartUIUtil.removeLastAxes( (ChartWithAxes) chartModel,
iAxisNumber - 2 );
}
}
ChartAdapter.endIgnoreNotifications( );
if ( xAxis.getAssociatedAxes( ).size( ) > 1 )
{
String lastSeriesType = ChartCacheManager.getInstance( )
.findSeriesType( );
if ( lastSeriesType != null )
{
cbSeriesType.setText( lastSeriesType );
}
else
{
Axis overlayAxis = xAxis.getAssociatedAxes( ).get( 1 );
String sDisplayName = overlayAxis.getSeriesDefinitions( )
.get( 0 )
.getDesignTimeSeries( )
.getDisplayName( );
cbSeriesType.setText( sDisplayName );
}
changeOverlaySeriesType( );
}
cbSeriesType.setEnabled( isTwoAxesEnabled( ) );
// Update dimension combo and related sub-types
if ( updateDimensionCombo( sType ) )
{
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
}
// Pack to display enough space for combo
cmpMisc.layout( );
return needUpdateModel;
}
protected boolean handleTableItemSelected( SelectionEvent e )
{
sType = ( (String) ( (TableItem) e.item ).getData( ) ).trim( );
if ( !sOldType.equals( sType ) )
{
handleChartTypeSelected( );
( (ChartWizardContext) context ).setChartType( ChartUIUtil.getChartType( sType ) );
return true;
}
return false;
}
protected void refreshChartAndPreview( Object oSelected )
{
ChartAdapter.notifyUpdateApply( );
refreshChart( sType, sSubType );
if ( oSelected.getClass( ).equals( Table.class ) )
{
// Ensure populate list after chart model generated
populateSeriesTypesList( );
}
else if ( oSelected.equals( btnOrientation ) )
{
// Auto rotates Axis title when transposing
if ( chartModel instanceof ChartWithAxes )
{
IChartType chartType = ChartUIUtil.getChartType( sType );
Orientation lastOrientation = ChartCacheManager.getInstance( )
.findOrientation( sType );
lastOrientation = getAvailableOrientation( chartType,
getAvailableDimension( chartType,
sDimension ),
lastOrientation );
if ( lastOrientation != getAvailableOrientation( chartType,
getAvailableDimension( chartType,
sDimension ),
orientation ) )
{
rotateAxisTitle( (ChartWithAxes) chartModel );
}
}
}
// Preview after all model changes
doPreview( );
}
protected void handleDimensionBtnSelected( String newDimension )
{
sDimension = newDimension;
ChartCacheManager.getInstance( ).cacheDimension( sType,
sDimension );
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
populateSeriesTypesList( );
}
protected void handleChartTypeSelected( )
{
// Get orientation for non-xtab case. In xtab, orientation won't
// be changed
if ( !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ) )
{
// Get the cached orientation
if ( chartModel != null
&& chartModel instanceof ChartWithAxes )
{
Orientation lastOrientation = ChartCacheManager.getInstance( )
.findOrientation( sOldType );
this.orientation = ChartCacheManager.getInstance( )
.findOrientation( sType );
if ( getAvailableOrientation( ChartUIUtil.getChartType( sOldType ),
getAvailableDimension( ChartUIUtil.getChartType( sOldType ),
sDimension ),
lastOrientation ) != getAvailableOrientation( ChartUIUtil.getChartType( sType ),
getAvailableDimension( ChartUIUtil.getChartType( sType ),
sDimension ),
this.orientation ) )
{
this.rotateAxisTitle( (ChartWithAxes) chartModel );
}
}
}
if ( chartModel != null
&& chartModel instanceof ChartWithAxes
&& ChartCacheManager.getInstance( )
.findCategory( sType ) != null )
{
boolean bCategory = ChartCacheManager.getInstance( )
.findCategory( sType )
.booleanValue( );
if ( ( (ChartWithAxes) chartModel ).getAxes( ).get( 0 ).isSetCategoryAxis( ) )
{
( (ChartWithAxes) chartModel ).getAxes( ).get( 0 ).setCategoryAxis( bCategory );
}
}
sSubType = null;
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
sOldType = sType;
cmpMisc.layout( );
}
protected void handleSubtypeBtnSelected( SelectionEvent e )
{
Button btn = (Button) e.getSource( );
if ( btn.getSelection( ) )
{
if ( this.sSubType != null
&& !getSubtypeFromButton( btn ).equals( sSubType ) )
{
int iTypeIndex = vSubTypeNames.indexOf( sSubType );
if ( iTypeIndex >= 0 )
{
( (Button) cmpTypeButtons.getChildren( )[iTypeIndex] ).setSelection( false );
cmpTypeButtons.redraw( );
}
}
// Cache label position for stacked or non-stacked case.
ChartUIUtil.saveLabelPositionIntoCache( getSeriesDefinitionForProcessing( ) );
sSubType = getSubtypeFromButton( btn );
ChartCacheManager.getInstance( ).cacheSubtype( sType,
sSubType );
}
else
{
if ( this.sSubType != null
&& getSubtypeFromButton( btn ).equals( sSubType ) )
{
// Clicking on the same button should not cause it to be
// unselected
btn.setSelection( true );
// Disable the statement to avoid when un-check all
// stacked attributes of series on format tab, the
// default chart is painted as side-by-side, but it
// can't select stacked button to change chart type to
// stacked in chart type tab.
// needUpdateModel = false;
}
}
}
protected void handleOrientationBtnSelected( )
{
int state = btnOrientation.getSelectionState( );
if ( state == ChartCheckbox.STATE_GRAYED )
{
orientation = null;
}
else if ( state == ChartCheckbox.STATE_SELECTED )
{
orientation = Orientation.HORIZONTAL_LITERAL;
}
else
{
orientation = Orientation.VERTICAL_LITERAL;
}
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
populateSeriesTypesList( );
ChartCacheManager.getInstance( ).cacheOrientation( sType,
orientation );
}
private boolean isAreaSeriesMixed( )
{
boolean hasAreaSeries = false;
boolean hasNonAreaSeries = false;
for ( SeriesDefinition sd : ChartUIUtil.getAllOrthogonalSeriesDefinitions( chartModel ) )
{
if ( sd.getDesignTimeSeries( ) instanceof AreaSeries )
{
hasAreaSeries = true;
}
else
{
hasNonAreaSeries = true;
}
if ( hasAreaSeries && hasNonAreaSeries )
{
return true;
}
}
return false;
}
/**
* Updates the dimension combo according to chart type and axes number
*
* @param sSelectedType
* Chart type
* @return whether the dimension is changed after updating
*/
protected boolean updateDimensionCombo( String sSelectedType )
{
cbDimension.setEObjectParent( getContext( ).getModel( ) );
// Remember last selection
boolean isOldExist = false;
// Update valid dimension list
IChartType chartType = ChartUIUtil.getChartType( sSelectedType );
String[] dimensionArray = chartType.getSupportedDimensions( );
int axesNum = ChartUIUtil.getOrthogonalAxisNumber( chartModel );
cbDimension.removeAll( );
boolean bAreaSeriesMixed = isAreaSeriesMixed( );
for ( int i = 0; i < dimensionArray.length; i++ )
{
boolean isSupported = chartType.isDimensionSupported( dimensionArray[i],
(ChartWizardContext) context,
axesNum,
0 );
if ( isSupported )
{
if ( bAreaSeriesMixed
&& dimensionArray[i].equals( IChartType.TWO_DIMENSION_WITH_DEPTH_TYPE ) )
{
continue;
}
cbDimension.add( dimensionArray[i] );
}
}
cbDimension.setDefualtItem( chartType.getDefaultDimension( ) );
cbDimension.setItemData( cbDimension.getItems( ) );
String cache = ChartCacheManager.getInstance( )
.getDimension( sSelectedType );
String availableCache = getAvailableDimension( chartType, cache );
String thisDimension = getAvailableDimension( chartType, sDimension );
if ( availableCache != thisDimension )
{
isOldExist = true;
}
sDimension = cache;
// Select the previous selection or the default
cbDimension.setText( sDimension );
return !isOldExist;
}
protected boolean isTwoAxesEnabled( )
{
return cbMultipleY.getSelectionIndex( ) == 1;
}
/**
* Returns the object which can add adapters
*
* @return chart model object to add adapters
*/
protected EObject getChartModelObject( )
{
return ( (ChartWizardContext) context ).getModel( );
}
protected void updateAdapters( )
{
EObject model = getChartModelObject( );
if ( container instanceof ChartWizard )
{
// Refresh all adapters
EContentAdapter adapter = ( (ChartWizard) container ).getAdapter( );
model.eAdapters( ).remove( adapter );
TreeIterator<EObject> iterator = model.eAllContents( );
while ( iterator.hasNext( ) )
{
EObject oModel = iterator.next( );
oModel.eAdapters( ).remove( adapter );
}
model.eAdapters( ).add( adapter );
}
else
{
// For extension case, create an adapter and add change listener
EList<Adapter> adapters = model.eAdapters( );
if ( adapters.isEmpty( ) )
{
// Get the previous adapter if existent
if ( adapter == null )
{
adapter = new ChartAdapter( container );
adapter.addListener( this );
}
adapters.add( adapter );
}
else
{
if ( adapters.get( 0 ) instanceof ChartAdapter )
{
( (ChartAdapter) adapters.get( 0 ) ).addListener( this );
}
}
}
}
protected boolean is3D( )
{
return IChartType.THREE_DIMENSION_TYPE.equals( getAvailableDimension( ChartUIUtil.getChartType( sType ),
sDimension ) );
}
private boolean isMultiAxisSupported()
{
boolean bOutXtab = !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART );
return bOutXtab
&& !is3D( )
&& !( IChartType.TWO_DIMENSION_WITH_DEPTH_TYPE.equals( getAvailableDimension( ChartUIUtil.getChartType( sType ),
sDimension ) ) && ChartUIConstants.TYPE_AREA.equals( sType ) );
}
protected void changeOverlaySeriesType( )
{
// cache the second axis series type if it can be combined.
if ( getCurrentChartType( ).canCombine( ) )
{
ChartCacheManager.getInstance( )
.cacheSeriesType( cbSeriesType.getText( ) );
}
try
{
// CHANGE ALL OVERLAY SERIES TO NEW SELECTED TYPE
Axis XAxis = ( (ChartWithAxes) chartModel ).getAxes( )
.get( 0 );
int iSeriesDefinitionIndex = ( XAxis.getAssociatedAxes( )
.get( 0 ) ).getSeriesDefinitions( ).size( ); // SINCE
// THIS IS FOR THE ORTHOGONAL OVERLAY SERIES DEFINITION
int iOverlaySeriesCount = ( XAxis.getAssociatedAxes( )
.get( 1 ) ).getSeriesDefinitions( ).size( );
// DISABLE NOTIFICATIONS WHILE MODEL UPDATE TAKES PLACE
ChartAdapter.beginIgnoreNotifications( );
for ( int i = 0; i < iOverlaySeriesCount; i++ )
{
Series lastSeries = ( ( XAxis.getAssociatedAxes( ).get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getDesignTimeSeries( );
if ( !lastSeries.getDisplayName( )
.equals( cbSeriesType.getText( ) ) )
{
String name = htSeriesNames.get( cbSeriesType.getText( ) )
.getClass( )
.getName( );
// check for cache
Series newSeries = ChartCacheManager.getInstance( )
.findSeries( name, iSeriesDefinitionIndex + i );
if ( newSeries == null || newSeries instanceof BarSeries )
{
newSeries = htSeriesNames.get( cbSeriesType.getText( ) )
.copyInstance( );
newSeries.translateFrom( lastSeries,
iSeriesDefinitionIndex,
chartModel );
}
// ADD THE MODEL ADAPTERS TO THE NEW SERIES
newSeries.eAdapters( ).addAll( chartModel.eAdapters( ) );
// UPDATE THE SERIES DEFINITION WITH THE SERIES INSTANCE
( ( XAxis.getAssociatedAxes( ).get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( )
.clear( );
( ( XAxis.getAssociatedAxes( ).get( 1 ) ).getSeriesDefinitions( ).get( i ) ).getSeries( )
.add( newSeries );
ChartUIUtil.setSeriesName( chartModel );
}
}
ChartWizard.removeException( ChartWizard.TaskSelType_chOvST_ID );
}
catch ( Exception e )
{
ChartWizard.showException( ChartWizard.TaskSelType_chOvST_ID,
e.getLocalizedMessage( ) );
}
finally
{
// ENABLE NOTIFICATIONS IN CASE EXCEPTIONS OCCUR
ChartAdapter.endIgnoreNotifications( );
}
}
protected void populateSeriesTypesList( )
{
if ( cbSeriesType == null )
{
return;
}
if ( htSeriesNames == null )
{
htSeriesNames = new Hashtable<String, Series>( 20 );
}
// Populate Series Types List
Series series = getSeriesDefinitionForProcessing( ).getDesignTimeSeries( );
ChartUIExtensionUtil.populateSeriesTypesList( htSeriesNames,
cbSeriesType,
getContext( ),
ChartUIExtensionsImpl.instance( )
.getUIChartTypeExtensions( getContext( ).getIdentifier( ) ),
series );
// Select the appropriate current series type if overlay series exists
if ( this.chartModel instanceof ChartWithAxes )
{
Axis xAxis = ( ( (ChartWithAxes) chartModel ).getAxes( )
.get( 0 ) );
if ( xAxis.getAssociatedAxes( ).size( ) > 1 )
{
// Set series name from cache or model
String lastType = ChartCacheManager.getInstance( )
.findSeriesType( );
Axis overlayAxis = xAxis.getAssociatedAxes( ).get( 1 );
if ( !overlayAxis.getSeriesDefinitions( ).isEmpty( ) )
{
Series oseries = ( overlayAxis.getSeriesDefinitions( )
.get( 0 ) ).getDesignTimeSeries( );
String sDisplayName = oseries.getDisplayName( );
if ( lastType != null )
{
cbSeriesType.setText( lastType );
}
else
{
cbSeriesType.setText( sDisplayName );
}
String seriesName = oseries.getSeriesIdentifier( )
.toString( );
if ( seriesName.trim( ).length( ) != 0 )
{
Iterator<Entry<String, Series>> itr = htSeriesNames.entrySet( )
.iterator( );
while ( itr.hasNext( ) )
{
Entry<String, Series> entry = itr.next( );
entry.getValue( ).setSeriesIdentifier( seriesName );
}
}
}
// Update overlay series
changeOverlaySeriesType( );
}
}
}
/**
* This method populates the subtype panel (creating its components if
* necessary). It gets called when the type selection changes or when the
* dimension selection changes (since not all sub types are supported for
* all dimension selections).
*
* @param sSelectedType
* Type from Type List
*/
protected void createAndDisplayTypesSheet( String sSelectedType )
{
IChartType chartType = ChartUIUtil.getChartType( sSelectedType );
if ( btnOrientation != null )
{
lblOrientation.setEnabled( chartType.supportsTransposition( )
&& !is3D( ) );
btnOrientation.setEnabled( chartType.supportsTransposition( )
&& !is3D( ) );
}
// Update dimension
updateDimensionCombo( sSelectedType );
// Show the subtypes for the selected type based on current selections
// of dimension and orientation
String availDim = getAvailableDimension( chartType, sDimension );
Vector<IChartSubType> vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( availDim,
getAvailableOrientation( chartType, availDim, this.orientation ) ) );
if ( vSubTypes.size( ) == 0 )
{
vSubTypes = new Vector<IChartSubType>( chartType.getChartSubtypes( chartType.getDefaultDimension( ),
chartType.getDefaultOrientation( ) ) );
this.sDimension = null;
this.orientation = null;
}
// If two orientations are not supported, to get the default.
if ( btnOrientation == null || !btnOrientation.isEnabled( ) )
{
this.orientation = null;
}
// Cache the orientation for each chart type.
ChartCacheManager.getInstance( ).cacheOrientation( sType, orientation );
if ( chartModel == null )
{
ChartCacheManager.getInstance( ).cacheCategory( sType, true );
}
else if ( chartModel instanceof ChartWithAxes )
{
ChartCacheManager.getInstance( )
.cacheCategory( sType,
( ( (ChartWithAxes) chartModel ).getAxes( )
.get( 0 ) ).isCategoryAxis( ) );
}
// Update the UI with information for selected type
createSubtypeBtnGroups( vSubTypes );
updateOrientationUIState();
cmpRight.layout( );
}
protected void setDefaultSubtypeSelection( )
{
if ( sSubType == null )
{
// Try to get cached subtype
sSubType = ChartCacheManager.getInstance( ).findSubtype( sType );
}
if ( sSubType == null )
{
// Get the default subtype
( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true );
sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] );
ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType );
}
else
{
Control[] buttons = cmpTypeButtons.getChildren( );
boolean bSelected = false;
for ( int iB = 0; iB < buttons.length; iB++ )
{
if ( getSubtypeFromButton( buttons[iB] ).equals( sSubType ) )
{
( (Button) buttons[iB] ).setSelection( true );
bSelected = true;
break;
}
}
// If specified subType is not found, select default
if ( !bSelected )
{
( (Button) cmpTypeButtons.getChildren( )[0] ).setSelection( true );
sSubType = getSubtypeFromButton( cmpTypeButtons.getChildren( )[0] );
ChartCacheManager.getInstance( ).cacheSubtype( sType, sSubType );
}
}
cmpTypeButtons.redraw( );
}
private void setDefaultTypeSelection( )
{
if ( table.getItems( ).length > 0 )
{
if ( sType == null )
{
table.select( 0 );
sType = (String) ( table.getSelection( )[0] ).getData( );
}
else
{
TableItem[] tiAll = table.getItems( );
for ( int iTI = 0; iTI < tiAll.length; iTI++ )
{
if ( tiAll[iTI].getData( ).equals( sType ) )
{
table.select( iTI );
break;
}
}
}
sOldType = sType;
createAndDisplayTypesSheet( sType );
setDefaultSubtypeSelection( );
}
}
public void dispose( )
{
super.dispose( );
lstDescriptor.clear( );
chartModel = null;
adapter = null;
if ( previewPainter != null )
{
previewPainter.dispose( );
}
previewPainter = null;
sSubType = null;
sType = null;
sDimension = null;
vSubTypeNames = null;
orientation = null;
}
protected void refreshChart( String type, String subType )
{
// DISABLE PREVIEW REFRESH DURING CONVERSION
ChartAdapter.beginIgnoreNotifications( );
IChartType chartType = ChartUIUtil.getChartType( type );
try
{
chartModel = adapteChartModel( chartModel, chartType, subType );
if ( getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART ) )
{
// Update model for part chart case
ChartWithAxes cwa = (ChartWithAxes) chartModel;
cwa.getAxes( ).get( 0 ).setCategoryAxis( true );
if ( cwa.isTransposed( ) )
{
cwa.setReverseCategory( true );
}
}
updateAdapters( );
ChartWizard.removeException( ChartWizard.TaskSelType_refreCh_ID );
}
catch ( Exception e )
{
ChartWizard.showException( ChartWizard.TaskSelType_refreCh_ID,
e.getLocalizedMessage( ) );
}
// RE-ENABLE PREVIEW REFRESH
ChartAdapter.endIgnoreNotifications( );
updateSelection( );
( (ChartWizardContext) context ).setModel( chartModel );
( (ChartWizardContext) context ).setChartType( chartType );
setContext( context );
}
protected Chart adapteChartModel( Chart chartModel, IChartType chartType, String subType )
{
Chart cm = chartType.getModel( subType,
this.orientation,
this.sDimension,
chartModel );
chartValueUpdater.update( cm, null, false );
return cm;
}
private SeriesDefinition getSeriesDefinitionForProcessing( )
{
// TODO Attention: all index is 0
SeriesDefinition sd = null;
if ( chartModel instanceof ChartWithAxes )
{
sd = ( (ChartWithAxes) chartModel ).getAxes( )
.get( 0 )
.getAssociatedAxes( )
.get( 0 )
.getSeriesDefinitions( )
.get( 0 );
}
else if ( chartModel instanceof ChartWithoutAxes )
{
sd = ( ( (ChartWithoutAxes) chartModel ).getSeriesDefinitions( ).get( 0 ) ).getSeriesDefinitions( )
.get( 0 );
}
return sd;
}
/**
* Updates UI selection according to Chart type
*
*/
protected void updateSelection( )
{
boolean bOutXtab = !getDataServiceProvider( ).checkState( IDataServiceProvider.PART_CHART );
if (getCurrentChartType().isChartWithAxes())
{
if ( cbMultipleY != null )
{
lblMultipleY.setEnabled( isMultiAxisSupported( ) );
cbMultipleY.setEnabled( isMultiAxisSupported( ) );
}
if ( cbSeriesType != null )
{
lblSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) );
cbSeriesType.setEnabled( bOutXtab && isTwoAxesEnabled( ) );
}
}
else
{
if ( cbMultipleY != null )
{
cbMultipleY.select( 0 );
getContext( ).setMoreAxesSupported( false );
lblMultipleY.setEnabled( false );
cbMultipleY.setEnabled( false );
}
if ( cbSeriesType != null )
{
lblSeriesType.setEnabled( false );
cbSeriesType.setEnabled( false );
}
}
if ( btnOrientation != null )
{
lblOrientation.setEnabled( bOutXtab && lblOrientation.isEnabled( ) );
btnOrientation.setEnabled( bOutXtab && btnOrientation.isEnabled( ) );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#getContext()
*/
public ChartWizardContext getContext( )
{
ChartWizardContext context = (ChartWizardContext) super.getContext( );
context.setModel( this.chartModel );
return context;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.frameworks.taskwizard.interfaces.ITask#setContext(org.eclipse.birt.frameworks.taskwizard.interfaces.IWizardContext)
*/
public void setContext( IWizardContext context )
{
super.setContext( context );
this.chartModel = ( (ChartWizardContext) context ).getModel( );
if ( chartModel != null )
{
this.sType = ( (ChartWizardContext) context ).getChartType( )
.getName( );
this.sSubType = chartModel.getSubType( );
if ( chartModel.isSetDimension( ) )
{
this.sDimension = translateDimensionString( chartModel.getDimension( )
.getName( ) );
ChartCacheManager.getInstance( ).cacheDimension( sType,
sDimension );
}
if ( chartModel instanceof ChartWithAxes )
{
this.orientation = ( (ChartWithAxes) chartModel ).isSetOrientation( ) ? ( (ChartWithAxes) chartModel ).getOrientation( )
: null;
ChartCacheManager.getInstance( ).cacheOrientation( sType, this.orientation );
int iYAxesCount = ChartUIUtil.getOrthogonalAxisNumber( chartModel );
// IF THE UI HAS BEEN INITIALIZED...I.E. IF setContext() IS
// CALLED AFTER getUI()
if ( iYAxesCount > 1
&& ( lblMultipleY != null && !lblMultipleY.isDisposed( ) ) )
{
lblMultipleY.setEnabled( !is3D( ) );
cbMultipleY.setEnabled( !is3D( ) );
lblSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) );
cbSeriesType.setEnabled( !is3D( ) && isTwoAxesEnabled( ) );
selectMultipleAxis( iYAxesCount );
// TODO: Update the series type based on series type for the
// second Y axis
}
}
}
}
private void selectMultipleAxis( int yAxisNum )
{
if ( getContext( ).isMoreAxesSupported( ) )
{
cbMultipleY.select( 2 );
}
else
{
if ( yAxisNum > 2 )
{
cbMultipleY.select( 2 );
getContext( ).setMoreAxesSupported( true );
}
else
{
cbMultipleY.select( yAxisNum > 0 ? yAxisNum - 1 : 0 );
}
}
}
public void changeTask( Notification notification )
{
if ( previewPainter != null )
{
doPreview( );
}
}
private void checkDataTypeForChartWithAxes( )
{
// To check the data type of base series and orthogonal series in chart
// with axes
List<SeriesDefinition> sdList = new ArrayList<SeriesDefinition>( );
sdList.addAll( ChartUIUtil.getBaseSeriesDefinitions( getChartModel( ) ) );
for ( int i = 0; i < sdList.size( ); i++ )
{
SeriesDefinition sd = sdList.get( i );
Series series = sd.getDesignTimeSeries( );
checkDataTypeForBaseSeries( ChartUIUtil.getDataQuery( sd, 0 ),
series );
}
sdList.clear( );
sdList.addAll( ChartUIUtil.getAllOrthogonalSeriesDefinitions( getChartModel( ) ) );
for ( int i = 0; i < sdList.size( ); i++ )
{
SeriesDefinition sd = sdList.get( i );
Series series = sd.getDesignTimeSeries( );
checkDataTypeForOrthoSeries( ChartUIUtil.getDataQuery( sd, 0 ),
series );
}
}
protected IDataServiceProvider getDataServiceProvider( )
{
return getContext( ).getDataServiceProvider( );
}
private String getSubtypeFromButton( Control button )
{
return (String) button.getData( );
}
private void checkDataTypeForBaseSeries( Query query, Series series )
{
checkDataTypeImpl( query, series, true );
}
private void checkDataTypeForOrthoSeries( Query query, Series series )
{
checkDataTypeImpl( query, series, false );
}
private void checkDataTypeImpl( Query query, Series series,
boolean isBaseSeries )
{
String expression = query.getDefinition( );
Axis axis = null;
for ( EObject o = query; o != null; )
{
o = o.eContainer( );
if ( o instanceof Axis )
{
axis = (Axis) o;
break;
}
}
Collection<ISeriesUIProvider> cRegisteredEntries = ChartUIExtensionsImpl.instance( )
.getSeriesUIComponents( getContext( ).getIdentifier( ) );
Iterator<ISeriesUIProvider> iterEntries = cRegisteredEntries.iterator( );
String sSeries = null;
while ( iterEntries.hasNext( ) )
{
ISeriesUIProvider provider = iterEntries.next( );
sSeries = provider.getSeriesClass( );
if ( sSeries.equals( series.getClass( ).getName( ) ) )
{
if ( chartModel instanceof ChartWithAxes )
{
DataType dataType = getDataServiceProvider( ).getDataType( expression );
SeriesDefinition baseSD = ( ChartUIUtil.getBaseSeriesDefinitions( chartModel ).get( 0 ) );
SeriesDefinition orthSD = null;
orthSD = (SeriesDefinition) series.eContainer( );
String aggFunc = null;
try
{
aggFunc = ChartUtil.getAggregateFuncExpr( orthSD,
baseSD,
query );
ChartWizard.removeException( ChartWizard.PluginSet_getAggF_ID );
}
catch ( ChartException e )
{
ChartWizard.showException( ChartWizard.PluginSet_getAggF_ID,
e.getLocalizedMessage( ) );
}
if ( baseSD != null )
{
// If aggregation is set to count/distinctcount on base
// series, don't change data type to numeric.
if ( !isBaseSeries
&& baseSD != orthSD
&& ChartUtil.isMagicAggregate( aggFunc ) )
{
dataType = DataType.NUMERIC_LITERAL;
}
}
if ( isValidatedAxis( dataType, axis.getType( ) ) )
{
ChartWizard.removeException( ChartWizard.CheckSeriesBindingType_ID
+ series.eContainer( ).hashCode( ) );
break;
}
AxisType[] axisTypes = provider.getCompatibleAxisType( series );
for ( int i = 0; i < axisTypes.length; i++ )
{
if ( isValidatedAxis( dataType, axisTypes[i] ) )
{
axisNotification( axis, axisTypes[i] );
// Avoid modifying model to notify an event loop
ChartAdapter.beginIgnoreNotifications( );
axis.setType( axisTypes[i] );
ChartAdapter.endIgnoreNotifications( );
break;
}
}
}
try
{
provider.validateSeriesBindingType( series,
getDataServiceProvider( ) );
ChartWizard.removeException( ChartWizard.CheckSeriesBindingType_ID
+ series.eContainer( ).hashCode( ) );
}
catch ( ChartException ce )
{
ChartWizard.showException( ChartWizard.CheckSeriesBindingType_ID
+ series.eContainer( ).hashCode( ),
Messages.getFormattedString( "TaskSelectData.Warning.TypeCheck",//$NON-NLS-1$
new String[]{
ce.getLocalizedMessage( ),
series.getDisplayName( )
} ) );
}
break;
}
}
}
private boolean isValidatedAxis( DataType dataType, AxisType axisType )
{
if ( dataType == null )
{
return true;
}
else if ( ( dataType == DataType.DATE_TIME_LITERAL )
&& ( axisType == AxisType.DATE_TIME_LITERAL ) )
{
return true;
}
else if ( ( dataType == DataType.NUMERIC_LITERAL )
&& ( ( axisType == AxisType.LINEAR_LITERAL ) || ( axisType == AxisType.LOGARITHMIC_LITERAL ) ) )
{
return true;
}
else if ( ( dataType == DataType.TEXT_LITERAL )
&& ( axisType == AxisType.TEXT_LITERAL ) )
{
return true;
}
return false;
}
private void axisNotification( Axis axis, AxisType type )
{
ChartAdapter.beginIgnoreNotifications( );
{
convertSampleData( axis, type );
axis.setFormatSpecifier( null );
EList<MarkerLine> markerLines = axis.getMarkerLines( );
for ( int i = 0; i < markerLines.size( ); i++ )
{
( markerLines.get( i ) ).setFormatSpecifier( null );
}
EList<MarkerRange> markerRanges = axis.getMarkerRanges( );
for ( int i = 0; i < markerRanges.size( ); i++ )
{
( markerRanges.get( i ) ).setFormatSpecifier( null );
}
}
ChartAdapter.endIgnoreNotifications( );
}
private void convertSampleData( Axis axis, AxisType axisType )
{
if(chartModel.getSampleData( ) == null)
{
return;
}
if ( ( axis.getAssociatedAxes( ) != null )
&& ( axis.getAssociatedAxes( ).size( ) != 0 ) )
{
BaseSampleData bsd = chartModel.getSampleData( )
.getBaseSampleData( )
.get( 0 );
bsd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType,
bsd.getDataSetRepresentation( ),
0 ) );
}
else
{
int iStartIndex = getFirstSeriesDefinitionIndexForAxis( axis );
int iEndIndex = iStartIndex + axis.getSeriesDefinitions( ).size( );
int iOSDSize = chartModel.getSampleData( )
.getOrthogonalSampleData( )
.size( );
for ( int i = 0; i < iOSDSize; i++ )
{
OrthogonalSampleData osd = chartModel.getSampleData( )
.getOrthogonalSampleData( )
.get( i );
if ( osd.getSeriesDefinitionIndex( ) >= iStartIndex
&& osd.getSeriesDefinitionIndex( ) < iEndIndex )
{
osd.setDataSetRepresentation( ChartUIUtil.getConvertedSampleDataRepresentation( axisType,
osd.getDataSetRepresentation( ),
i ) );
}
}
}
}
private int getFirstSeriesDefinitionIndexForAxis( Axis axis )
{
List<Axis> axisList = ( (ChartWithAxes) chartModel ).getAxes( )
.get( 0 )
.getAssociatedAxes( );
int index = 0;
for ( int i = 0; i < axisList.size( ); i++ )
{
if ( axis.equals( axisList.get( i ) ) )
{
index = i;
break;
}
}
int iTmp = 0;
for ( int i = 0; i < index; i++ )
{
iTmp += ChartUIUtil.getAxisYForProcessing( (ChartWithAxes) chartModel,
i )
.getSeriesDefinitions( )
.size( );
}
return iTmp;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.core.ui.frameworks.taskwizard.SimpleTask#getImage()
*/
public Image getImage( )
{
return UIHelper.getImage( ChartUIConstants.IMAGE_TASK_TYPE );
}
/**
* Rotates Axis Title when transposing
*
* @param cwa
* chart model
*/
private void rotateAxisTitle( ChartWithAxes cwa )
{
// Still rendering, it has auto case and use default behavior, different
// chart type has different default behavior.
boolean bRender = true;
ChartAdapter.beginIgnoreNotifications( );
Axis aX = ChartUIUtil.getAxisXForProcessing( cwa );
if ( aX.getTitle( ).getCaption( ).getFont( ).isSetRotation( ) )
{
double curRotation = aX.getTitle( )
.getCaption( )
.getFont( )
.getRotation( );
aX.getTitle( )
.getCaption( )
.getFont( )
.setRotation( curRotation >= 0 ? 90 - curRotation : -90
- curRotation );
}
EList<Axis> aYs = aX.getAssociatedAxes( );
for ( int i = 0; i < aYs.size( ); i++ )
{
Axis aY = aYs.get( i );
if ( aY.getTitle( ).getCaption( ).getFont( ).isSetRotation( ) )
{
double curRotation = aY.getTitle( )
.getCaption( )
.getFont( )
.getRotation( );
aY.getTitle( )
.getCaption( )
.getFont( )
.setRotation( curRotation >= 0 ? 90 - curRotation : -90
- curRotation );
}
}
ChartAdapter.endIgnoreNotifications( );
if ( bRender )
{
doPreview( );
}
}
public IChartPreviewPainter createPreviewPainter( )
{
ChartPreviewPainter painter = new ChartPreviewPainter( getContext( ) );
getPreviewCanvas( ).addPaintListener( painter );
getPreviewCanvas( ).addControlListener( painter );
painter.setPreview( getPreviewCanvas( ) );
return painter;
}
protected Chart getPreviewChartModel( ) throws ChartException
{
if ( getContext( ) == null )
{
return null;
}
return getContext( ).getModel( );
}
public void doPreview( )
{
// To update data type after chart type conversion
try
{
final Chart chart = getPreviewChartModel( );
if ( chart instanceof ChartWithAxes )
{
ChartAdapter.beginIgnoreNotifications( );
// should use design time model rather than
// runtime model.
checkDataTypeForChartWithAxes( );
ChartAdapter.endIgnoreNotifications( );
}
else
{
ChartWizard.removeAllExceptions( ChartWizard.CheckSeriesBindingType_ID );
}
LivePreviewTask lpt = new LivePreviewTask( Messages.getString( "TaskFormatChart.LivePreviewTask.BindData" ), null ); //$NON-NLS-1$
// Add a task to retrieve data and bind data to chart.
lpt.addTask( new LivePreviewTask( ) {
public void run( )
{
if ( previewPainter != null )
{
setParameter( ChartLivePreviewThread.PARAM_CHART_MODEL,
ChartUIUtil.prepareLivePreview( chart,
getDataServiceProvider( ),
( (ChartWizardContext) context ).getActionEvaluator( ) ) );
}
}
} );
// Add a task to render chart.
lpt.addTask( new LivePreviewTask( ) {
public void run( )
{
if ( previewCanvas != null
&& previewCanvas.getDisplay( ) != null
&& !previewCanvas.getDisplay( ).isDisposed( ) )
{
previewCanvas.getDisplay( ).syncExec( new Runnable( ) {
public void run( )
{
// Repaint chart.
if ( previewPainter != null )
{
Chart cm = (Chart) getParameter( ChartLivePreviewThread.PARAM_CHART_MODEL );
previewPainter.renderModel( cm );
}
}
} );
}
}
} );
// Add live preview tasks to live preview thread.
( (ChartLivePreviewThread) ( (ChartWizardContext) context ).getLivePreviewThread( ) ).setParentShell( getPreviewCanvas( ).getShell( ) );
( (ChartLivePreviewThread) ( (ChartWizardContext) context ).getLivePreviewThread( ) ).add( lpt );
}
catch ( ChartException e )
{
WizardBase.showException( e.getMessage( ) );
}
}
public Canvas getPreviewCanvas( )
{
return previewCanvas;
}
public boolean isPreviewable( )
{
return true;
}
protected IChartType getCurrentChartType( )
{
return ChartUIUtil.getChartType( sType );
}
protected void createUIDescriptors( Composite parent )
{
for ( TaskSelectTypeUIDescriptor descriptor : lstDescriptor )
{
if ( descriptor.isVisible( ) )
{
descriptor.createControl( parent );
}
}
}
protected final void addTypeUIDescriptor(
TaskSelectTypeUIDescriptor newDescriptor )
{
if ( newDescriptor.getIndex( ) < 0 )
{
// add to the last if it's negative
lstDescriptor.add( newDescriptor );
return;
}
int lastIndex = -1;
for ( int i = 0; i < lstDescriptor.size( ); i++ )
{
TaskSelectTypeUIDescriptor descriptor = lstDescriptor.get( i );
if ( newDescriptor.getIndex( ) > lastIndex
&& newDescriptor.getIndex( ) <= descriptor.getIndex( ) )
{
lstDescriptor.add( i, newDescriptor );
return;
}
lastIndex = descriptor.getIndex( );
}
lstDescriptor.add( newDescriptor );
}
protected void addOptionalUIDescriptor( )
{
addTypeUIDescriptor( new TaskSelectTypeUIDescriptor( ) {
public int getIndex( )
{
return 20;
}
public void createControl( Composite parent )
{
lblOutput = new Label( parent, SWT.WRAP );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalIndent = 10;
lblOutput.setLayoutData( gd );
lblOutput.setText( Messages.getString( "TaskSelectType.Label.OutputFormat" ) ); //$NON-NLS-1$
}
// Add the ComboBox for Output Format
cbOutput = new Combo( parent, SWT.DROP_DOWN
| SWT.READ_ONLY );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cbOutput.setLayoutData( gd );
cbOutput.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event event )
{
String outputFormat = outputFormats[cbOutput.getSelectionIndex( )];
getContext( ).setOutputFormat( outputFormat );
// Update apply button
if ( container != null && container instanceof ChartWizard )
{
( (ChartWizard) container ).updateApplyButton( );
}
}
} );
}
cbOutput.setItems( outputDisplayNames );
String sCurrentFormat = getContext( ).getOutputFormat( );
for ( int index = 0; index < outputFormats.length; index++ )
{
if ( outputFormats[index].equals( sCurrentFormat ) )
{
cbOutput.select( index );
break;
}
}
}
} );
}
/**
* Return available orientation even if it is not set.
*
* @param chartType
* @param dimension
* @param refOrientation
* @return available orientation
*/
protected Orientation getAvailableOrientation( IChartType chartType, String dimension, Orientation refOrientation )
{
if ( refOrientation == null )
{
return chartType.getDefaultOrientation( );
}
else if ( refOrientation == Orientation.HORIZONTAL_LITERAL
&& !chartType.supportsTransposition( dimension ) )
{
return chartType.getDefaultOrientation( );
}
return refOrientation;
}
/**
* Returns available dimension.
*
* @param ct
* @param refDimension
* @return dimension available dimension.
*/
protected String getAvailableDimension( IChartType ct, String refDimension )
{
if ( refDimension == null )
{
return ct.getDefaultDimension( );
}
return refDimension;
}
}
|
package io.lumify.securegraph.model.user;
import com.altamiracorp.bigtable.model.user.ModelUserContext;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.lumify.core.config.Configuration;
import io.lumify.core.exception.LumifyException;
import io.lumify.core.model.ontology.Concept;
import io.lumify.core.model.ontology.OntologyLumifyProperties;
import io.lumify.core.model.ontology.OntologyRepository;
import io.lumify.core.model.user.*;
import io.lumify.core.security.LumifyVisibility;
import io.lumify.core.user.Privilege;
import io.lumify.core.user.SystemUser;
import io.lumify.core.user.User;
import io.lumify.core.util.LumifyLogger;
import io.lumify.core.util.LumifyLoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.securegraph.Graph;
import org.securegraph.Vertex;
import org.securegraph.VertexBuilder;
import org.securegraph.util.ConvertingIterable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkNotNull;
@Singleton
public class SecureGraphUserRepository extends UserRepository {
private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(SecureGraphUserRepository.class);
private final AuthorizationRepository authorizationRepository;
private Graph graph;
private String userConceptId;
private org.securegraph.Authorizations authorizations;
private final Cache<String, Set<String>> userAuthorizationCache = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.SECONDS)
.build();
private final Cache<String, Set<Privilege>> userPrivilegesCache = CacheBuilder.newBuilder()
.expireAfterWrite(15, TimeUnit.SECONDS)
.build();
private UserListenerUtil userListenerUtil;
@Inject
public SecureGraphUserRepository(
final Configuration configuration,
final AuthorizationRepository authorizationRepository,
final Graph graph,
final OntologyRepository ontologyRepository,
final UserListenerUtil userListenerUtil) {
super(configuration);
this.authorizationRepository = authorizationRepository;
this.graph = graph;
this.userListenerUtil = userListenerUtil;
authorizationRepository.addAuthorizationToGraph(VISIBILITY_STRING);
authorizationRepository.addAuthorizationToGraph(LumifyVisibility.SUPER_USER_VISIBILITY_STRING);
Concept userConcept = ontologyRepository.getOrCreateConcept(null, LUMIFY_USER_CONCEPT_ID, "lumifyUser");
userConceptId = userConcept.getTitle();
Set<String> authorizationsSet = new HashSet<String>();
authorizationsSet.add(VISIBILITY_STRING);
authorizationsSet.add(LumifyVisibility.SUPER_USER_VISIBILITY_STRING);
this.authorizations = authorizationRepository.createAuthorizations(authorizationsSet);
}
private SecureGraphUser createFromVertex(Vertex user) {
if (user == null) {
return null;
}
String[] authorizations = Iterables.toArray(getAuthorizations(user), String.class);
ModelUserContext modelUserContext = getModelUserContext(authorizations);
String userName = UserLumifyProperties.USERNAME.getPropertyValue(user);
String displayName = UserLumifyProperties.DISPLAY_NAME.getPropertyValue(user);
String userId = (String) user.getId();
String userStatus = UserLumifyProperties.STATUS.getPropertyValue(user);
Set<Privilege> privileges = Privilege.stringToPrivileges(UserLumifyProperties.PRIVILEGES.getPropertyValue(user));
String currentWorkspaceId = UserLumifyProperties.CURRENT_WORKSPACE.getPropertyValue(user);
LOGGER.debug("Creating user from UserRow. userName: %s, authorizations: %s", userName, UserLumifyProperties.AUTHORIZATIONS.getPropertyValue(user));
return new SecureGraphUser(userId, userName, displayName, modelUserContext, userStatus, privileges, currentWorkspaceId);
}
@Override
public User findByUsername(String username) {
return createFromVertex(Iterables.getFirst(graph.query(authorizations)
.has(UserLumifyProperties.USERNAME.getKey(), username)
.has(OntologyLumifyProperties.CONCEPT_TYPE.getKey(), userConceptId)
.vertices(), null));
}
@Override
public Iterable<User> findAll() {
return new ConvertingIterable<Vertex, User>(graph.query(authorizations)
.has(OntologyLumifyProperties.CONCEPT_TYPE.getKey(), userConceptId)
.vertices()) {
@Override
protected User convert(Vertex vertex) {
return createFromVertex(vertex);
}
};
}
@Override
public User findById(String userId) {
return createFromVertex(findByIdUserVertex(userId));
}
public Vertex findByIdUserVertex(String userId) {
return graph.getVertex(userId, authorizations);
}
@Override
public User addUser(String username, String displayName, String password, String[] userAuthorizations) {
User existingUser = findByUsername(username);
if (existingUser != null) {
throw new LumifyException("duplicate username");
}
String authorizationsString = StringUtils.join(userAuthorizations, ",");
byte[] salt = UserPasswordUtil.getSalt();
byte[] passwordHash = UserPasswordUtil.hashPassword(password, salt);
String id = "USER_" + graph.getIdGenerator().nextId().toString();
VertexBuilder userBuilder = graph.prepareVertex(id, VISIBILITY.getVisibility(), this.authorizations);
UserLumifyProperties.USERNAME.setProperty(userBuilder, username, VISIBILITY.getVisibility());
UserLumifyProperties.DISPLAY_NAME.setProperty(userBuilder, displayName, VISIBILITY.getVisibility());
OntologyLumifyProperties.CONCEPT_TYPE.setProperty(userBuilder, userConceptId, VISIBILITY.getVisibility());
UserLumifyProperties.PASSWORD_SALT.setProperty(userBuilder, salt, VISIBILITY.getVisibility());
UserLumifyProperties.PASSWORD_HASH.setProperty(userBuilder, passwordHash, VISIBILITY.getVisibility());
UserLumifyProperties.STATUS.setProperty(userBuilder, UserStatus.OFFLINE.toString(), VISIBILITY.getVisibility());
UserLumifyProperties.AUTHORIZATIONS.setProperty(userBuilder, authorizationsString, VISIBILITY.getVisibility());
UserLumifyProperties.PRIVILEGES.setProperty(userBuilder, Privilege.toString(getDefaultPrivileges()), VISIBILITY.getVisibility());
User user = createFromVertex(userBuilder.save());
graph.flush();
userListenerUtil.fireNewUserAddedEvent(user);
return user;
}
@Override
public void setPassword(User user, String password) {
byte[] salt = UserPasswordUtil.getSalt();
byte[] passwordHash = UserPasswordUtil.hashPassword(password, salt);
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
UserLumifyProperties.PASSWORD_SALT.setProperty(userVertex, salt, VISIBILITY.getVisibility());
UserLumifyProperties.PASSWORD_HASH.setProperty(userVertex, passwordHash, VISIBILITY.getVisibility());
graph.flush();
}
@Override
public boolean isPasswordValid(User user, String password) {
try {
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
return UserPasswordUtil.validatePassword(password, UserLumifyProperties.PASSWORD_SALT.getPropertyValue(userVertex), UserLumifyProperties.PASSWORD_HASH.getPropertyValue(userVertex));
} catch (Exception ex) {
throw new RuntimeException("error validating password", ex);
}
}
@Override
public User setCurrentWorkspace(String userId, String workspaceId) {
User user = findById(userId);
checkNotNull(user, "Could not find user: " + userId);
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
UserLumifyProperties.CURRENT_WORKSPACE.setProperty(userVertex, workspaceId, VISIBILITY.getVisibility());
graph.flush();
return user;
}
@Override
public String getCurrentWorkspaceId(String userId) {
User user = findById(userId);
checkNotNull(user, "Could not find user: " + userId);
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
return UserLumifyProperties.CURRENT_WORKSPACE.getPropertyValue(userVertex);
}
@Override
public User setStatus(String userId, UserStatus status) {
SecureGraphUser user = (SecureGraphUser) findById(userId);
checkNotNull(user, "Could not find user: " + userId);
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
UserLumifyProperties.STATUS.setProperty(userVertex, status.toString(), VISIBILITY.getVisibility());
graph.flush();
user.setUserStatus(status.toString());
return user;
}
@Override
public void addAuthorization(User user, String auth) {
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
Set<String> authorizations = getAuthorizations(userVertex);
if (authorizations.contains(auth)) {
return;
}
authorizations.add(auth);
this.authorizationRepository.addAuthorizationToGraph(auth);
String authorizationsString = StringUtils.join(authorizations, ",");
UserLumifyProperties.AUTHORIZATIONS.setProperty(userVertex, authorizationsString, VISIBILITY.getVisibility());
graph.flush();
userAuthorizationCache.invalidate(user.getUserId());
}
@Override
public void removeAuthorization(User user, String auth) {
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
Set<String> authorizations = getAuthorizations(userVertex);
if (!authorizations.contains(auth)) {
return;
}
authorizations.remove(auth);
String authorizationsString = StringUtils.join(authorizations, ",");
UserLumifyProperties.AUTHORIZATIONS.setProperty(userVertex, authorizationsString, VISIBILITY.getVisibility());
graph.flush();
userAuthorizationCache.invalidate(user.getUserId());
}
@Override
public org.securegraph.Authorizations getAuthorizations(User user, String... additionalAuthorizations) {
Set<String> userAuthorizations;
if (user instanceof SystemUser) {
userAuthorizations = new HashSet<String>();
userAuthorizations.add(LumifyVisibility.SUPER_USER_VISIBILITY_STRING);
} else {
userAuthorizations = userAuthorizationCache.getIfPresent(user.getUserId());
}
if (userAuthorizations == null) {
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
userAuthorizations = getAuthorizations(userVertex);
userAuthorizationCache.put(user.getUserId(), userAuthorizations);
}
Set<String> authorizationsSet = new HashSet<String>(userAuthorizations);
Collections.addAll(authorizationsSet, additionalAuthorizations);
return authorizationRepository.createAuthorizations(authorizationsSet);
}
public static Set<String> getAuthorizations(Vertex userVertex) {
String authorizationsString = UserLumifyProperties.AUTHORIZATIONS.getPropertyValue(userVertex);
if (authorizationsString == null) {
return new HashSet<String>();
}
String[] authorizationsArray = authorizationsString.split(",");
if (authorizationsArray.length == 1 && authorizationsArray[0].length() == 0) {
authorizationsArray = new String[0];
}
HashSet<String> authorizations = new HashSet<String>();
for (String s : authorizationsArray) {
// Accumulo doesn't like zero length strings. they shouldn't be in the auth string to begin with but this just protects from that happening.
if (s.trim().length() == 0) {
continue;
}
authorizations.add(s);
}
return authorizations;
}
@Override
public Set<Privilege> getPrivileges(User user) {
Set<Privilege> privileges;
if (user instanceof SystemUser) {
return Privilege.ALL;
} else {
privileges = userPrivilegesCache.getIfPresent(user.getUserId());
}
if (privileges == null) {
Vertex userVertex = graph.getVertex(user.getUserId(), authorizations);
privileges = getPrivileges(userVertex);
userPrivilegesCache.put(user.getUserId(), privileges);
}
return privileges;
}
@Override
public void delete(User user) {
Vertex userVertex = findByIdUserVertex(user.getUserId());
graph.removeVertex(userVertex, authorizations);
}
@Override
public void setPrivileges(User user, Set<Privilege> privileges) {
Vertex userVertex = findByIdUserVertex(user.getUserId());
UserLumifyProperties.PRIVILEGES.setProperty(userVertex, Privilege.toString(privileges), VISIBILITY.getVisibility());
graph.flush();
}
private Set<Privilege> getPrivileges(Vertex userVertex) {
return Privilege.stringToPrivileges(UserLumifyProperties.PRIVILEGES.getPropertyValue(userVertex));
}
}
|
package org.cytoscape.task.internal.loaddatatable;
import org.cytoscape.io.read.CyTableReader;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.subnetwork.CyRootNetworkManager;
import org.cytoscape.task.internal.table.MapTableToNetworkTablesTask;
import org.cytoscape.task.internal.table.JoinTablesTask;
import org.cytoscape.task.internal.table.UpdateAddedNetworkAttributes;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.ContainsTunables;
import org.cytoscape.work.ProvidesTitle;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.TunableValidator;
import static org.cytoscape.work.TunableValidator.ValidationState.OK;
public class CombineReaderAndMappingTask extends AbstractTask implements TunableValidator {
@ProvidesTitle
public String getTitle() {
return "Import Column From Table";
}
// @ContainsTunables
// public MapTableToNetworkTablesTask mappingTask;
@ContainsTunables
public JoinTablesTask mergeTablesTask;
@ContainsTunables
public CyTableReader readerTask;
public CombineReaderAndMappingTask(CyTableReader readerTask , CyNetworkManager networkManager, final UpdateAddedNetworkAttributes updateAddedNetworkAttributes, final CyRootNetworkManager rootNetMgr){
this.readerTask = readerTask;
this.mergeTablesTask = new JoinTablesTask(readerTask, rootNetMgr, networkManager);
// this.mappingTask = new MapTableToNetworkTablesTask(networkManager, readerTask, updateAddedNetworkAttributes, rootNetMgr);
}
@Override
public ValidationState getValidationState(Appendable errMsg) {
if ( readerTask instanceof TunableValidator ) {
ValidationState readVS = ((TunableValidator)readerTask).getValidationState(errMsg);
if ( readVS != OK )
return readVS;
}
// If MapTableToNetworkTablesTask implemented TunableValidator, then
// this is what we'd do:
// return mappingTask.getValidationState(errMsg);
return OK;
}
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
readerTask.run(taskMonitor);
this.mergeTablesTask.run(taskMonitor);
// mappingTask.run(taskMonitor);
}
}
|
package db.migration;
import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 29/01/15
*/
public class V1_9_9_010__Association_locus_links_for_single_snp extends CommaSeparatedFieldSplitter
implements SpringJdbcMigration {
private static final String SELECT_SNPS =
"SELECT ID, SNP FROM GWASSNP";
private static final String SELECT_ASSOCIATIONS_AND_SNPS =
"SELECT DISTINCT ID, STRONGEST_ALLELE, SNP " +
"FROM GWASSTUDIESSNP " +
"WHERE SNP NOT LIKE '%,%' " +
"AND SNP NOT LIKE '%:%'";
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
// get all genes
SnpRowHandler snpHandler = new SnpRowHandler();
jdbcTemplate.query(SELECT_SNPS, snpHandler);
final Map<Long, String> snpIdToRsIdMap = snpHandler.getIdToRsIdMap();
final Map<Long, String> snpIdToRiskAlleleMap = new HashMap<>();
// get all associations and link to gene id
final Map<Long, Long> associationIdToSnpId = new HashMap<>();
jdbcTemplate.query(SELECT_ASSOCIATIONS_AND_SNPS, (resultSet, i) -> {
long associationID = resultSet.getLong(1);
Set<String> snps = split(resultSet.getString(3).trim());
Set<String> riskAlleles = split(resultSet.getString(2).trim());
snps.forEach(snp -> {
for (Long snpID : snpIdToRsIdMap.keySet()) {
if (snpIdToRsIdMap.get(snpID).equals(snp)) {
if (!associationIdToSnpId.containsKey(associationID)) {
throw new RuntimeException(
"Can't link association '" + associationID + " to single SNP - " +
"more than one connected rsID (" +
"existing = " + associationIdToSnpId.get(associationID) + ", " +
"new = " + snpID + ")");
}
else {
if (riskAlleles.size() > 1) {
throw new RuntimeException("Single SNP with multiple risk alleles for SNP - " +
snpID + " (risk alleles = " + riskAlleles + ")");
}
else {
associationIdToSnpId.put(associationID, snpID);
snpIdToRiskAlleleMap.put(snpID, riskAlleles.iterator().next());
}
}
}
}
});
return null;
});
SimpleJdbcInsert insertLocus =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("LOCUS")
.usingColumns("HAPLOTYPE_SNP_COUNT", "DESCRIPTION")
.usingGeneratedKeyColumns("ID");
SimpleJdbcInsert insertAssociationLocus =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("ASSOCIATION_LOCUS")
.usingColumns("ASSOCIATION_ID", "LOCUS_ID");
Map<Long, Long> associationIdToLocusIdMap = new HashMap<>();
for (Long associationId : associationIdToSnpId.keySet()) {
// create a single locus and get the locus ID
Map<String, Object> locusArgs = new HashMap<>();
locusArgs.put("HAPLOTYPE_SNP_COUNT", 1);
locusArgs.put("DESCRIPTION", "Single variant");
Number locusId = insertLocus.executeAndReturnKey(locusArgs);
associationIdToLocusIdMap.put(associationId, locusId.longValue());
// now create the ASSOCIATION_LOCUS link
Map<String, Object> associationLocusArgs = new HashMap<>();
associationLocusArgs.put("ASSOCIATION_ID", associationId);
associationLocusArgs.put("LOCUS_ID", locusId);
insertAssociationLocus.execute(associationLocusArgs);
}
SimpleJdbcInsert insertRiskAllele =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("RISK_ALLELE")
.usingColumns("RISK_ALLELE_NAME")
.usingGeneratedKeyColumns("ID");
SimpleJdbcInsert insertRiskAlleleSnp =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("RISK_ALLELE_SNP")
.usingColumns("RISK_ALLELE_ID", "SNP_ID");
Map<Long, Long> snpIdToRiskAlleleIdMap = new HashMap<>();
for (Long snpId : snpIdToRiskAlleleMap.keySet()) {
// create a single risk allele and get the risk allele id
Map<String, Object> riskAlleleArgs = new HashMap<>();
riskAlleleArgs.put("RISK_ALLELE_NAME", snpIdToRiskAlleleMap.get(snpId));
Number riskAlleleId = insertRiskAllele.execute(riskAlleleArgs);
snpIdToRiskAlleleIdMap.put(snpId, riskAlleleId.longValue());
// now create the RISK_ALLELE_SNP link
Map<String, Object> riskAlleleSnpArgs = new HashMap<>();
riskAlleleSnpArgs.put("RISK_ALLELE_ID", riskAlleleId);
riskAlleleSnpArgs.put("SNP_ID", snpId);
insertRiskAlleleSnp.execute(riskAlleleSnpArgs);
}
// finally, create the locus -> risk allele link
SimpleJdbcInsert insertLocusRiskAllele =
new SimpleJdbcInsert(jdbcTemplate)
.withTableName("LOCUS_RISK_ALLELE")
.usingColumns("LOCUS_ID", "RISK_ALLELE_ID");
for (Map.Entry<Long, Long> associationSnpIdPair : associationIdToSnpId.entrySet()) {
Map<String, Object> locusRiskAlleleArgs = new HashMap<>();
locusRiskAlleleArgs.put("LOCUS_ID", associationIdToLocusIdMap.get(associationSnpIdPair.getKey()));
locusRiskAlleleArgs.put("RISK_ALLELE_ID", snpIdToRiskAlleleIdMap.get(associationSnpIdPair.getValue()));
insertLocusRiskAllele.execute(locusRiskAlleleArgs);
}
}
public class SnpRowHandler implements RowCallbackHandler {
private Map<Long, String> idToRsIdMap;
public SnpRowHandler() {
this.idToRsIdMap = new HashMap<>();
}
@Override public void processRow(ResultSet resultSet) throws SQLException {
idToRsIdMap.put(resultSet.getLong(1), resultSet.getString(2).trim());
}
public Map<Long, String> getIdToRsIdMap() {
return idToRsIdMap;
}
}
}
|
package com.peterphi.std.guice.web.rest.service.breaker;
import com.google.inject.ImplementedBy;
import com.peterphi.std.annotation.Doc;
import com.peterphi.std.annotation.ServiceName;
import com.peterphi.std.guice.restclient.annotations.FastFailServiceClient;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
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;
@Path("/guice/breakers")
@FastFailServiceClient
@ServiceName("Breakers")
@Doc("Displays breakers and allows them to be tripped or reset")
@ImplementedBy(GuiceRestBreakerServiceImpl.class)
public interface GuiceRestBreakerService
{
@GET
@Path("/")
@Produces("text/html")
String getIndex(@QueryParam("message") @Doc("for internal use") String message);
@POST
@Path("/set-breaker-state")
@Produces("text/html")
@Doc("Trip or reset a breaker")
Response setState(@FormParam("name") final String name,
@FormParam("value") @DefaultValue("false") final boolean value,
@FormParam("note") String note);
@GET
@Path("/state")
@Produces(MediaType.TEXT_PLAIN)
@Doc("Return CSV of breaker,state")
String getOverview();
@GET
@Path("/breaker/{breaker_name}/test")
@Produces("text/plain")
@Doc("Returns 2xx with body 'OK' if breaker is not tripped, otherwise 503 with body 'Tripped'. If no such breaker then returns code 404. No auth is required for this method.")
Response testBreaker(@PathParam("breaker_name") String breakerName);
@POST
@Path("/set-breaker-state")
@Produces("text/plain")
@Doc("Trip or reset a breaker")
String setTripped(@FormParam("name") final String name,
@FormParam("value") @DefaultValue("false") final boolean value,
@FormParam("note") String note);
}
|
package ca.uhn.fhir.cli;
import ca.uhn.fhir.jpa.migrate.DriverTypeEnum;
import ca.uhn.fhir.jpa.migrate.JdbcUtils;
import com.google.common.base.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.junit.Assert.*;
public class HapiFlywayMigrateDatabaseCommandTest {
private static final Logger ourLog = LoggerFactory.getLogger(HapiFlywayMigrateDatabaseCommandTest.class);
public static final String DB_DIRECTORY = "target/h2_test";
static {
System.setProperty("test", "true");
}
// TODO INTERMITTENT This just failed for me on CI with a BadSqlGrammarException
@Test
public void testMigrateFrom340() throws IOException, SQLException {
File location = getLocation("migrator_h2_test_340_current");
String url = "jdbc:h2:" + location.getAbsolutePath() + ";create=true";
DriverTypeEnum.ConnectionProperties connectionProperties = DriverTypeEnum.H2_EMBEDDED.newConnectionProperties(url, "", "");
String initSql = "/persistence_create_h2_340.sql";
executeSqlStatements(connectionProperties, initSql);
seedDatabase340(connectionProperties);
ourLog.info("**********************************************");
ourLog.info("Done Setup, Starting Migration...");
ourLog.info("**********************************************");
String[] args = new String[]{
BaseFlywayMigrateDatabaseCommand.MIGRATE_DATABASE,
"-d", "H2_EMBEDDED",
"-u", url,
"-n", "",
"-p", ""
};
assertFalse(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RES_REINDEX_JOB"));
App.main(args);
assertTrue(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RES_REINDEX_JOB"));
connectionProperties.getTxTemplate().execute(t -> {
JdbcTemplate jdbcTemplate = connectionProperties.newJdbcTemplate();
List<Map<String, Object>> values = jdbcTemplate.queryForList("SELECT * FROM hfj_spidx_token");
assertEquals(1, values.size());
assertEquals("identifier", values.get(0).get("SP_NAME"));
assertEquals("12345678", values.get(0).get("SP_VALUE"));
assertTrue(values.get(0).keySet().contains("HASH_IDENTITY"));
assertEquals(7001889285610424179L, values.get(0).get("HASH_IDENTITY"));
return null;
});
}
@Test
public void testMigrateFrom340_NoFlyway() throws IOException, SQLException {
File location = getLocation("migrator_h2_test_340_current");
String url = "jdbc:h2:" + location.getAbsolutePath() + ";create=true";
DriverTypeEnum.ConnectionProperties connectionProperties = DriverTypeEnum.H2_EMBEDDED.newConnectionProperties(url, "", "");
String initSql = "/persistence_create_h2_340.sql";
executeSqlStatements(connectionProperties, initSql);
seedDatabase340(connectionProperties);
ourLog.info("**********************************************");
ourLog.info("Done Setup, Starting Migration...");
ourLog.info("**********************************************");
String[] args = new String[]{
BaseFlywayMigrateDatabaseCommand.MIGRATE_DATABASE,
"-d", "H2_EMBEDDED",
"-u", url,
"-n", "",
"-p", "",
"--" + BaseFlywayMigrateDatabaseCommand.DONT_USE_FLYWAY
};
assertFalse(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RES_REINDEX_JOB"));
App.main(args);
assertTrue(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RES_REINDEX_JOB"));
connectionProperties.getTxTemplate().execute(t -> {
JdbcTemplate jdbcTemplate = connectionProperties.newJdbcTemplate();
List<Map<String, Object>> values = jdbcTemplate.queryForList("SELECT * FROM hfj_spidx_token");
assertEquals(1, values.size());
assertEquals("identifier", values.get(0).get("SP_NAME"));
assertEquals("12345678", values.get(0).get("SP_VALUE"));
assertTrue(values.get(0).keySet().contains("HASH_IDENTITY"));
assertEquals(7001889285610424179L, values.get(0).get("HASH_IDENTITY"));
return null;
});
}
@Test
public void testMigrateFromEmptySchema() throws IOException, SQLException {
File location = getLocation("migrator_h2_test_empty_current");
String url = "jdbc:h2:" + location.getAbsolutePath() + ";create=true";
DriverTypeEnum.ConnectionProperties connectionProperties = DriverTypeEnum.H2_EMBEDDED.newConnectionProperties(url, "", "");
ourLog.info("**********************************************");
ourLog.info("Starting Migration...");
ourLog.info("**********************************************");
String[] args = new String[]{
BaseFlywayMigrateDatabaseCommand.MIGRATE_DATABASE,
"-d", "H2_EMBEDDED",
"-u", url,
"-n", "",
"-p", ""
};
assertFalse(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RESOURCE"));
assertFalse(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_BLK_EXPORT_JOB"));
App.main(args);
assertTrue(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_RESOURCE")); // Early table
assertTrue(JdbcUtils.getTableNames(connectionProperties).contains("HFJ_BLK_EXPORT_JOB")); // Late table
}
@NotNull
private File getLocation(String theDatabaseName) throws IOException {
File directory = new File(DB_DIRECTORY);
if (directory.exists()) {
FileUtils.deleteDirectory(directory);
}
return new File(DB_DIRECTORY + "/" + theDatabaseName);
}
private void seedDatabase340(DriverTypeEnum.ConnectionProperties theConnectionProperties) {
theConnectionProperties.getTxTemplate().execute(t -> {
JdbcTemplate jdbcTemplate = theConnectionProperties.newJdbcTemplate();
jdbcTemplate.execute(
"insert into HFJ_RESOURCE (RES_DELETED_AT, RES_VERSION, FORCED_ID_PID, HAS_TAGS, RES_PUBLISHED, RES_UPDATED, SP_HAS_LINKS, HASH_SHA256, SP_INDEX_STATUS, RES_LANGUAGE, SP_CMPSTR_UNIQ_PRESENT, SP_COORDS_PRESENT, SP_DATE_PRESENT, SP_NUMBER_PRESENT, SP_QUANTITY_PRESENT, SP_STRING_PRESENT, SP_TOKEN_PRESENT, SP_URI_PRESENT, RES_PROFILE, RES_TYPE, RES_VER, RES_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
@Override
protected void setValues(PreparedStatement thePs, LobCreator theLobCreator) throws SQLException {
thePs.setNull(1, Types.TIMESTAMP);
thePs.setString(2, "R4");
thePs.setNull(3, Types.BIGINT);
thePs.setBoolean(4, false);
thePs.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
thePs.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
thePs.setBoolean(7, false);
thePs.setNull(8, Types.VARCHAR);
thePs.setLong(9, 1L);
thePs.setNull(10, Types.VARCHAR);
thePs.setBoolean(11, false);
thePs.setBoolean(12, false);
thePs.setBoolean(13, false);
thePs.setBoolean(14, false);
thePs.setBoolean(15, false);
thePs.setBoolean(16, false);
thePs.setBoolean(17, false);
thePs.setBoolean(18, false);
thePs.setNull(19, Types.VARCHAR);
thePs.setString(20, "Patient");
thePs.setLong(21, 1L);
thePs.setLong(22, 1L);
}
}
);
jdbcTemplate.execute(
"insert into HFJ_RES_VER (RES_DELETED_AT, RES_VERSION, FORCED_ID_PID, HAS_TAGS, RES_PUBLISHED, RES_UPDATED, RES_ENCODING, RES_TEXT, RES_ID, RES_TYPE, RES_VER, PID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
@Override
protected void setValues(PreparedStatement thePs, LobCreator theLobCreator) throws SQLException {
thePs.setNull(1, Types.TIMESTAMP);
thePs.setString(2, "R4");
thePs.setNull(3, Types.BIGINT);
thePs.setBoolean(4, false);
thePs.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
thePs.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
thePs.setString(7, "JSON");
theLobCreator.setBlobAsBytes(thePs, 8, "{\"resourceType\":\"Patient\"}".getBytes(Charsets.US_ASCII));
thePs.setLong(9, 1L);
thePs.setString(10, "Patient");
thePs.setLong(11, 1L);
thePs.setLong(12, 1L);
}
}
);
jdbcTemplate.execute(
"insert into HFJ_SPIDX_STRING (SP_MISSING, SP_NAME, RES_ID, RES_TYPE, SP_UPDATED, SP_VALUE_EXACT, SP_VALUE_NORMALIZED, SP_ID) values (?, ?, ?, ?, ?, ?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
@Override
protected void setValues(PreparedStatement thePs, LobCreator theLobCreator) throws SQLException {
thePs.setBoolean(1, false);
thePs.setString(2, "given");
thePs.setLong(3, 1L); // res-id
thePs.setString(4, "Patient");
thePs.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
thePs.setString(6, "ROBERT");
thePs.setString(7, "Robert");
thePs.setLong(8, 1L);
}
}
);
jdbcTemplate.execute(
"insert into HFJ_SPIDX_TOKEN (SP_MISSING, SP_NAME, RES_ID, RES_TYPE, SP_UPDATED, SP_SYSTEM, SP_VALUE, SP_ID) values (?, ?, ?, ?, ?, ?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
@Override
protected void setValues(PreparedStatement thePs, LobCreator theLobCreator) throws SQLException {
thePs.setBoolean(1, false);
thePs.setString(2, "identifier");
thePs.setLong(3, 1L); // res-id
thePs.setString(4, "Patient");
thePs.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
thePs.setString(6, "http://foo");
thePs.setString(7, "12345678");
thePs.setLong(8, 1L);
}
}
);
jdbcTemplate.execute(
"insert into HFJ_SPIDX_DATE (SP_MISSING, SP_NAME, RES_ID, RES_TYPE, SP_UPDATED, SP_VALUE_HIGH, SP_VALUE_LOW, SP_ID) values (?, ?, ?, ?, ?, ?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
@Override
protected void setValues(PreparedStatement thePs, LobCreator theLobCreator) throws SQLException {
thePs.setBoolean(1, false);
thePs.setString(2, "birthdate");
thePs.setLong(3, 1L); // res-id
thePs.setString(4, "Patient");
thePs.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
thePs.setTimestamp(6, new Timestamp(1000000000L)); // value high
thePs.setTimestamp(7, new Timestamp(1000000000L)); // value low
thePs.setLong(8, 1L);
}
}
);
return null;
});
}
private void executeSqlStatements(DriverTypeEnum.ConnectionProperties theConnectionProperties, String theInitSql) throws
IOException {
String script = IOUtils.toString(HapiFlywayMigrateDatabaseCommandTest.class.getResourceAsStream(theInitSql), Charsets.UTF_8);
List<String> scriptStatements = new ArrayList<>(Arrays.asList(script.split("\n")));
for (int i = 0; i < scriptStatements.size(); i++) {
String nextStatement = scriptStatements.get(i);
if (isBlank(nextStatement)) {
scriptStatements.remove(i);
i
continue;
}
nextStatement = nextStatement.trim();
while (nextStatement.endsWith(";")) {
nextStatement = nextStatement.substring(0, nextStatement.length() - 1);
}
scriptStatements.set(i, nextStatement);
}
theConnectionProperties.getTxTemplate().execute(t -> {
for (String next : scriptStatements) {
theConnectionProperties.newJdbcTemplate().execute(next);
}
return null;
});
}
}
|
package animesearch.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.sun.org.apache.bcel.internal.generic.ANEWARRAY;
import animesearch.exception.DatabaseLoginFailedException;
import animesearch.model.AnimeInfo;
import animesearch.model.DatabaseManager;
import animesearch.model.SearchFilter;
import animesearch.view.AnimeFilter;
import animesearch.view.MainView;
import animesearch.view.TwoStateButton;
public class ProgramController {
private DatabaseManager modelManager;
private MainView mainView;
private static AnimeFilter animeFilterView = null;
private ArrayList<AnimeInfo> arrayResultSearch;
public ProgramController() throws DatabaseLoginFailedException {
// Instantiate properties
modelManager = new DatabaseManager();
modelManager.connect("postgres", "123456789"); // Change this depend on
// servers
modelManager.getSearchFilter();
if (animeFilterView == null) {
animeFilterView = new AnimeFilter();
animeFilterView.setVisible(false);
}
mainView = new MainView();
mainView.setVisible(true);
// Implementation
addTextFieldListener();
addFilterButtonListener();
showInfo();
}
private void showInfo() {
// TODO Auto-generated method stub
mainView.setResultListListener(new MouseListener() {
@Override
public void mouseReleased(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
// Action goes here
AnimeInfo animeInfo = arrayResultSearch.get(mainView.getSelectedAnimeIndex());
mainView.setInformation(animeInfo);
animeInfo.setCharacters(modelManager.getAnimeCharacters(animeInfo.getId()));
mainView.setListOfCharacter(animeInfo);
}
});
}
private void addFilterButtonListener() {
// TODO Auto-generated method stub
mainView.addFilterButtonActionListerner(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
private void addTextFieldListener() {
mainView.addSearchTextFieldListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (mainView.getTextInSearchTextField().length() < 3) {
JOptionPane.showMessageDialog(mainView, "In order to provide the best precise result, input search string must contain 3 or more characters");
} else {
if(mainView.getStateOfToggleButton() == TwoStateButton.ANIME_MODE ){
String text = mainView.getTextInSearchTextField();
arrayResultSearch = modelManager.searchAnimeByName(text);
mainView.setListOfResult(arrayResultSearch);
}else{
String text = mainView.getTextInSearchTextField();
arrayResultSearch = modelManager.searchAnimeByCharacter(text);
mainView.setListOfResult(arrayResultSearch);
}
}
}
});
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
ProgramController programController = new ProgramController();
} catch (DatabaseLoginFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.highcharts.export.util;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
public enum MimeType {
PNG("image/png", "png"),
JPEG("image/jpeg", "jpeg"),
PDF("application/pdf", "pdf"),
SVG("image/svg+xml", "svg");
private static final Map<String, MimeType> lookup = new HashMap<>();
static {
for (MimeType m : EnumSet.allOf(MimeType.class)) {
lookup.put(m.getType(), m);
}
}
private String type;
private String extension;
private MimeType(String type, String extension) {
this.type = type;
this.extension = extension;
}
public String getType() {
return type;
}
public String getExtension() {
return extension;
}
public static MimeType get(String type) {
MimeType mime = lookup.get(type);
if (mime != null) {
return mime;
}
return MimeType.PNG;
}
}
|
package com.atlassian.jira.plugins.dvcs.dao.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.java.ao.EntityStreamCallback;
import net.java.ao.Query;
import net.java.ao.RawEntity;
import net.java.ao.schema.PrimaryKey;
import net.java.ao.schema.Table;
import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.jira.plugins.dvcs.activeobjects.ActiveObjectsUtils;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.ChangesetMapping;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.IssueToChangesetMapping;
import com.atlassian.jira.plugins.dvcs.activeobjects.v3.RepositoryToChangesetMapping;
import com.atlassian.jira.plugins.dvcs.dao.ChangesetDao;
import com.atlassian.jira.plugins.dvcs.dao.impl.transform.ChangesetTransformer;
import com.atlassian.jira.plugins.dvcs.model.Changeset;
import com.atlassian.jira.plugins.dvcs.model.ChangesetFile;
import com.atlassian.jira.plugins.dvcs.model.GlobalFilter;
import com.atlassian.jira.util.json.JSONArray;
import com.atlassian.jira.util.json.JSONException;
import com.atlassian.jira.util.json.JSONObject;
import com.atlassian.sal.api.transaction.TransactionCallback;
public class ChangesetDaoImpl implements ChangesetDao
{
private static final Logger log = LoggerFactory.getLogger(ChangesetDaoImpl.class);
private final ActiveObjects activeObjects;
private final ChangesetTransformer transformer = new ChangesetTransformer();
public ChangesetDaoImpl(ActiveObjects activeObjects)
{
this.activeObjects = activeObjects;
}
private List<Changeset> transform(ChangesetMapping changesetMapping)
{
return transformer.transform(changesetMapping);
}
private List<Changeset> transform(List<ChangesetMapping> changesetMappings)
{
List<Changeset> changesets = new ArrayList<Changeset>();
for (ChangesetMapping changesetMapping : changesetMappings)
{
changesets.addAll(transform(changesetMapping));
}
return changesets;
}
@Override
public void removeAllInRepository(final int repositoryId)
{
activeObjects.executeInTransaction(new TransactionCallback<Object>()
{
@Override
public Object doInTransaction()
{
// todo: transaction: plugin use SalTransactionManager and there is empty implementation of TransactionSynchronisationManager.
// todo: Therefore there are only entityCache transactions. No DB transactions.
// delete association repo - changesets
Query query = Query.select().where(RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId);
log.debug("deleting repo - changesets associations from RepoToChangeset with id = [ {} ]", new String[]{String.valueOf(repositoryId)});
ActiveObjectsUtils.delete(activeObjects, RepositoryToChangesetMapping.class, query);
// delete association issues - changeset
query = Query.select().where(
IssueToChangesetMapping.CHANGESET_ID + " not in " +
"(select \"" + RepositoryToChangesetMapping.CHANGESET_ID + "\" from \"" + RepositoryToChangesetMapping.TABLE_NAME + "\")");
log.debug("deleting orphaned issue-changeset associations");
ActiveObjectsUtils.delete(activeObjects, IssueToChangesetMapping.class, query);
// delete orphaned changesets
query = Query.select().where(
"ID not in " +
"(select \"" + RepositoryToChangesetMapping.CHANGESET_ID + "\" from \"" + RepositoryToChangesetMapping.TABLE_NAME + "\")");
log.debug("deleting orphaned changesets");
ActiveObjectsUtils.delete(activeObjects, ChangesetMapping.class, query);
return null;
}
});
}
@Override
public Changeset create(final Changeset changeset, final Set<String> extractedIssues)
{
ChangesetMapping changesetMapping = activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
ChangesetMapping chm = getChangesetMapping(changeset);
if (chm == null)
{
chm = activeObjects.create(ChangesetMapping.class);
fillProperties(changeset, chm);
chm.save();
}
associateRepositoryToChangeset(chm, changeset.getRepositoryId());
if (extractedIssues != null)
{
associateIssuesToChangeset(chm, extractedIssues);
}
return chm;
}
});
changeset.setId(changesetMapping.getID());
return changeset;
}
@Override
public Changeset update(final Changeset changeset)
{
activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
ChangesetMapping chm = getChangesetMapping(changeset);
if (chm != null)
{
fillProperties(changeset, chm);
chm.save();
} else
{
log.warn("Changest with node {} is not exists.", changeset.getNode());
}
return chm;
}
});
return changeset;
}
private ChangesetMapping getChangesetMapping(Changeset changeset)
{
// A Query is little bit more complicated, but:
// 1. previous implementation did not properly fill RAW_NODE, in some cases it is null, in some other cases it is empty string
String hasRawNode = "( " + ChangesetMapping.RAW_NODE + " is not null AND " + ChangesetMapping.RAW_NODE + " != '') ";
// 2. Latest implementation is using full RAW_NODE, but not all records contains it!
String matchRawNode = ChangesetMapping.RAW_NODE + " = ? ";
// 3. Previous implementation has used NODE, but it is mix in some cases it is short version, in some cases it is full version
String matchNode = ChangesetMapping.NODE + " like ? ";
String shortNode = changeset.getNode().substring(0, 13) + "%";
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, "(" + hasRawNode + " AND " + matchRawNode + " ) OR ( NOT "
+ hasRawNode + " AND " + matchNode + " ) ", changeset.getRawNode(), shortNode);
if (mappings.length > 1)
{
log.warn("More changesets with same Node. Same changesets count: {}, Node: {}, Repository: {}", new Object[] { mappings.length,
changeset.getNode(), changeset.getRepositoryId() });
}
return (ArrayUtils.isNotEmpty(mappings)) ? mappings[0] : null;
}
public void fillProperties(Changeset changeset, ChangesetMapping chm)
{
// we need to remove null characters '\u0000' because PostgreSQL cannot store String values with such
// characters
// todo: remove NULL Chars before call setters
chm.setNode(changeset.getNode());
chm.setRawAuthor(changeset.getRawAuthor());
chm.setAuthor(changeset.getAuthor());
chm.setDate(changeset.getDate());
chm.setRawNode(changeset.getRawNode());
chm.setBranch(changeset.getBranch());
chm.setMessage(changeset.getMessage());
chm.setAuthorEmail(changeset.getAuthorEmail());
chm.setSmartcommitAvailable(changeset.isSmartcommitAvaliable());
JSONArray parentsJson = new JSONArray();
for (String parent : changeset.getParents())
{
parentsJson.put(parent);
}
String parentsData = parentsJson.toString();
if (parentsData.length() > 255)
{
parentsData = ChangesetMapping.TOO_MANY_PARENTS;
}
chm.setParentsData(parentsData);
JSONObject filesDataJson = new JSONObject();
JSONArray filesJson = new JSONArray();
try
{
List<ChangesetFile> files = changeset.getFiles();
int count = changeset.getAllFileCount();
filesDataJson.put("count", count);
for (int i = 0; i < Math.min(count, Changeset.MAX_VISIBLE_FILES); i++)
{
ChangesetFile changesetFile = files.get(i);
JSONObject fileJson = new JSONObject();
fileJson.put("filename", changesetFile.getFile());
fileJson.put("status", changesetFile.getFileAction().getAction());
fileJson.put("additions", changesetFile.getAdditions());
fileJson.put("deletions", changesetFile.getDeletions());
filesJson.put(fileJson);
}
filesDataJson.put("files", filesJson);
chm.setFilesData(filesDataJson.toString());
} catch (JSONException e)
{
log.error("Creating files JSON failed!", e);
}
chm.setVersion(ChangesetMapping.LATEST_VERSION);
chm.save();
}
private Changeset filterByRepository(List<Changeset> changesets, int repositoryId)
{
for (Changeset changeset : changesets)
{
if (changeset.getRepositoryId() == repositoryId)
{
return changeset;
}
}
return null;
}
private void associateIssuesToChangeset(ChangesetMapping changesetMapping, Set<String> extractedIssues)
{
// remove all assoc issues-changeset
Query query = Query.select().where(IssueToChangesetMapping.CHANGESET_ID + " = ? ", changesetMapping);
ActiveObjectsUtils.delete(activeObjects, IssueToChangesetMapping.class, query);
// insert all
for (String extractedIssue : extractedIssues)
{
final Map<String, Object> map = new MapRemovingNullCharacterFromStringValues();
map.put(IssueToChangesetMapping.ISSUE_KEY, extractedIssue);
map.put(IssueToChangesetMapping.PROJECT_KEY, parseProjectKey(extractedIssue));
map.put(IssueToChangesetMapping.CHANGESET_ID, changesetMapping.getID());
activeObjects.create(IssueToChangesetMapping.class, map);
}
}
private void associateRepositoryToChangeset(ChangesetMapping changesetMapping, int repositoryId)
{
RepositoryToChangesetMapping[] mappings = activeObjects.find(RepositoryToChangesetMapping.class,
RepositoryToChangesetMapping.REPOSITORY_ID + " = ? and " +
RepositoryToChangesetMapping.CHANGESET_ID + " = ? ",
repositoryId,
changesetMapping);
if (ArrayUtils.isEmpty(mappings))
{
final Map<String, Object> map = new MapRemovingNullCharacterFromStringValues();
map.put(RepositoryToChangesetMapping.REPOSITORY_ID, repositoryId);
map.put(RepositoryToChangesetMapping.CHANGESET_ID, changesetMapping);
activeObjects.create(RepositoryToChangesetMapping.class, map);
}
}
public static String parseProjectKey(String issueKey)
{
return issueKey.substring(0, issueKey.indexOf("-"));
}
@Override
public Changeset getByNode(final int repositoryId, final String changesetNode)
{
final ChangesetMapping changesetMapping = activeObjects.executeInTransaction(new TransactionCallback<ChangesetMapping>()
{
@Override
public ChangesetMapping doInTransaction()
{
Query query = Query.select()
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("chm." + ChangesetMapping.NODE + " = ? AND rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ? ", changesetNode, repositoryId);
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, query);
return mappings.length != 0 ? mappings[0] : null;
}
});
final List<Changeset> changesets = transform(changesetMapping);
return changesets != null ? filterByRepository(changesets, repositoryId) : null;
}
@Override
public List<Changeset> getByIssueKey(final String issueKey)
{
final List<ChangesetMapping> changesetMappings = activeObjects.executeInTransaction(new TransactionCallback<List<ChangesetMapping>>()
{
@Override
public List<ChangesetMapping> doInTransaction()
{
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class,
Query.select()
.alias(ChangesetMapping.class, "chm")
.alias(IssueToChangesetMapping.class, "itchm")
.join(IssueToChangesetMapping.class, "chm.ID = itchm." + IssueToChangesetMapping.CHANGESET_ID)
.where("itchm." + IssueToChangesetMapping.ISSUE_KEY + " = ?", issueKey)
.order(ChangesetMapping.DATE));
return Arrays.asList(mappings);
}
});
return transform(changesetMappings);
}
@Override
public List<Changeset> getLatestChangesets(final int maxResults, final GlobalFilter gf)
{
if (maxResults <= 0)
{
return Collections.emptyList();
}
final List<ChangesetMapping> changesetMappings = activeObjects.executeInTransaction(new TransactionCallback<List<ChangesetMapping>>()
{
@Override
public List<ChangesetMapping> doInTransaction()
{
String baseWhereClause = new GlobalFilterQueryWhereClauseBuilder(gf).build();
Query query = Query.select()
.alias(ChangesetMapping.class, "CHANGESET")
.alias(IssueToChangesetMapping.class, "ISSUE")
.join(IssueToChangesetMapping.class, "CHANGESET.ID = ISSUE." + IssueToChangesetMapping.CHANGESET_ID)
.where(baseWhereClause).limit(maxResults).order(ChangesetMapping.DATE + " DESC");
ChangesetMapping[] mappings = activeObjects.find(ChangesetMapping.class, query);
return Arrays.asList(mappings);
}
});
return transform(changesetMappings);
}
@Override
public void forEachLatestChangesetsAvailableForSmartcommitDo(final int repositoryId, final ForEachChangesetClosure closure)
{
Query query = createLatestChangesetsAvailableForSmartcommitQuery(repositoryId);
activeObjects.stream(ChangesetMapping.class, query, new EntityStreamCallback<ChangesetMapping, Integer>()
{
@Override
public void onRowRead(ChangesetMapping mapping)
{
closure.execute(mapping);
}
});
}
private Query createLatestChangesetsAvailableForSmartcommitQuery(int repositoryId)
{
return Query.select("*")
.from(ChangesetMapping.class)
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ? and chm."+ChangesetMapping.SMARTCOMMIT_AVAILABLE+" = ? " , repositoryId, Boolean.TRUE)
.order(ChangesetMapping.DATE + " DESC");
}
@Override
public Set<String> findReferencedProjects(int repositoryId)
{
Query query = Query.select(IssueToChangesetMapping.PROJECT_KEY).distinct()
.alias(ProjectKey.class, "pk")
.alias(ChangesetMapping.class, "chm")
.alias(RepositoryToChangesetMapping.class, "rtchm")
.join(ChangesetMapping.class, "chm.ID = pk." + IssueToChangesetMapping.CHANGESET_ID)
.join(RepositoryToChangesetMapping.class, "chm.ID = rtchm." + RepositoryToChangesetMapping.CHANGESET_ID)
.where("rtchm." + RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId)
.order(IssueToChangesetMapping.PROJECT_KEY);
final Set<String> projectKeys = new HashSet<String>();
activeObjects.stream(ProjectKey.class, query, new EntityStreamCallback<ProjectKey, String>()
{
@Override
public void onRowRead(ProjectKey mapping)
{
projectKeys.add(mapping.getProjectKey());
}
});
return projectKeys;
}
@Table("IssueToChangeset")
static interface ProjectKey extends RawEntity<String>
{
@PrimaryKey(IssueToChangesetMapping.PROJECT_KEY)
String getProjectKey();
void setProjectKey();
}
@Override
public void markSmartcommitAvailability(int id, boolean available)
{
final ChangesetMapping changesetMapping = activeObjects.get(ChangesetMapping.class, id);
changesetMapping.setSmartcommitAvailable(available);
activeObjects.executeInTransaction(new TransactionCallback<Void>()
{
@Override
public Void doInTransaction()
{
changesetMapping.save();
return null;
}
});
}
@Override
public int getChangesetCount(final int repositoryId)
{
return activeObjects.executeInTransaction(new TransactionCallback<Integer>()
{
@Override
public Integer doInTransaction()
{
Query query = Query.select().where(RepositoryToChangesetMapping.REPOSITORY_ID + " = ?", repositoryId);
return activeObjects.count(RepositoryToChangesetMapping.class, query);
}
});
}
}
|
package org.jboss.forge.addon.maven.archetype;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jboss.forge.addon.configuration.Configuration;
import org.jboss.forge.addon.configuration.Subset;
import org.jboss.forge.furnace.services.Imported;
import org.jboss.forge.furnace.util.Assert;
/**
* Default implementation for {@link ArchetypeCatalogFactoryRegistry}
*
* @author <a href="ggastald@redhat.com">George Gastaldi</a>
*/
@Singleton
public class ArchetypeCatalogFactoryRegistryImpl implements ArchetypeCatalogFactoryRegistry
{
private Map<String, ArchetypeCatalogFactory> factories = new TreeMap<>();
private final Logger log = Logger.getLogger(getClass().getName());
@Inject
private Imported<ArchetypeCatalogFactory> services;
@Inject
@Subset("maven.archetypes")
private Configuration archetypeConfiguration;
/**
* Registers the {@link ArchetypeCatalogFactory} objects from the user {@link Configuration}
*/
@PostConstruct
void initializeDefaultFactories()
{
Iterator<?> keys = archetypeConfiguration.getKeys();
while (keys.hasNext())
{
String name = keys.next().toString();
if (!name.isEmpty())
{
String url = archetypeConfiguration.getString(name);
try
{
addArchetypeCatalogFactory(name, new URL(url));
}
catch (MalformedURLException e)
{
log.log(Level.SEVERE, "Malformed URL for " + name, e);
}
}
}
}
@PreDestroy
void destroy()
{
this.factories.clear();
}
@Override
public void addArchetypeCatalogFactory(String name, URL catalogURL)
{
addArchetypeCatalogFactory(new URLArchetypeCatalogFactory(name, catalogURL));
}
@Override
public void addArchetypeCatalogFactory(String name, URL catalogURL, String defaultRepositoryName)
{
addArchetypeCatalogFactory(new URLArchetypeCatalogFactory(name, catalogURL, defaultRepositoryName));
}
@Override
public void addArchetypeCatalogFactory(ArchetypeCatalogFactory factory)
{
Assert.notNull(factory, "Cannot add a null Archetype Catalog Factory");
Assert.notNull(factory.getName(), "Archetype Catalog Factory must have a name");
factories.put(factory.getName(), factory);
}
@Override
public Iterable<ArchetypeCatalogFactory> getArchetypeCatalogFactories()
{
Map<String, ArchetypeCatalogFactory> result = new TreeMap<>();
for (ArchetypeCatalogFactory factory : services)
{
result.put(factory.getName(), factory);
}
result.putAll(factories);
return Collections.unmodifiableCollection(result.values());
}
@Override
public ArchetypeCatalogFactory getArchetypeCatalogFactory(String name)
{
ArchetypeCatalogFactory result = null;
if (name != null)
{
for (ArchetypeCatalogFactory factory : getArchetypeCatalogFactories())
{
if (name.equals(factory.getName()))
return factory;
}
}
return result;
}
@Override
public void removeArchetypeCatalogFactory(String name)
{
factories.remove(name);
}
@Override
public boolean hasArchetypeCatalogFactories()
{
return factories.size() > 0 || !services.isUnsatisfied();
}
}
|
package org.wildfly.extension.messaging.activemq;
import static org.jboss.as.controller.SimpleAttributeDefinitionBuilder.create;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.BYTES;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.DAYS;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.MILLISECONDS;
import static org.jboss.as.controller.client.helpers.MeasurementUnit.SECONDS;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.DEAD_LETTER_ADDRESS;
import static org.wildfly.extension.messaging.activemq.CommonAttributes.EXPIRY_ADDRESS;
import java.util.Arrays;
import java.util.Collection;
import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.settings.impl.SlowConsumerPolicy;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.PersistentResourceDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public class AddressSettingDefinition extends PersistentResourceDefinition {
public static final SimpleAttributeDefinition AUTO_CREATE_JMS_QUEUES = create("auto-create-jms-queues", ModelType.BOOLEAN)
// Default value is false to have the same behaviour than the legacy messaging subsystem (Artemis defaults to true)
.setDefaultValue(new ModelNode(false))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition AUTO_DELETE_JMS_QUEUES = create("auto-delete-jms-queues", ModelType.BOOLEAN)
// Default value is false to have the same behaviour than the legacy messaging subsystem (Artemis defaults to true)
.setDefaultValue(new ModelNode(false))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition ADDRESS_FULL_MESSAGE_POLICY = create("address-full-policy", ModelType.STRING)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_ADDRESS_FULL_MESSAGE_POLICY.toString()))
.setValidator(new EnumValidator<>(AddressFullMessagePolicy.class, true, false))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition EXPIRY_DELAY = create("expiry-delay", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_EXPIRY_DELAY))
.setMeasurementUnit(MILLISECONDS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition LAST_VALUE_QUEUE = create("last-value-queue", ModelType.BOOLEAN)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_LAST_VALUE_QUEUE))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition MAX_DELIVERY_ATTEMPTS = create("max-delivery-attempts", ModelType.INT)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition MAX_REDELIVERY_DELAY = create("max-redelivery-delay", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_REDELIVER_DELAY * 10))
.setMeasurementUnit(MILLISECONDS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition MAX_SIZE_BYTES = create("max-size-bytes", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_MAX_SIZE_BYTES))
.setMeasurementUnit(BYTES)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition MESSAGE_COUNTER_HISTORY_DAY_LIMIT = create("message-counter-history-day-limit", ModelType.INT)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT))
.setMeasurementUnit(DAYS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition PAGE_MAX_CACHE_SIZE = create("page-max-cache-size", ModelType.INT)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_PAGE_MAX_CACHE))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition PAGE_SIZE_BYTES = create("page-size-bytes", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_PAGE_SIZE))
.setMeasurementUnit(BYTES)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition REDELIVERY_DELAY = create("redelivery-delay", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_REDELIVER_DELAY))
.setMeasurementUnit(MILLISECONDS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition REDELIVERY_MULTIPLIER = create("redelivery-multiplier", ModelType.DOUBLE)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_REDELIVER_MULTIPLIER))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition REDISTRIBUTION_DELAY = create("redistribution-delay", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_REDISTRIBUTION_DELAY))
.setMeasurementUnit(MILLISECONDS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition SEND_TO_DLA_ON_NO_ROUTE = create("send-to-dla-on-no-route", ModelType.BOOLEAN)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_SEND_TO_DLA_ON_NO_ROUTE))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition SLOW_CONSUMER_CHECK_PERIOD = create("slow-consumer-check-period", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_SLOW_CONSUMER_CHECK_PERIOD))
.setMeasurementUnit(SECONDS)
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition SLOW_CONSUMER_POLICY = create("slow-consumer-policy", ModelType.STRING)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_SLOW_CONSUMER_POLICY.toString()))
.setValidator(new EnumValidator<>(SlowConsumerPolicy.class, true, true))
.setAllowNull(true)
.setAllowExpression(true)
.build();
public static final SimpleAttributeDefinition SLOW_CONSUMER_THRESHOLD = create("slow-consumer-threshold", ModelType.LONG)
.setDefaultValue(new ModelNode(AddressSettings.DEFAULT_SLOW_CONSUMER_THRESHOLD))
.setAllowNull(true)
.setAllowExpression(true)
.build();
/**
* Attributes are defined in the <em>same order than in the XSD schema</em>
*/
static final AttributeDefinition[] ATTRIBUTES = new SimpleAttributeDefinition[] {
DEAD_LETTER_ADDRESS,
EXPIRY_ADDRESS,
EXPIRY_DELAY,
REDELIVERY_DELAY,
REDELIVERY_MULTIPLIER,
MAX_DELIVERY_ATTEMPTS,
MAX_REDELIVERY_DELAY,
MAX_SIZE_BYTES,
PAGE_SIZE_BYTES,
PAGE_MAX_CACHE_SIZE,
ADDRESS_FULL_MESSAGE_POLICY,
MESSAGE_COUNTER_HISTORY_DAY_LIMIT,
LAST_VALUE_QUEUE,
REDISTRIBUTION_DELAY,
SEND_TO_DLA_ON_NO_ROUTE,
SLOW_CONSUMER_CHECK_PERIOD,
SLOW_CONSUMER_POLICY,
SLOW_CONSUMER_THRESHOLD,
AUTO_CREATE_JMS_QUEUES,
AUTO_DELETE_JMS_QUEUES
};
static final AddressSettingDefinition INSTANCE = new AddressSettingDefinition();
private AddressSettingDefinition() {
super(MessagingExtension.ADDRESS_SETTING_PATH,
MessagingExtension.getResourceDescriptionResolver(CommonAttributes.ADDRESS_SETTING),
AddressSettingAdd.INSTANCE,
AddressSettingRemove.INSTANCE);
}
@Override
public void registerAttributes(ManagementResourceRegistration registry) {
for (AttributeDefinition attr : ATTRIBUTES) {
if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) {
registry.registerReadWriteAttribute(attr, null, AddressSettingsWriteHandler.INSTANCE);
}
}
}
@Override
public Collection<AttributeDefinition> getAttributes() {
return Arrays.asList(ATTRIBUTES);
}
}
|
package org.motechproject.commcare.service.impl;
import org.motechproject.commcare.domain.CommcareForm;
import org.motechproject.commcare.parser.FormAdapter;
import org.motechproject.commcare.service.CommcareFormService;
import org.motechproject.commcare.util.CommCareAPIHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.gson.JsonParseException;
@Service
public class CommcareFormServiceImpl implements CommcareFormService {
private CommCareAPIHttpClient commcareHttpClient;
@Autowired
public CommcareFormServiceImpl(CommCareAPIHttpClient commcareHttpClient) {
this.commcareHttpClient = commcareHttpClient;
}
@Override
public CommcareForm retrieveForm(String id) {
String returnJson = commcareHttpClient.formRequest(id);
try {
return FormAdapter.readJson(returnJson);
} catch (JsonParseException e) {
return null;
}
}
@Override
public String retrieveFormJson(String id) {
return commcareHttpClient.formRequest(id);
}
}
|
package org.opendaylight.netvirt.natservice.internal;
import static org.opendaylight.controller.md.sal.binding.api.WriteTransaction.CREATE_MISSING_PARENTS;
import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
import static org.opendaylight.netvirt.natservice.internal.NatUtil.requireNonNullElse;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.math.BigInteger;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
import org.opendaylight.genius.infra.Datastore.Configuration;
import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
import org.opendaylight.genius.infra.TypedReadWriteTransaction;
import org.opendaylight.genius.infra.TypedWriteTransaction;
import org.opendaylight.genius.interfacemanager.interfaces.IInterfaceManager;
import org.opendaylight.genius.mdsalutil.ActionInfo;
import org.opendaylight.genius.mdsalutil.BucketInfo;
import org.opendaylight.genius.mdsalutil.FlowEntity;
import org.opendaylight.genius.mdsalutil.GroupEntity;
import org.opendaylight.genius.mdsalutil.InstructionInfo;
import org.opendaylight.genius.mdsalutil.MDSALUtil;
import org.opendaylight.genius.mdsalutil.MatchInfo;
import org.opendaylight.genius.mdsalutil.MetaDataUtil;
import org.opendaylight.genius.mdsalutil.NwConstants;
import org.opendaylight.genius.mdsalutil.NwConstants.NxmOfFieldType;
import org.opendaylight.genius.mdsalutil.actions.ActionDrop;
import org.opendaylight.genius.mdsalutil.actions.ActionGroup;
import org.opendaylight.genius.mdsalutil.actions.ActionLearn;
import org.opendaylight.genius.mdsalutil.actions.ActionLearn.MatchFromField;
import org.opendaylight.genius.mdsalutil.actions.ActionLearn.MatchFromValue;
import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadInPort;
import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
import org.opendaylight.genius.mdsalutil.actions.ActionPopMpls;
import org.opendaylight.genius.mdsalutil.actions.ActionPuntToController;
import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldTunnelId;
import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
import org.opendaylight.genius.mdsalutil.matches.MatchMplsLabel;
import org.opendaylight.genius.mdsalutil.matches.MatchTunnelId;
import org.opendaylight.infrautils.jobcoordinator.JobCoordinator;
import org.opendaylight.netvirt.bgpmanager.api.IBgpManager;
import org.opendaylight.netvirt.elanmanager.api.IElanService;
import org.opendaylight.netvirt.fibmanager.api.IFibManager;
import org.opendaylight.netvirt.fibmanager.api.RouteOrigin;
import org.opendaylight.netvirt.natservice.api.CentralizedSwitchScheduler;
import org.opendaylight.netvirt.neutronvpn.interfaces.INeutronVpnManager;
import org.opendaylight.netvirt.vpnmanager.api.IVpnManager;
import org.opendaylight.serviceutils.upgrade.UpgradeState;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeGre;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.GetTunnelInterfaceNameOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.itm.rpcs.rev160406.ItmRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.CreateFibEntryInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.CreateFibEntryInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.CreateFibEntryOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.FibRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.RemoveFibEntryInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.RemoveFibEntryInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fib.rpc.rev160121.RemoveFibEntryOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig.NatMode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExtRouters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalIpsCounter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpPortMap;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProtocolTypes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.RouterIdName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.RoutersKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.ips.counter.ExternalCounters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.ips.counter.external.counters.ExternalIpCounter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.subnets.Subnets;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.map.ip.mapping.IpMap;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.map.ip.mapping.IpMapBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.map.ip.mapping.IpMapKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMapping;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMappingKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.IntextIpProtocolType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitchKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.router.id.name.RouterIds;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.router.id.name.RouterIdsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.router.id.name.RouterIdsKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.Subnetmaps;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.SubnetmapKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.GenerateVpnLabelOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.RemoveVpnLabelOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.vpn.rpc.rev160201.VpnRpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class ExternalRoutersListener extends AsyncDataTreeChangeListenerBase<Routers, ExternalRoutersListener> {
private static final Logger LOG = LoggerFactory.getLogger(ExternalRoutersListener.class);
private static final BigInteger COOKIE_TUNNEL = new BigInteger("9000000", 16);
private static final BigInteger COOKIE_VM_LFIB_TABLE = new BigInteger("8000022", 16);
private final DataBroker dataBroker;
private final ManagedNewTransactionRunner txRunner;
private final IMdsalApiManager mdsalManager;
private final ItmRpcService itmManager;
private final OdlInterfaceRpcService odlInterfaceRpcService;
private final IdManagerService idManager;
private final NaptManager naptManager;
private final NAPTSwitchSelector naptSwitchSelector;
private final IBgpManager bgpManager;
private final VpnRpcService vpnService;
private final FibRpcService fibService;
private final SNATDefaultRouteProgrammer defaultRouteProgrammer;
private final NaptEventHandler naptEventHandler;
private final NaptPacketInHandler naptPacketInHandler;
private final IFibManager fibManager;
private final IVpnManager vpnManager;
private final EvpnSnatFlowProgrammer evpnSnatFlowProgrammer;
private final CentralizedSwitchScheduler centralizedSwitchScheduler;
private final NatMode natMode;
private final INeutronVpnManager nvpnManager;
private final IElanService elanManager;
private final JobCoordinator coordinator;
private final UpgradeState upgradeState;
private final IInterfaceManager interfaceManager;
private final NatOverVxlanUtil natOverVxlanUtil;
private final int snatPuntTimeout;
@Inject
public ExternalRoutersListener(final DataBroker dataBroker, final IMdsalApiManager mdsalManager,
final ItmRpcService itmManager,
final OdlInterfaceRpcService odlInterfaceRpcService,
final IdManagerService idManager,
final NaptManager naptManager,
final NAPTSwitchSelector naptSwitchSelector,
final IBgpManager bgpManager,
final VpnRpcService vpnService,
final FibRpcService fibService,
final SNATDefaultRouteProgrammer snatDefaultRouteProgrammer,
final NaptEventHandler naptEventHandler,
final NaptPacketInHandler naptPacketInHandler,
final IFibManager fibManager,
final IVpnManager vpnManager,
final EvpnSnatFlowProgrammer evpnSnatFlowProgrammer,
final INeutronVpnManager nvpnManager,
final CentralizedSwitchScheduler centralizedSwitchScheduler,
final NatserviceConfig config,
final IElanService elanManager,
final JobCoordinator coordinator,
final UpgradeState upgradeState,
final NatOverVxlanUtil natOverVxlanUtil,
final IInterfaceManager interfaceManager) {
super(Routers.class, ExternalRoutersListener.class);
this.dataBroker = dataBroker;
this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
this.mdsalManager = mdsalManager;
this.itmManager = itmManager;
this.odlInterfaceRpcService = odlInterfaceRpcService;
this.idManager = idManager;
this.naptManager = naptManager;
this.naptSwitchSelector = naptSwitchSelector;
this.bgpManager = bgpManager;
this.vpnService = vpnService;
this.fibService = fibService;
this.defaultRouteProgrammer = snatDefaultRouteProgrammer;
this.naptEventHandler = naptEventHandler;
this.naptPacketInHandler = naptPacketInHandler;
this.fibManager = fibManager;
this.vpnManager = vpnManager;
this.evpnSnatFlowProgrammer = evpnSnatFlowProgrammer;
this.nvpnManager = nvpnManager;
this.elanManager = elanManager;
this.centralizedSwitchScheduler = centralizedSwitchScheduler;
this.coordinator = coordinator;
this.upgradeState = upgradeState;
this.interfaceManager = interfaceManager;
this.natOverVxlanUtil = natOverVxlanUtil;
if (config != null) {
this.natMode = config.getNatMode();
this.snatPuntTimeout = config.getSnatPuntTimeout().intValue();
} else {
this.natMode = NatMode.Controller;
this.snatPuntTimeout = 0;
}
}
@Override
@PostConstruct
public void init() {
LOG.info("{} init", getClass().getSimpleName());
// This class handles ExternalRouters for Controller SNAT mode.
// For Conntrack SNAT mode, its handled in SnatExternalRoutersListener.java
if (natMode == NatMode.Controller) {
registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
NatUtil.createGroupIdPool(idManager);
}
}
@Override
protected InstanceIdentifier<Routers> getWildCardPath() {
return InstanceIdentifier.create(ExtRouters.class).child(Routers.class);
}
@Override
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
protected void add(InstanceIdentifier<Routers> identifier, Routers routers) {
// Populate the router-id-name container
String routerName = routers.getRouterName();
LOG.info("add : external router event for {}", routerName);
long routerId = NatUtil.getVpnId(dataBroker, routerName);
NatUtil.createRouterIdsConfigDS(dataBroker, routerId, routerName);
Uuid bgpVpnUuid = NatUtil.getVpnForRouter(dataBroker, routerName);
try {
if (routers.isEnableSnat()) {
coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + routers.key(),
() -> Collections.singletonList(
txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, confTx -> {
LOG.info("add : Installing NAT default route on all dpns part of router {}", routerName);
long bgpVpnId = NatConstants.INVALID_ID;
if (bgpVpnUuid != null) {
bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnUuid.getValue());
}
addOrDelDefFibRouteToSNAT(routerName, routerId, bgpVpnId, bgpVpnUuid, true, confTx);
// Allocate Primary Napt Switch for this router
BigInteger primarySwitchId = getPrimaryNaptSwitch(routerName);
if (primarySwitchId != null && !primarySwitchId.equals(BigInteger.ZERO)) {
handleEnableSnat(routers, routerId, primarySwitchId, bgpVpnId, confTx);
}
}
)), NatConstants.NAT_DJC_MAX_RETRIES);
} else {
LOG.info("add : SNAT is disabled for external router {} ", routerName);
}
} catch (Exception ex) {
LOG.error("add : Exception while Installing NAT flows on all dpns as part of router {}",
routerName, ex);
}
}
public void handleEnableSnat(Routers routers, long routerId, BigInteger primarySwitchId, long bgpVpnId,
TypedWriteTransaction<Configuration> confTx) {
String routerName = routers.getRouterName();
LOG.info("handleEnableSnat : Handling SNAT for router {}", routerName);
naptManager.initialiseExternalCounter(routers, routerId);
subnetRegisterMapping(routers, routerId);
LOG.debug("handleEnableSnat:About to create and install outbound miss entry in Primary Switch {} for router {}",
primarySwitchId, routerName);
ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName,
routers.getNetworkId());
if (extNwProvType == null) {
LOG.error("handleEnableSnat : External Network Provider Type missing");
return;
}
if (bgpVpnId != NatConstants.INVALID_ID) {
installFlowsWithUpdatedVpnId(primarySwitchId, routerName, bgpVpnId, routerId, false, confTx,
extNwProvType);
} else {
// write metadata and punt
installOutboundMissEntry(routerName, routerId, primarySwitchId, confTx);
// Now install entries in SNAT tables to point to Primary for each router
List<BigInteger> switches = naptSwitchSelector.getDpnsForVpn(routerName);
for (BigInteger dpnId : switches) {
// Handle switches and NAPT switches separately
if (!dpnId.equals(primarySwitchId)) {
LOG.debug("handleEnableSnat : Handle Ordinary switch");
handleSwitches(dpnId, routerName, routerId, primarySwitchId);
} else {
LOG.debug("handleEnableSnat : Handle NAPT switch");
handlePrimaryNaptSwitch(dpnId, routerName, routerId, confTx);
}
}
}
Collection<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerId);
if (externalIps.isEmpty()) {
LOG.error("handleEnableSnat : Internal External mapping not found for router {}", routerName);
return;
} else {
for (String externalIpAddrPrefix : externalIps) {
LOG.debug("handleEnableSnat : Calling handleSnatReverseTraffic for primarySwitchId {}, "
+ "routerName {} and externalIpAddPrefix {}", primarySwitchId, routerName, externalIpAddrPrefix);
handleSnatReverseTraffic(confTx, primarySwitchId, routers, routerId, routerName, externalIpAddrPrefix
);
}
}
LOG.debug("handleEnableSnat : Exit");
}
private BigInteger getPrimaryNaptSwitch(String routerName) {
// Allocate Primary Napt Switch for this router
BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerName);
if (primarySwitchId != null && !primarySwitchId.equals(BigInteger.ZERO)) {
LOG.debug("handleEnableSnat : Primary NAPT switch with DPN ID {} is already elected for router {}",
primarySwitchId, routerName);
return primarySwitchId;
}
// Allocated an id from VNI pool for the Router.
natOverVxlanUtil.getRouterVni(routerName, NatConstants.INVALID_ID);
primarySwitchId = naptSwitchSelector.selectNewNAPTSwitch(routerName);
LOG.debug("handleEnableSnat : Primary NAPT switch DPN ID {}", primarySwitchId);
return primarySwitchId;
}
protected void installNaptPfibExternalOutputFlow(String routerName, Long routerId, BigInteger dpnId,
TypedWriteTransaction<Configuration> confTx) {
Long extVpnId = NatUtil.getNetworkVpnIdFromRouterId(dataBroker, routerId);
if (extVpnId == NatConstants.INVALID_ID) {
LOG.error("installNaptPfibExternalOutputFlow - not found extVpnId for router {}", routerId);
extVpnId = routerId;
}
List<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerName);
if (externalIps.isEmpty()) {
LOG.error("installNaptPfibExternalOutputFlow - empty external Ips list for dpnId {} extVpnId {}",
dpnId, extVpnId);
return;
}
for (String ip : externalIps) {
Uuid subnetId = getSubnetIdForFixedIp(ip);
if (subnetId != null) {
long subnetVpnId = NatUtil.getExternalSubnetVpnId(dataBroker, subnetId);
if (subnetVpnId != NatConstants.INVALID_ID) {
extVpnId = subnetVpnId;
}
LOG.debug("installNaptPfibExternalOutputFlow - dpnId {} extVpnId {} subnetId {}",
dpnId, extVpnId, subnetId);
FlowEntity postNaptFlowEntity = buildNaptPfibFlowEntity(dpnId, extVpnId);
mdsalManager.addFlow(confTx, postNaptFlowEntity);
}
}
}
@Nullable
private Uuid getSubnetIdForFixedIp(String ip) {
if (ip != null) {
IpAddress externalIpv4Address = new IpAddress(new Ipv4Address(ip));
Port port = NatUtil.getNeutronPortForRouterGetewayIp(dataBroker, externalIpv4Address);
return NatUtil.getSubnetIdForFloatingIp(port, externalIpv4Address);
}
LOG.error("getSubnetIdForFixedIp : ip is null");
return null;
}
protected void subnetRegisterMapping(Routers routerEntry, Long segmentId) {
LOG.debug("subnetRegisterMapping : Fetching values from extRouters model");
List<String> externalIps = NatUtil.getIpsListFromExternalIps(routerEntry.getExternalIps());
int counter = 0;
int extIpCounter = externalIps.size();
LOG.debug("subnetRegisterMapping : counter values before looping counter {} and extIpCounter {}",
counter, extIpCounter);
for (Uuid subnet : requireNonNullElse(routerEntry.getSubnetIds(), Collections.<Uuid>emptyList())) {
LOG.debug("subnetRegisterMapping : Looping internal subnets for subnet {}", subnet);
InstanceIdentifier<Subnetmap> subnetmapId = InstanceIdentifier
.builder(Subnetmaps.class)
.child(Subnetmap.class, new SubnetmapKey(subnet))
.build();
Optional<Subnetmap> sn;
try {
sn = SingleTransactionDataBroker.syncReadOptional(dataBroker,
LogicalDatastoreType.CONFIGURATION, subnetmapId);
} catch (ReadFailedException e) {
LOG.error("Failed to read SubnetMap for subnetmap Id {}", subnetmapId, e);
sn = Optional.absent();
}
if (sn.isPresent()) {
// subnets
Subnetmap subnetmapEntry = sn.get();
String subnetString = subnetmapEntry.getSubnetIp();
String[] subnetSplit = subnetString.split("/");
String subnetIp = subnetSplit[0];
try {
InetAddress address = InetAddress.getByName(subnetIp);
if (address instanceof Inet6Address) {
LOG.debug("subnetRegisterMapping : Skipping ipv6 subnet {} for the router {} with ipv6 address "
+ "{} ", subnet, routerEntry.getRouterName(), address);
continue;
}
} catch (UnknownHostException e) {
LOG.error("subnetRegisterMapping : Invalid ip address {}", subnetIp, e);
return;
}
String subnetPrefix = "0";
if (subnetSplit.length == 2) {
subnetPrefix = subnetSplit[1];
}
IPAddress subnetAddr = new IPAddress(subnetIp, Integer.parseInt(subnetPrefix));
LOG.debug("subnetRegisterMapping : subnetAddr is {} and subnetPrefix is {}",
subnetAddr.getIpAddress(), subnetAddr.getPrefixLength());
//externalIps
LOG.debug("subnetRegisterMapping : counter values counter {} and extIpCounter {}",
counter, extIpCounter);
if (extIpCounter != 0) {
if (counter < extIpCounter) {
String[] ipSplit = externalIps.get(counter).split("/");
String externalIp = ipSplit[0];
String extPrefix = Short.toString(NatConstants.DEFAULT_PREFIX);
if (ipSplit.length == 2) {
extPrefix = ipSplit[1];
}
IPAddress externalIpAddr = new IPAddress(externalIp, Integer.parseInt(extPrefix));
LOG.debug("subnetRegisterMapping : externalIp is {} and extPrefix is {}",
externalIpAddr.getIpAddress(), externalIpAddr.getPrefixLength());
naptManager.registerMapping(segmentId, subnetAddr, externalIpAddr);
LOG.debug("subnetRegisterMapping : Called registerMapping for subnetIp {}, prefix {}, "
+ "externalIp {}. prefix {}", subnetIp, subnetPrefix, externalIp, extPrefix);
} else {
counter = 0; //Reset the counter which runs on externalIps for round-robbin effect
LOG.debug("subnetRegisterMapping : Counter on externalIps got reset");
String[] ipSplit = externalIps.get(counter).split("/");
String externalIp = ipSplit[0];
String extPrefix = Short.toString(NatConstants.DEFAULT_PREFIX);
if (ipSplit.length == 2) {
extPrefix = ipSplit[1];
}
IPAddress externalIpAddr = new IPAddress(externalIp, Integer.parseInt(extPrefix));
LOG.debug("subnetRegisterMapping : externalIp is {} and extPrefix is {}",
externalIpAddr.getIpAddress(), externalIpAddr.getPrefixLength());
naptManager.registerMapping(segmentId, subnetAddr, externalIpAddr);
LOG.debug("subnetRegisterMapping : Called registerMapping for subnetIp {}, prefix {}, "
+ "externalIp {}. prefix {}", subnetIp, subnetPrefix,
externalIp, extPrefix);
}
}
counter++;
LOG.debug("subnetRegisterMapping : Counter on externalIps incremented to {}", counter);
} else {
LOG.warn("subnetRegisterMapping : No internal subnets present in extRouters Model");
}
}
}
private void addOrDelDefFibRouteToSNAT(String routerName, long routerId, long bgpVpnId,
Uuid bgpVpnUuid, boolean create, TypedReadWriteTransaction<Configuration> confTx)
throws ExecutionException, InterruptedException {
//Check if BGP VPN exists. If exists then invoke the new method.
if (bgpVpnId != NatConstants.INVALID_ID) {
if (bgpVpnUuid != null) {
String bgpVpnName = bgpVpnUuid.getValue();
LOG.debug("Populate the router-id-name container with the mapping BGP VPN-ID {} -> BGP VPN-NAME {}",
bgpVpnId, bgpVpnName);
RouterIds rtrs = new RouterIdsBuilder().withKey(new RouterIdsKey(bgpVpnId))
.setRouterId(bgpVpnId).setRouterName(bgpVpnName).build();
confTx.put(getRoutersIdentifier(bgpVpnId), rtrs, CREATE_MISSING_PARENTS);
}
if (create) {
addDefaultFibRouteForSnatWithBgpVpn(routerName, routerId, bgpVpnId, confTx);
} else {
removeDefaultFibRouteForSnatWithBgpVpn(routerName, routerId, bgpVpnId, confTx);
}
return;
}
//Router ID is used as the internal VPN's name, hence the vrf-id in VpnInstance Op DataStore
addOrDelDefaultFibRouteForSNAT(routerName, routerId, create, confTx);
}
private void addOrDelDefaultFibRouteForSNAT(String routerName, long routerId, boolean create,
TypedReadWriteTransaction<Configuration> confTx) throws ExecutionException, InterruptedException {
List<BigInteger> switches = naptSwitchSelector.getDpnsForVpn(routerName);
if (switches.isEmpty()) {
LOG.info("addOrDelDefaultFibRouteForSNAT : No switches found for router {}", routerName);
return;
}
if (routerId == NatConstants.INVALID_ID) {
LOG.error("addOrDelDefaultFibRouteForSNAT : Could not retrieve router Id for {} to program "
+ "default NAT route in FIB", routerName);
return;
}
for (BigInteger dpnId : switches) {
if (create) {
LOG.debug("addOrDelDefaultFibRouteForSNAT : installing default NAT route for router {} in dpn {} "
+ "for the internal vpn-id {}", routerId, dpnId, routerId);
defaultRouteProgrammer.installDefNATRouteInDPN(dpnId, routerId, confTx);
} else {
LOG.debug("addOrDelDefaultFibRouteForSNAT : removing default NAT route for router {} in dpn {} "
+ "for the internal vpn-id {}", routerId, dpnId, routerId);
defaultRouteProgrammer.removeDefNATRouteInDPN(dpnId, routerId, confTx);
}
}
}
private void addDefaultFibRouteForSnatWithBgpVpn(String routerName, long routerId,
long bgpVpnId, TypedWriteTransaction<Configuration> confTx) {
List<BigInteger> dpnIds = NatUtil.getDpnsForRouter(dataBroker, routerName);
if (dpnIds.isEmpty()) {
LOG.error("addOrDelDefaultFibRouteForSNATWIthBgpVpn: No dpns are part of router {} to program "
+ "default NAT flows for BGP-VPN {}", routerName, bgpVpnId);
return;
}
for (BigInteger dpnId : dpnIds) {
if (bgpVpnId != NatConstants.INVALID_ID) {
LOG.debug("addOrDelDefaultFibRouteForSnatWithBgpVpn : installing default NAT route for router {} "
+ "in dpn {} for the BGP vpnID {}", routerId, dpnId, bgpVpnId);
defaultRouteProgrammer.installDefNATRouteInDPN(dpnId, bgpVpnId, routerId, confTx);
} else {
LOG.debug("addOrDelDefaultFibRouteForSnatWithBgpVpn : installing default NAT route for router {} "
+ "in dpn {} for the internal vpn", routerId, dpnId);
defaultRouteProgrammer.installDefNATRouteInDPN(dpnId, routerId, confTx);
}
}
}
private void removeDefaultFibRouteForSnatWithBgpVpn(String routerName, long routerId,
long bgpVpnId, TypedReadWriteTransaction<Configuration> confTx)
throws ExecutionException, InterruptedException {
List<BigInteger> dpnIds = NatUtil.getDpnsForRouter(dataBroker, routerName);
if (dpnIds.isEmpty()) {
LOG.error("addOrDelDefaultFibRouteForSNATWIthBgpVpn: No dpns are part of router {} to program "
+ "default NAT flows for BGP-VPN {}", routerName, bgpVpnId);
return;
}
for (BigInteger dpnId : dpnIds) {
if (bgpVpnId != NatConstants.INVALID_ID) {
LOG.debug("addOrDelDefaultFibRouteForSnatWithBgpVpn : removing default NAT route for router {} "
+ "in dpn {} for the BGP vpnID {}", routerId, dpnId, bgpVpnId);
defaultRouteProgrammer.removeDefNATRouteInDPN(dpnId, bgpVpnId, routerId, confTx);
} else {
LOG.debug("addOrDelDefaultFibRouteForSnatWithBgpVpn : removing default NAT route for router {} "
+ "in dpn {} for the internal vpn", routerId, dpnId);
defaultRouteProgrammer.removeDefNATRouteInDPN(dpnId, routerId, confTx);
}
}
}
protected void installOutboundMissEntry(String routerName, long routerId, BigInteger primarySwitchId,
TypedWriteTransaction<Configuration> confTx) {
LOG.debug("installOutboundMissEntry : Router ID from getVpnId {}", routerId);
if (routerId != NatConstants.INVALID_ID) {
LOG.debug("installOutboundMissEntry : Creating miss entry on primary {}, for router {}",
primarySwitchId, routerId);
createOutboundTblEntry(primarySwitchId, routerId, confTx);
} else {
LOG.error("installOutboundMissEntry : Unable to fetch Router Id for RouterName {}, failed to "
+ "createAndInstallMissEntry", routerName);
}
}
public String getFlowRefOutbound(BigInteger dpnId, short tableId, long routerID, int protocol) {
return NatConstants.NAPT_FLOWID_PREFIX + dpnId + NatConstants.FLOWID_SEPARATOR + tableId + NatConstants
.FLOWID_SEPARATOR + routerID + NatConstants.FLOWID_SEPARATOR + protocol;
}
private String getFlowRefNaptPreFib(BigInteger dpnId, short tableId, long vpnId) {
return NatConstants.NAPT_FLOWID_PREFIX + dpnId + NatConstants.FLOWID_SEPARATOR + tableId + NatConstants
.FLOWID_SEPARATOR + vpnId;
}
public BigInteger getCookieOutboundFlow(long routerId) {
return NwConstants.COOKIE_OUTBOUND_NAPT_TABLE.add(new BigInteger("0110001", 16)).add(
BigInteger.valueOf(routerId));
}
private ActionLearn getLearnActionForPunt(int protocol, int hardTimeout, BigInteger cookie) {
long l4SrcPortField;
long l4DstPortField;
int l4portFieldLen = NxmOfFieldType.NXM_OF_TCP_SRC.getFlowModHeaderLenInt();
if (protocol == NwConstants.IP_PROT_TCP) {
l4SrcPortField = NxmOfFieldType.NXM_OF_TCP_SRC.getType();
l4DstPortField = NxmOfFieldType.NXM_OF_TCP_DST.getType();
} else {
l4SrcPortField = NxmOfFieldType.NXM_OF_UDP_SRC.getType();
l4DstPortField = NxmOfFieldType.NXM_OF_UDP_DST.getType();
}
List<ActionLearn.FlowMod> flowMods = Arrays.asList(
new MatchFromValue(NwConstants.ETHTYPE_IPV4, NxmOfFieldType.NXM_OF_ETH_TYPE.getType(),
NxmOfFieldType.NXM_OF_ETH_TYPE.getFlowModHeaderLenInt()),
new MatchFromValue(protocol, NxmOfFieldType.NXM_OF_IP_PROTO.getType(),
NxmOfFieldType.NXM_OF_IP_PROTO.getFlowModHeaderLenInt()),
new MatchFromField(NxmOfFieldType.NXM_OF_IP_SRC.getType(), NxmOfFieldType.NXM_OF_IP_SRC.getType(),
NxmOfFieldType.NXM_OF_IP_SRC.getFlowModHeaderLenInt()),
new MatchFromField(NxmOfFieldType.NXM_OF_IP_DST.getType(), NxmOfFieldType.NXM_OF_IP_DST.getType(),
NxmOfFieldType.NXM_OF_IP_DST.getFlowModHeaderLenInt()),
new MatchFromField(l4SrcPortField, l4SrcPortField, l4portFieldLen),
new MatchFromField(l4DstPortField, l4DstPortField, l4portFieldLen),
new MatchFromField(NxmOfFieldType.OXM_OF_METADATA.getType(),
MetaDataUtil.METADATA_VPN_ID_OFFSET,
NxmOfFieldType.OXM_OF_METADATA.getType(), MetaDataUtil.METADATA_VPN_ID_OFFSET,
MetaDataUtil.METADATA_VPN_ID_BITLEN));
return new ActionLearn(0, hardTimeout, 7, cookie, 0,
NwConstants.OUTBOUND_NAPT_TABLE, 0, 0, flowMods);
}
private FlowEntity buildIcmpDropFlow(BigInteger dpnId, long routerId, long vpnId) {
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(MatchIpProtocol.ICMP);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
List<ActionInfo> actionInfos = new ArrayList<>();
actionInfos.add(new ActionDrop());
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionInfos));
String flowRef = getFlowRefOutbound(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId,
NwConstants.IP_PROT_ICMP);
FlowEntity flow = MDSALUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, flowRef,
NwConstants.TABLE_MISS_PRIORITY, "icmp drop flow", 0, 0,
NwConstants.COOKIE_OUTBOUND_NAPT_TABLE, matches, instructions);
return flow;
}
protected FlowEntity buildOutboundFlowEntity(BigInteger dpId, long routerId, int protocol) {
LOG.debug("buildOutboundFlowEntity : called for dpId {} and routerId{}", dpId, routerId);
BigInteger cookie = getCookieOutboundFlow(routerId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchIpProtocol((short)protocol));
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
List<InstructionInfo> instructions = new ArrayList<>();
List<ActionInfo> actionsInfos = new ArrayList<>();
actionsInfos.add(new ActionPuntToController());
if (snatPuntTimeout != 0) {
actionsInfos.add(getLearnActionForPunt(protocol, snatPuntTimeout, cookie));
}
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRefOutbound(dpId, NwConstants.OUTBOUND_NAPT_TABLE, routerId, protocol);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.OUTBOUND_NAPT_TABLE, flowRef,
5, flowRef, 0, 0,
cookie, matches, instructions);
LOG.debug("installOutboundMissEntry : returning flowEntity {}", flowEntity);
return flowEntity;
}
public void createOutboundTblEntry(BigInteger dpnId, long routerId, TypedWriteTransaction<Configuration> confTx) {
LOG.debug("createOutboundTblEntry : called for dpId {} and routerId {}", dpnId, routerId);
FlowEntity tcpflowEntity = buildOutboundFlowEntity(dpnId, routerId, NwConstants.IP_PROT_TCP);
LOG.debug("createOutboundTblEntry : Installing tcp flow {}", tcpflowEntity);
mdsalManager.addFlow(confTx, tcpflowEntity);
FlowEntity udpflowEntity = buildOutboundFlowEntity(dpnId, routerId, NwConstants.IP_PROT_UDP);
LOG.debug("createOutboundTblEntry : Installing udp flow {}", udpflowEntity);
mdsalManager.addFlow(confTx, udpflowEntity);
FlowEntity icmpDropFlow = buildIcmpDropFlow(dpnId, routerId, routerId);
LOG.debug("createOutboundTblEntry: Installing icmp drop flow {}", icmpDropFlow);
mdsalManager.addFlow(confTx, icmpDropFlow);
}
@Nullable
protected String getTunnelInterfaceName(BigInteger srcDpId, BigInteger dstDpId) {
Class<? extends TunnelTypeBase> tunType = TunnelTypeVxlan.class;
RpcResult<GetTunnelInterfaceNameOutput> rpcResult;
try {
Future<RpcResult<GetTunnelInterfaceNameOutput>> result =
itmManager.getTunnelInterfaceName(new GetTunnelInterfaceNameInputBuilder()
.setSourceDpid(srcDpId)
.setDestinationDpid(dstDpId)
.setTunnelType(tunType)
.build());
rpcResult = result.get();
if (!rpcResult.isSuccessful()) {
tunType = TunnelTypeGre.class;
result = itmManager.getTunnelInterfaceName(new GetTunnelInterfaceNameInputBuilder()
.setSourceDpid(srcDpId)
.setDestinationDpid(dstDpId)
.setTunnelType(tunType)
.build());
rpcResult = result.get();
if (!rpcResult.isSuccessful()) {
LOG.warn("getTunnelInterfaceName : RPC Call to getTunnelInterfaceId returned with Errors {}",
rpcResult.getErrors());
} else {
return rpcResult.getResult().getInterfaceName();
}
LOG.warn("getTunnelInterfaceName : RPC Call to getTunnelInterfaceId returned with Errors {}",
rpcResult.getErrors());
} else {
return rpcResult.getResult().getInterfaceName();
}
} catch (InterruptedException | ExecutionException | NullPointerException e) {
LOG.error("getTunnelInterfaceName : Exception when getting tunnel interface Id for tunnel "
+ "between {} and {}", srcDpId, dstDpId, e);
}
return null;
}
protected void installSnatMissEntryForPrimrySwch(BigInteger dpnId, String routerName, long routerId,
TypedWriteTransaction<Configuration> confTx) {
LOG.debug("installSnatMissEntry : called for for the primary NAPT switch dpnId {} ", dpnId);
// Install miss entry pointing to group
FlowEntity flowEntity = buildSnatFlowEntityForPrmrySwtch(dpnId, routerName, routerId);
mdsalManager.addFlow(confTx, flowEntity);
}
protected void installSnatMissEntry(BigInteger dpnId, List<BucketInfo> bucketInfo,
String routerName, long routerId) {
LOG.debug("installSnatMissEntry : called for dpnId {} with primaryBucket {} ",
dpnId, bucketInfo.get(0));
// Install the select group
long groupId = createGroupId(getGroupIdKey(routerName));
GroupEntity groupEntity =
MDSALUtil.buildGroupEntity(dpnId, groupId, routerName, GroupTypes.GroupAll, bucketInfo);
LOG.debug("installSnatMissEntry : installing the SNAT to NAPT GroupEntity:{}", groupEntity);
mdsalManager.syncInstallGroup(groupEntity);
// Install miss entry pointing to group
FlowEntity flowEntity = buildSnatFlowEntity(dpnId, routerName, routerId, groupId);
if (flowEntity == null) {
LOG.error("installSnatMissEntry : Flow entity received as NULL. "
+ "Cannot proceed with installation of SNAT Flow in table {} which is pointing to Group "
+ "on Non NAPT DPN {} for router {}", NwConstants.PSNAT_TABLE, dpnId, routerName);
return;
}
mdsalManager.installFlow(flowEntity);
}
long installGroup(BigInteger dpnId, String routerName, List<BucketInfo> bucketInfo) {
long groupId = createGroupId(getGroupIdKey(routerName));
GroupEntity groupEntity =
MDSALUtil.buildGroupEntity(dpnId, groupId, routerName, GroupTypes.GroupAll, bucketInfo);
LOG.debug("installGroup : installing the SNAT to NAPT GroupEntity:{}", groupEntity);
mdsalManager.syncInstallGroup(groupEntity);
return groupId;
}
private FlowEntity buildSnatFlowEntity(BigInteger dpId, String routerName, long routerId, long groupId) {
LOG.debug("buildSnatFlowEntity : called for dpId {}, routerName {} and groupId {}",
dpId, routerName, groupId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
List<ActionInfo> actionsInfo = new ArrayList<>();
long tunnelId = NatUtil.getTunnelIdForNonNaptToNaptFlow(dataBroker, natOverVxlanUtil, elanManager, idManager,
routerId, routerName);
actionsInfo.add(new ActionSetFieldTunnelId(BigInteger.valueOf(tunnelId)));
LOG.debug("buildSnatFlowEntity : Setting the tunnel to the list of action infos {}", actionsInfo);
actionsInfo.add(new ActionGroup(groupId));
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionsInfo));
String flowRef = getFlowRefSnat(dpId, NwConstants.PSNAT_TABLE, routerName);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions);
LOG.debug("buildSnatFlowEntity : Returning SNAT Flow Entity {}", flowEntity);
return flowEntity;
}
private FlowEntity buildSnatFlowEntityForPrmrySwtch(BigInteger dpId, String routerName, long routerId) {
LOG.debug("buildSnatFlowEntityForPrmrySwtch : called for primary NAPT switch dpId {}, routerName {}", dpId,
routerName);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(routerId), MetaDataUtil.METADATA_MASK_VRFID));
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionGotoTable(NwConstants.OUTBOUND_NAPT_TABLE));
String flowRef = getFlowRefSnat(dpId, NwConstants.PSNAT_TABLE, routerName);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions);
LOG.debug("buildSnatFlowEntityForPrmrySwtch : Returning SNAT Flow Entity {}", flowEntity);
return flowEntity;
}
// TODO : Replace this with ITM Rpc once its available with full functionality
protected void installTerminatingServiceTblEntry(BigInteger dpnId, String routerName, long routerId,
TypedWriteTransaction<Configuration> confTx) {
LOG.debug("installTerminatingServiceTblEntry : for switch {}, routerName {}",
dpnId, routerName);
FlowEntity flowEntity = buildTsFlowEntity(dpnId, routerName, routerId);
if (flowEntity == null) {
LOG.error("installTerminatingServiceTblEntry : Flow entity received as NULL. "
+ "Cannot proceed with installation of Terminating Service table {} which is pointing to table {} "
+ "on DPN {} for router {}", NwConstants.INTERNAL_TUNNEL_TABLE, NwConstants.OUTBOUND_NAPT_TABLE,
dpnId, routerName);
return;
}
mdsalManager.addFlow(confTx, flowEntity);
}
private FlowEntity buildTsFlowEntity(BigInteger dpId, String routerName, long routerId) {
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
long tunnelId = NatUtil.getTunnelIdForNonNaptToNaptFlow(dataBroker, natOverVxlanUtil, elanManager,
idManager, routerId, routerName);
matches.add(new MatchTunnelId(BigInteger.valueOf(tunnelId)));
String flowRef = getFlowRefTs(dpId, NwConstants.INTERNAL_TUNNEL_TABLE, tunnelId);
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(routerId),
MetaDataUtil.METADATA_MASK_VRFID));
instructions.add(new InstructionGotoTable(NwConstants.OUTBOUND_NAPT_TABLE));
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.INTERNAL_TUNNEL_TABLE, flowRef,
NatConstants.DEFAULT_TS_FLOW_PRIORITY, flowRef, 0, 0, NwConstants.COOKIE_TS_TABLE, matches,
instructions);
return flowEntity;
}
public String getFlowRefTs(BigInteger dpnId, short tableId, long routerID) {
return NatConstants.NAPT_FLOWID_PREFIX + dpnId + NatConstants.FLOWID_SEPARATOR + tableId + NatConstants
.FLOWID_SEPARATOR + routerID;
}
public static String getFlowRefSnat(BigInteger dpnId, short tableId, String routerID) {
return NatConstants.SNAT_FLOWID_PREFIX + dpnId + NatConstants.FLOWID_SEPARATOR + tableId + NatConstants
.FLOWID_SEPARATOR + routerID;
}
private String getGroupIdKey(String routerName) {
return "snatmiss." + routerName;
}
protected long createGroupId(String groupIdKey) {
AllocateIdInput getIdInput = new AllocateIdInputBuilder()
.setPoolName(NatConstants.SNAT_IDPOOL_NAME).setIdKey(groupIdKey)
.build();
try {
Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
RpcResult<AllocateIdOutput> rpcResult = result.get();
return rpcResult.getResult().getIdValue();
} catch (NullPointerException | InterruptedException | ExecutionException e) {
LOG.error("Exception While allocating id for group: {}", groupIdKey, e);
}
return 0;
}
protected void handleSwitches(BigInteger dpnId, String routerName, long routerId, BigInteger primarySwitchId) {
LOG.debug("handleSwitches : Installing SNAT miss entry in switch {}", dpnId);
List<ActionInfo> listActionInfoPrimary = new ArrayList<>();
String ifNamePrimary = getTunnelInterfaceName(dpnId, primarySwitchId);
List<BucketInfo> listBucketInfo = new ArrayList<>();
if (ifNamePrimary != null) {
LOG.debug("handleSwitches : On Non- Napt switch , Primary Tunnel interface is {}", ifNamePrimary);
listActionInfoPrimary = NatUtil.getEgressActionsForInterface(odlInterfaceRpcService, itmManager,
interfaceManager, ifNamePrimary, routerId, true);
if (listActionInfoPrimary.isEmpty()) {
LOG.error("handleSwitches : Unable to retrieve output actions on Non-NAPT switch {} for router {}"
+ " towards Napt-switch {} via tunnel interface {}", dpnId, routerName, primarySwitchId,
ifNamePrimary);
}
} else {
LOG.error("handleSwitches : Unable to obtain primary tunnel interface to Napt-Switch {} from "
+ "Non-Napt switch {} for router {}", primarySwitchId, dpnId, routerName);
}
BucketInfo bucketPrimary = new BucketInfo(listActionInfoPrimary);
listBucketInfo.add(0, bucketPrimary);
installSnatMissEntry(dpnId, listBucketInfo, routerName, routerId);
}
List<BucketInfo> getBucketInfoForNonNaptSwitches(BigInteger nonNaptSwitchId,
BigInteger primarySwitchId, String routerName, long routerId) {
List<ActionInfo> listActionInfoPrimary = new ArrayList<>();
String ifNamePrimary = getTunnelInterfaceName(nonNaptSwitchId, primarySwitchId);
List<BucketInfo> listBucketInfo = new ArrayList<>();
if (ifNamePrimary != null) {
LOG.debug("getBucketInfoForNonNaptSwitches : On Non- Napt switch , Primary Tunnel interface is {}",
ifNamePrimary);
listActionInfoPrimary = NatUtil.getEgressActionsForInterface(odlInterfaceRpcService, itmManager,
interfaceManager, ifNamePrimary, routerId, true);
if (listActionInfoPrimary.isEmpty()) {
LOG.error("getBucketInfoForNonNaptSwitches : Unable to retrieve output actions on Non-NAPT switch {} "
+ "for router {} towards Napt-switch {} via tunnel interface {}",
nonNaptSwitchId, routerName, primarySwitchId, ifNamePrimary);
}
} else {
LOG.error("getBucketInfoForNonNaptSwitches : Unable to obtain primary tunnel interface to Napt-Switch {} "
+ "from Non-Napt switch {} for router {}", primarySwitchId, nonNaptSwitchId, routerName);
}
BucketInfo bucketPrimary = new BucketInfo(listActionInfoPrimary);
listBucketInfo.add(0, bucketPrimary);
return listBucketInfo;
}
protected void handlePrimaryNaptSwitch(BigInteger dpnId, String routerName, long routerId,
TypedWriteTransaction<Configuration> confTx) {
LOG.debug("handlePrimaryNaptSwitch : Installing SNAT miss entry in Primary NAPT switch {} ", dpnId);
/*
List<BucketInfo> listBucketInfo = new ArrayList<>();
List<ActionInfo> listActionInfoPrimary = new ArrayList<>();
listActionInfoPrimary.add(new ActionNxResubmit(NatConstants.TERMINATING_SERVICE_TABLE));
BucketInfo bucketPrimary = new BucketInfo(listActionInfoPrimary);
listBucketInfo.add(0, bucketPrimary);
*/
installSnatMissEntryForPrimrySwch(dpnId, routerName, routerId, confTx);
installTerminatingServiceTblEntry(dpnId, routerName, routerId, confTx);
//Install the NAPT PFIB TABLE which forwards the outgoing packet to FIB Table matching on the router ID.
installNaptPfibEntry(dpnId, routerId, confTx);
Uuid networkId = NatUtil.getNetworkIdFromRouterId(dataBroker, routerId);
if (networkId != null) {
Uuid vpnUuid = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
if (vpnUuid != null) {
long vpnId = NatUtil.getVpnId(dataBroker, vpnUuid.getValue());
coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + networkId, () -> {
installNaptPfibEntriesForExternalSubnets(routerName, dpnId, null);
//Install the NAPT PFIB TABLE which forwards outgoing packet to FIB Table matching on the VPN ID.
if (vpnId != NatConstants.INVALID_ID) {
installNaptPfibEntry(dpnId, vpnId, null);
}
return Collections.emptyList();
});
} else {
LOG.warn("handlePrimaryNaptSwitch : External Vpn ID missing for Ext-Network : {}", networkId);
}
} else {
LOG.warn("handlePrimaryNaptSwitch : External Network not available for router : {}", routerName);
}
}
List<BucketInfo> getBucketInfoForPrimaryNaptSwitch() {
List<BucketInfo> listBucketInfo = new ArrayList<>();
List<ActionInfo> listActionInfoPrimary = new ArrayList<>();
listActionInfoPrimary.add(new ActionNxResubmit(NwConstants.INTERNAL_TUNNEL_TABLE));
BucketInfo bucketPrimary = new BucketInfo(listActionInfoPrimary);
listBucketInfo.add(0, bucketPrimary);
return listBucketInfo;
}
public void installNaptPfibEntry(BigInteger dpnId, long segmentId,
@Nullable TypedWriteTransaction<Configuration> confTx) {
LOG.debug("installNaptPfibEntry : called for dpnId {} and segmentId {} ", dpnId, segmentId);
FlowEntity naptPfibFlowEntity = buildNaptPfibFlowEntity(dpnId, segmentId);
if (confTx != null) {
mdsalManager.addFlow(confTx, naptPfibFlowEntity);
} else {
mdsalManager.installFlow(naptPfibFlowEntity);
}
}
public FlowEntity buildNaptPfibFlowEntity(BigInteger dpId, long segmentId) {
LOG.debug("buildNaptPfibFlowEntity : called for dpId {}, segmentId {}", dpId, segmentId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID));
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
listActionInfo.add(new ActionNxLoadInPort(BigInteger.ZERO));
listActionInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
instructionInfo.add(new InstructionApplyActions(listActionInfo));
String flowRef = getFlowRefTs(dpId, NwConstants.NAPT_PFIB_TABLE, segmentId);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.NAPT_PFIB_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructionInfo);
LOG.debug("buildNaptPfibFlowEntity : Returning NaptPFib Flow Entity {}", flowEntity);
return flowEntity;
}
public void handleSnatReverseTraffic(TypedWriteTransaction<Configuration> confTx, BigInteger dpnId, Routers router,
long routerId, String routerName, String externalIp) {
LOG.debug("handleSnatReverseTraffic : entry for DPN ID {}, routerId {}, externalIp: {}",
dpnId, routerId, externalIp);
Uuid networkId = router.getNetworkId();
if (networkId == null) {
LOG.error("handleSnatReverseTraffic : networkId is null for the router ID {}", routerId);
return;
}
final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId);
if (vpnName == null) {
LOG.error("handleSnatReverseTraffic : No VPN associated with ext nw {} to handle add external ip "
+ "configuration {} in router {}", networkId, externalIp, routerId);
return;
}
advToBgpAndInstallFibAndTsFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, vpnName, routerId, routerName,
externalIp, networkId, router, confTx);
LOG.debug("handleSnatReverseTraffic : exit for DPN ID {}, routerId {}, externalIp : {}",
dpnId, routerId, externalIp);
}
public void advToBgpAndInstallFibAndTsFlows(final BigInteger dpnId, final short tableId, final String vpnName,
final long routerId, final String routerName, final String externalIp,
final Uuid extNetworkId, @Nullable final Routers router,
final TypedWriteTransaction<Configuration> confTx) {
LOG.debug("advToBgpAndInstallFibAndTsFlows : entry for DPN ID {}, tableId {}, vpnname {} "
+ "and externalIp {}", dpnId, tableId, vpnName, externalIp);
String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId);
String rd = NatUtil.getVpnRd(dataBroker, vpnName);
if (rd == null || rd.isEmpty()) {
LOG.error("advToBgpAndInstallFibAndTsFlows : Unable to get RD for VPN Name {}", vpnName);
return;
}
ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, extNetworkId);
if (extNwProvType == null) {
LOG.error("advToBgpAndInstallFibAndTsFlows : External Network Provider Type missing");
return;
}
if (extNwProvType == ProviderTypes.VXLAN) {
evpnSnatFlowProgrammer.evpnAdvToBgpAndInstallFibAndTsFlows(dpnId, tableId, externalIp, vpnName, rd,
nextHopIp, routerId, routerName, extNetworkId, confTx);
return;
}
//Generate VPN label for the external IP
GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName)
.setIpPrefix(externalIp).build();
ListenableFuture<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput);
//On successful generation of the VPN label, advertise the route to the BGP and install the FIB routes.
ListenableFuture<RpcResult<CreateFibEntryOutput>> future = Futures.transformAsync(labelFuture, result -> {
if (result.isSuccessful()) {
LOG.debug("advToBgpAndInstallFibAndTsFlows : inside apply with result success");
GenerateVpnLabelOutput output = result.getResult();
final long label = output.getLabel();
int externalIpInDsFlag = 0;
//Get IPMaps from the DB for the router ID
List<IpMap> dbIpMaps = NaptManager.getIpMapList(dataBroker, routerId);
for (IpMap dbIpMap : dbIpMaps) {
String dbExternalIp = dbIpMap.getExternalIp();
//Select the IPMap, whose external IP is the IP for which FIB is installed
if (dbExternalIp.contains(externalIp)) {
String dbInternalIp = dbIpMap.getInternalIp();
IpMapKey dbIpMapKey = dbIpMap.key();
LOG.debug("advToBgpAndInstallFibAndTsFlows : Setting label {} for internalIp {} "
+ "and externalIp {}", label, dbInternalIp, externalIp);
IpMap newIpm = new IpMapBuilder().withKey(dbIpMapKey).setInternalIp(dbInternalIp)
.setExternalIp(dbExternalIp).setLabel(label).build();
MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL,
naptManager.getIpMapIdentifier(routerId, dbInternalIp), newIpm);
externalIpInDsFlag++;
}
}
if (externalIpInDsFlag <= 0) {
LOG.debug("advToBgpAndInstallFibAndTsFlows : External Ip {} not found in DS, "
+ "Failed to update label {} for routerId {} in DS",
externalIp, label, routerId);
String errMsg = String.format("Failed to update label %s due to external Ip %s not"
+ " found in DS for router %s", label, externalIp, routerId);
return Futures.immediateFailedFuture(new Exception(errMsg));
}
//Inform BGP
long l3vni = 0;
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
l3vni = natOverVxlanUtil.getInternetVpnVni(vpnName, l3vni).longValue();
}
Routers extRouter = router != null ? router :
NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
NatUtil.addPrefixToBGP(dataBroker, bgpManager, fibManager, vpnName, rd,
externalIp, nextHopIp, extRouter.getNetworkId().getValue(), null, label, l3vni,
RouteOrigin.STATIC, dpnId);
//Install custom FIB routes
List<Instruction> tunnelTableCustomInstructions = new ArrayList<>();
tunnelTableCustomInstructions.add(new InstructionGotoTable(tableId).buildInstruction(0));
makeTunnelTableEntry(dpnId, label, l3vni, tunnelTableCustomInstructions, confTx,
extNwProvType);
makeLFibTableEntry(dpnId, label, tableId, confTx);
//Install custom FIB routes - FIB table.
List<Instruction> fibTableCustomInstructions = createFibTableCustomInstructions(tableId,
routerName, externalIp);
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
//Install the flow table 25->44 If there is no FIP Match on table 25 (PDNAT_TABLE)
NatUtil.makePreDnatToSnatTableEntry(mdsalManager, dpnId, NwConstants.INBOUND_NAPT_TABLE, confTx);
}
String fibExternalIp = NatUtil.validateAndAddNetworkMask(externalIp);
Uuid externalSubnetId = NatUtil.getExternalSubnetForRouterExternalIp(externalIp, extRouter);
Optional<Subnets> externalSubnet = NatUtil.getOptionalExternalSubnets(dataBroker, externalSubnetId);
String externalVpn = externalSubnet.isPresent() ? externalSubnetId.getValue() : vpnName;
CreateFibEntryInput input = new CreateFibEntryInputBuilder()
.setVpnName(externalVpn)
.setSourceDpid(dpnId).setIpAddress(fibExternalIp).setServiceId(label)
.setIpAddressSource(CreateFibEntryInput.IpAddressSource.ExternalFixedIP)
.setInstruction(fibTableCustomInstructions).build();
return fibService.createFibEntry(input);
} else {
LOG.error("advToBgpAndInstallFibAndTsFlows : inside apply with result failed");
String errMsg = String.format("Could not retrieve the label for prefix %s in VPN %s, %s",
externalIp, vpnName, result.getErrors());
return Futures.immediateFailedFuture(new RuntimeException(errMsg));
}
}, MoreExecutors.directExecutor());
Futures.addCallback(future, new FutureCallback<RpcResult<CreateFibEntryOutput>>() {
@Override
public void onFailure(@Nonnull Throwable error) {
LOG.error("advToBgpAndInstallFibAndTsFlows : Error in generate label or fib install process", error);
}
@Override
public void onSuccess(@Nonnull RpcResult<CreateFibEntryOutput> result) {
if (result.isSuccessful()) {
LOG.info("advToBgpAndInstallFibAndTsFlows : Successfully installed custom FIB routes for prefix {}",
externalIp);
} else {
LOG.error("advToBgpAndInstallFibAndTsFlows : Error in rpc call to create custom Fib entries "
+ "for prefix {} in DPN {}, {}", externalIp, dpnId, result.getErrors());
}
}
}, MoreExecutors.directExecutor());
}
private List<Instruction> createFibTableCustomInstructions(short tableId, String routerName,
String externalIp) {
List<Instruction> fibTableCustomInstructions = new ArrayList<>();
Routers router = NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
long externalSubnetVpnId = NatUtil.getExternalSubnetVpnIdForRouterExternalIp(dataBroker,
externalIp, router);
int instructionIndex = 0;
if (externalSubnetVpnId != NatConstants.INVALID_ID) {
BigInteger subnetIdMetaData = MetaDataUtil.getVpnIdMetadata(externalSubnetVpnId);
fibTableCustomInstructions.add(new InstructionWriteMetadata(subnetIdMetaData,
MetaDataUtil.METADATA_MASK_VRFID).buildInstruction(instructionIndex));
instructionIndex++;
}
fibTableCustomInstructions.add(new InstructionGotoTable(tableId).buildInstruction(instructionIndex));
return fibTableCustomInstructions;
}
private void makeLFibTableEntry(BigInteger dpId, long serviceId, short tableId,
TypedWriteTransaction<Configuration> confTx) {
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.MPLS_UNICAST);
matches.add(new MatchMplsLabel(serviceId));
List<Instruction> instructions = new ArrayList<>();
List<ActionInfo> actionsInfos = new ArrayList<>();
//NAT is required for IPv4 only. Hence always etherType will be IPv4
actionsInfos.add(new ActionPopMpls(NwConstants.ETHTYPE_IPV4));
Instruction writeInstruction = new InstructionApplyActions(actionsInfos).buildInstruction(0);
instructions.add(writeInstruction);
instructions.add(new InstructionGotoTable(tableId).buildInstruction(1));
// Install the flow entry in L3_LFIB_TABLE
String flowRef = getFlowRef(dpId, NwConstants.L3_LFIB_TABLE, serviceId, "");
Flow flowEntity = MDSALUtil.buildFlowNew(NwConstants.L3_LFIB_TABLE, flowRef,
10, flowRef, 0, 0,
COOKIE_VM_LFIB_TABLE, matches, instructions);
mdsalManager.addFlow(confTx, dpId, flowEntity);
LOG.debug("makeLFibTableEntry : LFIB Entry for dpID {} : label : {} modified successfully", dpId, serviceId);
}
private void makeTunnelTableEntry(BigInteger dpnId, long serviceId, long l3Vni,
List<Instruction> customInstructions, TypedWriteTransaction<Configuration> confTx,
ProviderTypes extNwProvType) {
List<MatchInfo> mkMatches = new ArrayList<>();
LOG.debug("makeTunnelTableEntry : DpnId = {} and serviceId = {} and actions = {}",
dpnId, serviceId, customInstructions);
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
mkMatches.add(new MatchTunnelId(BigInteger.valueOf(l3Vni)));
} else {
mkMatches.add(new MatchTunnelId(BigInteger.valueOf(serviceId)));
}
Flow terminatingServiceTableFlowEntity = MDSALUtil.buildFlowNew(NwConstants.INTERNAL_TUNNEL_TABLE,
getFlowRef(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, serviceId, ""), 5,
String.format("%s:%d", "TST Flow Entry ", serviceId),
0, 0, COOKIE_TUNNEL.add(BigInteger.valueOf(serviceId)), mkMatches, customInstructions);
mdsalManager.addFlow(confTx, dpnId, terminatingServiceTableFlowEntity);
}
protected InstanceIdentifier<RouterIds> getRoutersIdentifier(long routerId) {
return InstanceIdentifier.builder(RouterIdName.class).child(RouterIds.class,
new RouterIdsKey(routerId)).build();
}
private String getFlowRef(BigInteger dpnId, short tableId, long id, String ipAddress) {
return NatConstants.SNAT_FLOWID_PREFIX + dpnId + NwConstants.FLOWID_SEPARATOR + tableId + NwConstants
.FLOWID_SEPARATOR + id + NwConstants.FLOWID_SEPARATOR + ipAddress;
}
@Override
protected void update(InstanceIdentifier<Routers> identifier, Routers original, Routers update) {
String routerName = original.getRouterName();
Long routerId = NatUtil.getVpnId(dataBroker, routerName);
if (routerId == NatConstants.INVALID_ID) {
LOG.error("update : external router event - Invalid routerId for routerName {}", routerName);
return;
}
// Check if its update on SNAT flag
boolean originalSNATEnabled = original.isEnableSnat();
boolean updatedSNATEnabled = update.isEnableSnat();
LOG.debug("update :called with originalFlag and updatedFlag for SNAT enabled "
+ "as {} and {}", originalSNATEnabled, updatedSNATEnabled);
/* Get Primary Napt Switch for existing router from "router-to-napt-switch" DS.
* if dpnId value is null or zero then go for electing new Napt switch for existing router.
*/
long bgpVpnId = NatConstants.INVALID_ID;
Uuid bgpVpnUuid = NatUtil.getVpnForRouter(dataBroker, routerName);
if (bgpVpnUuid != null) {
bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnUuid.getValue());
}
BigInteger dpnId = getPrimaryNaptSwitch(routerName);
if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
// Router has no interface attached
return;
}
final long finalBgpVpnId = bgpVpnId;
coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + update.key(), () -> {
List<ListenableFuture<Void>> futures = new ArrayList<>();
futures.add(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, writeFlowInvTx -> {
futures.add(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, removeFlowInvTx -> {
Uuid networkId = original.getNetworkId();
if (originalSNATEnabled != updatedSNATEnabled) {
if (originalSNATEnabled) {
//SNAT disabled for the router
Uuid networkUuid = original.getNetworkId();
LOG.info("update : SNAT disabled for Router {}", routerName);
Collection<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerId);
handleDisableSnat(original, networkUuid, externalIps, false, null, dpnId, routerId,
removeFlowInvTx);
} else {
LOG.info("update : SNAT enabled for Router {}", original.getRouterName());
addOrDelDefFibRouteToSNAT(routerName, routerId, finalBgpVpnId, bgpVpnUuid,
true, writeFlowInvTx);
handleEnableSnat(original, routerId, dpnId, finalBgpVpnId, removeFlowInvTx);
}
}
if (!Objects.equals(original.getExtGwMacAddress(), update.getExtGwMacAddress())) {
NatUtil.installRouterGwFlows(txRunner, vpnManager, original, dpnId, NwConstants.DEL_FLOW);
NatUtil.installRouterGwFlows(txRunner, vpnManager, update, dpnId, NwConstants.ADD_FLOW);
}
//Check if the Update is on External IPs
LOG.debug("update : Checking if this is update on External IPs");
List<String> originalExternalIps = NatUtil.getIpsListFromExternalIps(original.getExternalIps());
List<String> updatedExternalIps = NatUtil.getIpsListFromExternalIps(update.getExternalIps());
//Check if the External IPs are added during the update.
Set<String> addedExternalIps = new HashSet<>(updatedExternalIps);
addedExternalIps.removeAll(originalExternalIps);
if (addedExternalIps.size() != 0) {
LOG.debug("update : Start processing of the External IPs addition during the update "
+ "operation");
vpnManager.addArpResponderFlowsToExternalNetworkIps(routerName, addedExternalIps,
update.getExtGwMacAddress(), dpnId,
update.getNetworkId());
for (String addedExternalIp : addedExternalIps) {
/*
1) Do nothing in the IntExtIp model.
2) Initialise the count of the added external IP to 0 in the ExternalCounter model.
*/
String[] externalIpParts = NatUtil.getExternalIpAndPrefix(addedExternalIp);
String externalIp = externalIpParts[0];
String externalIpPrefix = externalIpParts[1];
String externalpStr = externalIp + "/" + externalIpPrefix;
LOG.debug("update : Initialise the count mapping of the external IP {} for the "
+ "router ID {} in the ExternalIpsCounter model.",
externalpStr, routerId);
naptManager.initialiseNewExternalIpCounter(routerId, externalpStr);
}
LOG.debug(
"update : End processing of the External IPs addition during the update operation");
}
//Check if the External IPs are removed during the update.
Set<String> removedExternalIps = new HashSet<>(originalExternalIps);
removedExternalIps.removeAll(updatedExternalIps);
if (removedExternalIps.size() > 0) {
LOG.debug("update : Start processing of the External IPs removal during the update "
+ "operation");
vpnManager.removeArpResponderFlowsToExternalNetworkIps(routerName,
removedExternalIps, original.getExtGwMacAddress(),
dpnId, networkId);
for (String removedExternalIp : removedExternalIps) {
/*
1) Remove the mappings in the IntExt IP model which has external IP.
2) Remove the external IP in the ExternalCounter model.
3) For the corresponding subnet IDs whose external IP mapping was removed, allocate one of the
least loaded external IP.
Store the subnet IP and the reallocated external IP mapping in the IntExtIp model.
4) Increase the count of the allocated external IP by one.
5) Advertise to the BGP if external IP is allocated for the first time for the router
i.e. the route for the external IP is absent.
6) Remove the NAPT translation entries from Inbound and Outbound NAPT tables for
the removed external IPs and also from the model.
7) Advertise to the BGP for removing the route for the removed external IPs.
*/
String[] externalIpParts = NatUtil.getExternalIpAndPrefix(removedExternalIp);
String externalIp = externalIpParts[0];
String externalIpPrefix = externalIpParts[1];
String externalIpAddrStr = externalIp + "/" + externalIpPrefix;
LOG.debug("update : Clear the routes from the BGP and remove the FIB and TS "
+ "entries for removed external IP {}", externalIpAddrStr);
Uuid vpnUuId = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
String vpnName = "";
if (vpnUuId != null) {
vpnName = vpnUuId.getValue();
}
clrRtsFromBgpAndDelFibTs(dpnId, routerId, externalIpAddrStr, vpnName, networkId,
update.getExtGwMacAddress(), removeFlowInvTx);
LOG.debug("update : Remove the mappings in the IntExtIP model which has external IP.");
//Get the internal IPs which are associated to the removed external IPs
List<IpMap> ipMaps = naptManager.getIpMapList(dataBroker, routerId);
List<String> removedInternalIps = new ArrayList<>();
for (IpMap ipMap : ipMaps) {
if (ipMap.getExternalIp().equals(externalIpAddrStr)) {
removedInternalIps.add(ipMap.getInternalIp());
}
}
LOG.debug("update : Remove the mappings of the internal IPs from the IntExtIP model.");
for (String removedInternalIp : removedInternalIps) {
LOG.debug("update : Remove the IP mapping of the internal IP {} for the "
+ "router ID {} from the IntExtIP model",
removedInternalIp, routerId);
naptManager.removeFromIpMapDS(routerId, removedInternalIp);
}
LOG.debug("update : Remove the count mapping of the external IP {} for the "
+ "router ID {} from the ExternalIpsCounter model.",
externalIpAddrStr, routerId);
naptManager.removeExternalIpCounter(routerId, externalIpAddrStr);
LOG.debug("update : Allocate the least loaded external IPs to the subnets "
+ "whose external IPs were removed.");
for (String removedInternalIp : removedInternalIps) {
allocateExternalIp(dpnId, update, routerId, routerName, networkId,
removedInternalIp, writeFlowInvTx);
}
LOG.debug("update : Remove the NAPT translation entries from "
+ "Inbound and Outbound NAPT tables for the removed external IPs.");
//Get the internalIP and internal Port which were associated to the removed external IP.
List<Integer> externalPorts = new ArrayList<>();
Map<ProtocolTypes, List<String>> protoTypesIntIpPortsMap = new HashMap<>();
InstanceIdentifier<IpPortMapping> ipPortMappingId = InstanceIdentifier
.builder(IntextIpPortMap.class)
.child(IpPortMapping.class, new IpPortMappingKey(routerId)).build();
Optional<IpPortMapping> ipPortMapping;
try {
ipPortMapping = SingleTransactionDataBroker
.syncReadOptional(dataBroker,
LogicalDatastoreType.CONFIGURATION, ipPortMappingId);
} catch (ReadFailedException e) {
LOG.error("Failed to read ipPortMapping for router id {}", routerId, e);
ipPortMapping = Optional.absent();
}
if (ipPortMapping.isPresent()) {
for (IntextIpProtocolType intextIpProtocolType : requireNonNullElse(
ipPortMapping.get().getIntextIpProtocolType(),
Collections.<IntextIpProtocolType>emptyList())) {
ProtocolTypes protoType = intextIpProtocolType.getProtocol();
for (IpPortMap ipPortMap : requireNonNullElse(intextIpProtocolType.getIpPortMap(),
Collections.<IpPortMap>emptyList())) {
IpPortExternal ipPortExternal = ipPortMap.getIpPortExternal();
if (ipPortExternal.getIpAddress().equals(externalIp)) {
externalPorts.add(ipPortExternal.getPortNum());
List<String> removedInternalIpPorts =
protoTypesIntIpPortsMap.get(protoType);
if (removedInternalIpPorts != null) {
removedInternalIpPorts.add(ipPortMap.getIpPortInternal());
protoTypesIntIpPortsMap.put(protoType, removedInternalIpPorts);
} else {
removedInternalIpPorts = new ArrayList<>();
removedInternalIpPorts.add(ipPortMap.getIpPortInternal());
protoTypesIntIpPortsMap.put(protoType, removedInternalIpPorts);
}
}
}
}
}
//Remove the IP port map from the intext-ip-port-map model, which were containing
// the removed external IP.
Set<Map.Entry<ProtocolTypes, List<String>>> protoTypesIntIpPorts =
protoTypesIntIpPortsMap.entrySet();
Map<String, List<String>> internalIpPortMap = new HashMap<>();
for (Map.Entry protoTypesIntIpPort : protoTypesIntIpPorts) {
ProtocolTypes protocolType = (ProtocolTypes) protoTypesIntIpPort.getKey();
List<String> removedInternalIpPorts = (List<String>) protoTypesIntIpPort.getValue();
for (String removedInternalIpPort : removedInternalIpPorts) {
// Remove the IP port map from the intext-ip-port-map model,
// which were containing the removed external IP
naptManager.removeFromIpPortMapDS(routerId, removedInternalIpPort,
protocolType);
//Remove the IP port incomint packer map.
naptPacketInHandler.removeIncomingPacketMap(
routerId + NatConstants.COLON_SEPARATOR + removedInternalIpPort);
String[] removedInternalIpPortParts = removedInternalIpPort
.split(NatConstants.COLON_SEPARATOR);
if (removedInternalIpPortParts.length == 2) {
String removedInternalIp = removedInternalIpPortParts[0];
String removedInternalPort = removedInternalIpPortParts[1];
List<String> removedInternalPortsList =
internalIpPortMap.get(removedInternalPort);
if (removedInternalPortsList != null) {
removedInternalPortsList.add(removedInternalPort);
internalIpPortMap.put(removedInternalIp, removedInternalPortsList);
} else {
removedInternalPortsList = new ArrayList<>();
removedInternalPortsList.add(removedInternalPort);
internalIpPortMap.put(removedInternalIp, removedInternalPortsList);
}
}
}
}
// Delete the entry from SnatIntIpPortMap DS
Set<String> internalIps = internalIpPortMap.keySet();
for (String internalIp : internalIps) {
LOG.debug("update : Removing IpPort having the internal IP {} from the "
+ "model SnatIntIpPortMap", internalIp);
naptManager.removeFromSnatIpPortDS(routerId, internalIp);
}
naptManager.removeNaptPortPool(externalIp);
LOG.debug("update : Remove the NAPT translation entries from Inbound NAPT tables for "
+ "the removed external IP {}", externalIp);
for (Integer externalPort : externalPorts) {
//Remove the NAPT translation entries from Inbound NAPT table
naptEventHandler.removeNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE,
routerId, externalIp, externalPort);
}
Set<Map.Entry<String, List<String>>> internalIpPorts = internalIpPortMap.entrySet();
for (Map.Entry<String, List<String>> internalIpPort : internalIpPorts) {
String internalIp = internalIpPort.getKey();
LOG.debug("update : Remove the NAPT translation entries from Outbound NAPT tables "
+ "for the removed internal IP {}", internalIp);
List<String> internalPorts = internalIpPort.getValue();
for (String internalPort : internalPorts) {
//Remove the NAPT translation entries from Outbound NAPT table
naptPacketInHandler.removeIncomingPacketMap(
routerId + NatConstants.COLON_SEPARATOR + internalIp
+ NatConstants.COLON_SEPARATOR + internalPort);
naptEventHandler.removeNatFlows(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
routerId, internalIp, Integer.parseInt(internalPort));
}
}
}
LOG.debug(
"update : End processing of the External IPs removal during the update operation");
}
//Check if its Update on subnets
LOG.debug("update : Checking if this is update on subnets");
List<Uuid> originalSubnetIds = original.getSubnetIds();
List<Uuid> updatedSubnetIds = update.getSubnetIds();
Set<Uuid> addedSubnetIds =
updatedSubnetIds != null ? new HashSet<>(updatedSubnetIds) : new HashSet<>();
if (originalSubnetIds != null) {
addedSubnetIds.removeAll(originalSubnetIds);
}
//Check if the Subnet IDs are added during the update.
if (addedSubnetIds.size() != 0) {
LOG.debug(
"update : Start processing of the Subnet IDs addition during the update operation");
for (Uuid addedSubnetId : addedSubnetIds) {
/*
1) Select the least loaded external IP for the subnet and store the mapping of the
subnet IP and the external IP in the IntExtIp model.
2) Increase the count of the selected external IP by one.
3) Advertise to the BGP if external IP is allocated for the first time for the
router i.e. the route for the external IP is absent.
*/
String subnetIp = NatUtil.getSubnetIp(dataBroker, addedSubnetId);
if (subnetIp != null) {
allocateExternalIp(dpnId, update, routerId, routerName, networkId, subnetIp,
writeFlowInvTx);
}
}
LOG.debug("update : End processing of the Subnet IDs addition during the update operation");
}
//Check if the Subnet IDs are removed during the update.
Set<Uuid> removedSubnetIds = new HashSet<>(originalSubnetIds);
removedSubnetIds.removeAll(updatedSubnetIds);
if (removedSubnetIds.size() != 0) {
LOG.debug(
"update : Start processing of the Subnet IDs removal during the update operation");
for (Uuid removedSubnetId : removedSubnetIds) {
String[] subnetAddr = NatUtil.getSubnetIpAndPrefix(dataBroker, removedSubnetId);
if (subnetAddr != null) {
/*
1) Remove the subnet IP and the external IP in the IntExtIp map
2) Decrease the count of the coresponding external IP by one.
3) Advertise to the BGP for removing the routes of the corresponding external
IP if its not allocated to any other internal IP.
*/
String externalIp = naptManager.getExternalIpAllocatedForSubnet(routerId,
subnetAddr[0] + "/" + subnetAddr[1]);
if (externalIp == null) {
LOG.error("update : No mapping found for router ID {} and internal IP {}",
routerId, subnetAddr[0]);
return;
}
naptManager.updateCounter(routerId, externalIp, false);
// Traverse entire model of external-ip counter whether external ip is not
// used by any other internal ip in any router
if (!isExternalIpAllocated(externalIp)) {
LOG.debug("update : external ip is not allocated to any other "
+ "internal IP so proceeding to remove routes");
clrRtsFromBgpAndDelFibTs(dpnId, routerId, networkId,
Collections.singleton(externalIp), null, update.getExtGwMacAddress(),
removeFlowInvTx);
LOG.debug("update : Successfully removed fib entries in switch {} for "
+ "router {} with networkId {} and externalIp {}",
dpnId, routerId, networkId, externalIp);
}
LOG.debug("update : Remove the IP mapping for the router ID {} and "
+ "internal IP {} external IP {}", routerId, subnetAddr[0], externalIp);
naptManager.removeIntExtIpMapDS(routerId, subnetAddr[0] + "/" + subnetAddr[1]);
}
}
LOG.debug("update : End processing of the Subnet IDs removal during the update operation");
}
}));
}));
return futures;
}, NatConstants.NAT_DJC_MAX_RETRIES);
}
private boolean isExternalIpAllocated(String externalIp) {
InstanceIdentifier<ExternalIpsCounter> id = InstanceIdentifier.builder(ExternalIpsCounter.class).build();
Optional<ExternalIpsCounter> externalCountersData;
try {
externalCountersData = SingleTransactionDataBroker.syncReadOptional(dataBroker,
LogicalDatastoreType.OPERATIONAL, id);
} catch (ReadFailedException e) {
LOG.error("Failed to read external counters data for ExternalIp {}", externalIp, e);
externalCountersData = Optional.absent();
}
if (externalCountersData.isPresent()) {
ExternalIpsCounter externalIpsCounters = externalCountersData.get();
for (ExternalCounters ext : requireNonNullElse(externalIpsCounters.getExternalCounters(),
Collections.<ExternalCounters>emptyList())) {
for (ExternalIpCounter externalIpCount : requireNonNullElse(ext.getExternalIpCounter(),
Collections.<ExternalIpCounter>emptyList())) {
if (externalIpCount.getExternalIp().equals(externalIp)) {
if (externalIpCount.getCounter() != 0) {
return true;
}
break;
}
}
}
}
return false;
}
private void allocateExternalIp(BigInteger dpnId, Routers router, long routerId, String routerName,
Uuid networkId, String subnetIp, TypedWriteTransaction<Configuration> writeFlowInvTx) {
String[] subnetIpParts = NatUtil.getSubnetIpAndPrefix(subnetIp);
try {
InetAddress address = InetAddress.getByName(subnetIpParts[0]);
if (address instanceof Inet6Address) {
LOG.debug("allocateExternalIp : Skipping ipv6 address {} for the router {}.", address, routerName);
return;
}
} catch (UnknownHostException e) {
LOG.error("allocateExternalIp : Invalid ip address {}", subnetIpParts[0], e);
return;
}
String leastLoadedExtIpAddr = NatUtil.getLeastLoadedExternalIp(dataBroker, routerId);
if (leastLoadedExtIpAddr != null) {
String[] externalIpParts = NatUtil.getExternalIpAndPrefix(leastLoadedExtIpAddr);
String leastLoadedExtIp = externalIpParts[0];
String leastLoadedExtIpPrefix = externalIpParts[1];
IPAddress externalIpAddr = new IPAddress(leastLoadedExtIp, Integer.parseInt(leastLoadedExtIpPrefix));
subnetIp = subnetIpParts[0];
String subnetIpPrefix = subnetIpParts[1];
IPAddress subnetIpAddr = new IPAddress(subnetIp, Integer.parseInt(subnetIpPrefix));
LOG.debug("allocateExternalIp : Add the IP mapping for the router ID {} and internal "
+ "IP {} and prefix {} -> external IP {} and prefix {}",
routerId, subnetIp, subnetIpPrefix, leastLoadedExtIp, leastLoadedExtIpPrefix);
naptManager.registerMapping(routerId, subnetIpAddr, externalIpAddr);
// Check if external IP is already assigned a route. (i.e. External IP is previously
// allocated to any of the subnets)
// If external IP is already assigned a route, (, do not re-advertise to the BGP
String leastLoadedExtIpAddrStr = leastLoadedExtIp + "/" + leastLoadedExtIpPrefix;
Long label = checkExternalIpLabel(routerId, leastLoadedExtIpAddrStr);
if (label != null) {
//update
String internalIp = subnetIpParts[0] + "/" + subnetIpParts[1];
IpMapKey ipMapKey = new IpMapKey(internalIp);
LOG.debug("allocateExternalIp : Setting label {} for internalIp {} and externalIp {}",
label, internalIp, leastLoadedExtIpAddrStr);
IpMap newIpm = new IpMapBuilder().withKey(ipMapKey).setInternalIp(internalIp)
.setExternalIp(leastLoadedExtIpAddrStr).setLabel(label).build();
MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL,
naptManager.getIpMapIdentifier(routerId, internalIp), newIpm);
return;
}
// Re-advertise to the BGP for the external IP, which is allocated to the subnet
// for the first time and hence not having a route.
//Get the VPN Name using the network ID
final String vpnName = NatUtil.getAssociatedVPN(dataBroker, networkId);
if (vpnName != null) {
LOG.debug("allocateExternalIp : Retrieved vpnName {} for networkId {}", vpnName, networkId);
if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
LOG.debug("allocateExternalIp : Best effort for getting primary napt switch when router i/f are"
+ "added after gateway-set");
dpnId = NatUtil.getPrimaryNaptfromRouterId(dataBroker, routerId);
if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
LOG.error("allocateExternalIp : dpnId is null or Zero for the router {}", routerName);
return;
}
}
advToBgpAndInstallFibAndTsFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, vpnName, routerId, routerName,
leastLoadedExtIp + "/" + leastLoadedExtIpPrefix, networkId, router,
writeFlowInvTx);
}
}
}
@Nullable
protected Long checkExternalIpLabel(long routerId, String externalIp) {
List<IpMap> ipMaps = naptManager.getIpMapList(dataBroker, routerId);
for (IpMap ipMap : ipMaps) {
if (ipMap.getExternalIp().equals(externalIp)) {
if (ipMap.getLabel() != null) {
return ipMap.getLabel();
}
}
}
LOG.error("checkExternalIpLabel : no ipMaps found for routerID:{} and externalIP:{}", routerId, externalIp);
return null;
}
@Override
protected void remove(InstanceIdentifier<Routers> identifier, Routers router) {
LOG.trace("remove : Router delete method");
/*
ROUTER DELETE SCENARIO
1) Get the router ID from the event.
2) Build the cookie information from the router ID.
3) Get the primary and secondary switch DPN IDs using the router ID from the model.
4) Build the flow with the cookie value.
5) Delete the flows which matches the cookie information from the NAPT outbound, inbound tables.
6) Remove the flows from the other switches which points to the primary and secondary
switches for the flows related the router ID.
7) Get the list of external IP address maintained for the router ID.
8) Use the NaptMananager removeMapping API to remove the list of IP addresses maintained.
9) Withdraw the corresponding routes from the BGP.
*/
if (identifier == null || router == null) {
LOG.error("remove : returning without processing since routers is null");
return;
}
String routerName = router.getRouterName();
coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + router.key(),
() -> Collections.singletonList(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, tx -> {
LOG.info("remove : Removing default NAT route from FIB on all dpns part of router {} ",
routerName);
Long routerId = NatUtil.getVpnId(dataBroker, routerName);
if (routerId == NatConstants.INVALID_ID) {
LOG.error("remove : Remove external router event - Invalid routerId for routerName {}",
routerName);
return;
}
long bgpVpnId = NatConstants.INVALID_ID;
Uuid bgpVpnUuid = NatUtil.getVpnForRouter(dataBroker, routerName);
if (bgpVpnUuid != null) {
bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnUuid.getValue());
}
addOrDelDefFibRouteToSNAT(routerName, routerId, bgpVpnId, bgpVpnUuid, false,
tx);
Uuid networkUuid = router.getNetworkId();
BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerName);
if (primarySwitchId == null || primarySwitchId.equals(BigInteger.ZERO)) {
// No NAPT switch for external router, probably because the router is not attached to
// any
// internal networks
LOG.debug(
"No NAPT switch for router {}, check if router is attached to any internal "
+ "network",
routerName);
return;
} else {
Collection<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerId);
handleDisableSnat(router, networkUuid, externalIps, true, null, primarySwitchId,
routerId, tx);
}
natOverVxlanUtil.releaseVNI(routerName);
})), NatConstants.NAT_DJC_MAX_RETRIES);
}
public void handleDisableSnat(Routers router, Uuid networkUuid, @Nonnull Collection<String> externalIps,
boolean routerFlag, @Nullable String vpnName, BigInteger naptSwitchDpnId,
long routerId, TypedReadWriteTransaction<Configuration> removeFlowInvTx) {
LOG.info("handleDisableSnat : Entry");
String routerName = router.getRouterName();
try {
if (routerFlag) {
removeNaptSwitch(routerName);
} else {
updateNaptSwitch(routerName, BigInteger.ZERO);
}
LOG.debug("handleDisableSnat : Remove the ExternalCounter model for the router ID {}", routerId);
naptManager.removeExternalCounter(routerId);
LOG.debug("handleDisableSnat : got primarySwitch as dpnId {}", naptSwitchDpnId);
if (naptSwitchDpnId == null || naptSwitchDpnId.equals(BigInteger.ZERO)) {
LOG.error("handleDisableSnat : Unable to retrieve the primary NAPT switch for the "
+ "router ID {} from RouterNaptSwitch model", routerId);
return;
}
ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName,
networkUuid);
if (extNwProvType == null) {
LOG.error("handleDisableSnat : External Network Provider Type missing");
return;
}
Collection<Uuid> externalSubnetList = NatUtil.getExternalSubnetIdsFromExternalIps(router.getExternalIps());
removeNaptFlowsFromActiveSwitch(routerId, routerName, naptSwitchDpnId, networkUuid, vpnName, externalIps,
externalSubnetList, removeFlowInvTx, extNwProvType);
removeFlowsFromNonActiveSwitches(routerId, routerName, naptSwitchDpnId, removeFlowInvTx);
String externalSubnetVpn = null;
for (Uuid externalSubnetId : externalSubnetList) {
Optional<Subnets> externalSubnet = NatUtil.getOptionalExternalSubnets(dataBroker, externalSubnetId);
// externalSubnet data model will exist for FLAT/VLAN external netowrk UCs.
if (externalSubnet.isPresent()) {
externalSubnetVpn = externalSubnetId.getValue();
clrRtsFromBgpAndDelFibTs(naptSwitchDpnId, routerId, networkUuid, externalIps, externalSubnetVpn,
router.getExtGwMacAddress(), removeFlowInvTx);
}
}
if (externalSubnetVpn == null) {
clrRtsFromBgpAndDelFibTs(naptSwitchDpnId, routerId, networkUuid, externalIps, vpnName,
router.getExtGwMacAddress(), removeFlowInvTx);
}
// Use the NaptMananager removeMapping API to remove the entire list of IP addresses maintained
// for the router ID.
LOG.debug("handleDisableSnat : Remove the Internal to external IP address maintained for the "
+ "router ID {} in the DS", routerId);
naptManager.removeMapping(routerId);
} catch (InterruptedException | ExecutionException e) {
LOG.error("handleDisableSnat : Exception while handling disableSNAT for router :{}", routerName, e);
}
LOG.info("handleDisableSnat : Exit");
}
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public void handleDisableSnatInternetVpn(String routerName, long routerId, Uuid networkUuid,
@Nonnull Collection<String> externalIps,
String vpnId, TypedReadWriteTransaction<Configuration> writeFlowInvTx) {
LOG.debug("handleDisableSnatInternetVpn: Started to process handle disable snat for router {} "
+ "with internet vpn {}", routerName, vpnId);
try {
BigInteger naptSwitchDpnId = null;
InstanceIdentifier<RouterToNaptSwitch> routerToNaptSwitch =
NatUtil.buildNaptSwitchRouterIdentifier(routerName);
Optional<RouterToNaptSwitch> rtrToNapt;
try {
rtrToNapt = SingleTransactionDataBroker.syncReadOptional(dataBroker,
LogicalDatastoreType.CONFIGURATION, routerToNaptSwitch);
} catch (ReadFailedException e) {
LOG.error("Failed to read NAPT switch for router {}", routerName, e);
rtrToNapt = Optional.absent();
}
if (rtrToNapt.isPresent()) {
naptSwitchDpnId = rtrToNapt.get().getPrimarySwitchId();
}
LOG.debug("handleDisableSnatInternetVpn : got primarySwitch as dpnId{} ", naptSwitchDpnId);
removeNaptFlowsFromActiveSwitchInternetVpn(routerId, routerName, naptSwitchDpnId, networkUuid, vpnId,
writeFlowInvTx);
try {
String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterName(dataBroker, routerName);
if (extGwMacAddress != null) {
LOG.debug("handleDisableSnatInternetVpn : External Gateway MAC address {} found for "
+ "External Router ID {}", extGwMacAddress, routerId);
} else {
LOG.error("handleDisableSnatInternetVpn : No External Gateway MAC address found for "
+ "External Router ID {}", routerId);
return;
}
clrRtsFromBgpAndDelFibTs(naptSwitchDpnId, routerId, networkUuid, externalIps, vpnId, extGwMacAddress,
writeFlowInvTx);
} catch (Exception ex) {
LOG.error("handleDisableSnatInternetVpn : Failed to remove fib entries for routerId {} "
+ "in naptSwitchDpnId {}", routerId, naptSwitchDpnId, ex);
}
natOverVxlanUtil.releaseVNI(vpnId);
} catch (InterruptedException | ExecutionException e) {
LOG.error("handleDisableSnatInternetVpn: Exception while handling disableSNATInternetVpn for router {} "
+ "with internet vpn {}", routerName, vpnId, e);
}
LOG.debug("handleDisableSnatInternetVpn: Processed handle disable snat for router {} with internet vpn {}",
routerName, vpnId);
}
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public void updateNaptSwitch(String routerName, BigInteger naptSwitchId) {
RouterToNaptSwitch naptSwitch = new RouterToNaptSwitchBuilder().withKey(new RouterToNaptSwitchKey(routerName))
.setPrimarySwitchId(naptSwitchId).build();
try {
MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
NatUtil.buildNaptSwitchRouterIdentifier(routerName), naptSwitch);
} catch (Exception ex) {
LOG.error("updateNaptSwitch : Failed to write naptSwitch {} for router {} in ds",
naptSwitchId, routerName);
}
LOG.debug("updateNaptSwitch : Successfully updated naptSwitch {} for router {} in ds",
naptSwitchId, routerName);
}
protected void removeNaptSwitch(String routerName) {
// Remove router and switch from model
InstanceIdentifier<RouterToNaptSwitch> id =
InstanceIdentifier.builder(NaptSwitches.class)
.child(RouterToNaptSwitch.class, new RouterToNaptSwitchKey(routerName)).build();
LOG.debug("removeNaptSwitch : Removing NaptSwitch and Router for the router {} from datastore", routerName);
MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, id);
//Release allocated router_lPort_tag from the ID Manager if Router is on L3VPNOverVxlan
NatEvpnUtil.releaseLPortTagForRouter(dataBroker, idManager, routerName);
}
public void removeNaptFlowsFromActiveSwitch(long routerId, String routerName,
BigInteger dpnId, Uuid networkId, String vpnName,
@Nonnull Collection<String> externalIps,
Collection<Uuid> externalSubnetList,
TypedReadWriteTransaction<Configuration> confTx,
ProviderTypes extNwProvType)
throws InterruptedException, ExecutionException {
LOG.debug("removeNaptFlowsFromActiveSwitch : Remove NAPT flows from Active switch");
BigInteger cookieSnatFlow = NatUtil.getCookieNaptFlow(routerId);
//Remove the PSNAT entry which forwards the packet to Outbound NAPT Table (For the
// traffic which comes from the VMs of the NAPT switches)
String preSnatFlowRef = getFlowRefSnat(dpnId, NwConstants.PSNAT_TABLE, routerName);
FlowEntity preSnatFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.PSNAT_TABLE, preSnatFlowRef);
LOG.info(
"removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active switch with the DPN ID {} "
+ "and router ID {}", NwConstants.PSNAT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(confTx, preSnatFlowEntity);
//Remove the Terminating Service table entry which forwards the packet to Outbound NAPT Table (For the
// traffic which comes from the VMs of the non NAPT switches)
long tunnelId = NatUtil.getTunnelIdForNonNaptToNaptFlow(dataBroker, natOverVxlanUtil,
elanManager, idManager, routerId, routerName);
String tsFlowRef = getFlowRefTs(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, tunnelId);
FlowEntity tsNatFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, tsFlowRef);
LOG.info(
"removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active switch with the DPN ID {} "
+ "and router ID {}", NwConstants.INTERNAL_TUNNEL_TABLE, dpnId, routerId);
mdsalManager.removeFlow(confTx, tsNatFlowEntity);
//Remove the flow table 25->44 from NAPT Switch
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
NatUtil.removePreDnatToSnatTableEntry(confTx, mdsalManager, dpnId);
}
//Remove the Outbound flow entry which forwards the packet to FIB Table
LOG.info(
"removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active switch with the DPN ID {}"
+ " and router ID {}", NwConstants.OUTBOUND_NAPT_TABLE, dpnId, routerId);
String outboundTcpNatFlowRef = getFlowRefOutbound(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId,
NwConstants.IP_PROT_TCP);
FlowEntity outboundTcpNatFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
outboundTcpNatFlowRef);
mdsalManager.removeFlow(confTx, outboundTcpNatFlowEntity);
String outboundUdpNatFlowRef = getFlowRefOutbound(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId,
NwConstants.IP_PROT_UDP);
FlowEntity outboundUdpNatFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
outboundUdpNatFlowRef);
mdsalManager.removeFlow(confTx, outboundUdpNatFlowEntity);
String icmpDropFlowRef = getFlowRefOutbound(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId,
NwConstants.IP_PROT_ICMP);
FlowEntity icmpDropFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
icmpDropFlowRef);
mdsalManager.removeFlow(confTx, icmpDropFlowEntity);
boolean lastRouterOnExternalNetwork =
!NatUtil.checkForRoutersWithSameExtNetAndNaptSwitch(dataBroker, networkId, routerName, dpnId);
if (lastRouterOnExternalNetwork) {
removeNaptFibExternalOutputFlows(routerId, dpnId, networkId, externalIps, confTx);
}
//Remove the NAPT PFIB TABLE (47->21) which forwards the incoming packet to FIB Table matching on the
// External Subnet Vpn Id.
for (Uuid externalSubnetId : externalSubnetList) {
long subnetVpnId = NatUtil.getVpnId(dataBroker, externalSubnetId.getValue());
if (subnetVpnId != -1 && !NatUtil.checkForRoutersWithSameExtSubnetAndNaptSwitch(
dataBroker, externalSubnetId, routerName, dpnId)) {
String natPfibSubnetFlowRef = getFlowRefTs(dpnId, NwConstants.NAPT_PFIB_TABLE, subnetVpnId);
FlowEntity natPfibFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.NAPT_PFIB_TABLE,
natPfibSubnetFlowRef);
mdsalManager.removeFlow(confTx, natPfibFlowEntity);
LOG.debug("removeNaptFlowsFromActiveSwitch : Removed the flow in table {} with external subnet "
+ "Vpn Id {} as metadata on Napt Switch {}", NwConstants.NAPT_PFIB_TABLE,
subnetVpnId, dpnId);
}
}
//Remove the NAPT PFIB TABLE which forwards the incoming packet to FIB Table matching on the router ID.
String natPfibFlowRef = getFlowRefTs(dpnId, NwConstants.NAPT_PFIB_TABLE, routerId);
FlowEntity natPfibFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.NAPT_PFIB_TABLE, natPfibFlowRef);
LOG.info(
"removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active switch with the DPN ID {} "
+ "and router ID {}", NwConstants.NAPT_PFIB_TABLE, dpnId, routerId);
mdsalManager.removeFlow(confTx, natPfibFlowEntity);
if (lastRouterOnExternalNetwork) {
// Long vpnId = NatUtil.getVpnId(dataBroker, routerId);
// - This does not work since ext-routers is deleted already - no network info
//Get the VPN ID from the ExternalNetworks model
long vpnId = -1;
if (vpnName == null || vpnName.isEmpty()) {
// ie called from router delete cases
Uuid vpnUuid = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
LOG.debug("removeNaptFlowsFromActiveSwitch : vpnUuid is {}", vpnUuid);
if (vpnUuid != null) {
vpnId = NatUtil.getVpnId(dataBroker, vpnUuid.getValue());
LOG.debug("removeNaptFlowsFromActiveSwitch : vpnId {} for external network {} router delete "
+ "or disableSNAT scenario", vpnId, networkId);
}
} else {
// ie called from disassociate vpn case
LOG.debug("removeNaptFlowsFromActiveSwitch : This is disassociate nw with vpn case with vpnName {}",
vpnName);
vpnId = NatUtil.getVpnId(dataBroker, vpnName);
LOG.debug("removeNaptFlowsFromActiveSwitch : vpnId for disassociate nw with vpn scenario {}",
vpnId);
}
if (vpnId != NatConstants.INVALID_ID) {
//Remove the NAPT PFIB TABLE which forwards the outgoing packet to FIB Table matching on the VPN ID.
String natPfibVpnFlowRef = getFlowRefTs(dpnId, NwConstants.NAPT_PFIB_TABLE, vpnId);
FlowEntity natPfibVpnFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.NAPT_PFIB_TABLE, natPfibVpnFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitch : Remove the flow in {} for the active switch with the "
+ "DPN ID {} and VPN ID {}", NwConstants.NAPT_PFIB_TABLE, dpnId, vpnId);
mdsalManager.removeFlow(confTx, natPfibVpnFlowEntity);
}
}
//For the router ID get the internal IP , internal port and the corresponding external IP and external Port.
IpPortMapping ipPortMapping = NatUtil.getIportMapping(dataBroker, routerId);
if (ipPortMapping == null) {
LOG.error("removeNaptFlowsFromActiveSwitch : Unable to retrieve the IpPortMapping");
return;
}
for (IntextIpProtocolType intextIpProtocolType : requireNonNullElse(ipPortMapping.getIntextIpProtocolType(),
Collections.<IntextIpProtocolType>emptyList())) {
for (IpPortMap ipPortMap : requireNonNullElse(intextIpProtocolType.getIpPortMap(),
Collections.<IpPortMap>emptyList())) {
String ipPortInternal = ipPortMap.getIpPortInternal();
String[] ipPortParts = ipPortInternal.split(":");
if (ipPortParts.length != 2) {
LOG.error("removeNaptFlowsFromActiveSwitch : Unable to retrieve the Internal IP and port");
return;
}
String internalIp = ipPortParts[0];
String internalPort = ipPortParts[1];
//Build the flow for the outbound NAPT table
naptPacketInHandler.removeIncomingPacketMap(routerId + NatConstants.COLON_SEPARATOR + internalIp
+ NatConstants.COLON_SEPARATOR + internalPort);
String switchFlowRef = NatUtil.getNaptFlowRef(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
String.valueOf(routerId), internalIp, Integer.parseInt(internalPort));
FlowEntity outboundNaptFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active switch "
+ "with the DPN ID {} and router ID {}", NwConstants.OUTBOUND_NAPT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(confTx, outboundNaptFlowEntity);
IpPortExternal ipPortExternal = ipPortMap.getIpPortExternal();
String externalIp = ipPortExternal.getIpAddress();
int externalPort = ipPortExternal.getPortNum();
//Build the flow for the inbound NAPT table
switchFlowRef = NatUtil.getNaptFlowRef(dpnId, NwConstants.INBOUND_NAPT_TABLE,
String.valueOf(routerId), externalIp, externalPort);
FlowEntity inboundNaptFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.INBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitch : Remove the flow in the {} for the active active switch "
+ "with the DPN ID {} and router ID {}", NwConstants.INBOUND_NAPT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(confTx, inboundNaptFlowEntity);
}
}
}
protected void removeNaptFibExternalOutputFlows(long routerId, BigInteger dpnId, Uuid networkId,
@Nonnull Collection<String> externalIps,
TypedReadWriteTransaction<Configuration> writeFlowInvTx)
throws ExecutionException, InterruptedException {
long extVpnId = NatConstants.INVALID_ID;
if (networkId != null) {
Uuid vpnUuid = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
if (vpnUuid != null) {
extVpnId = NatUtil.getVpnId(dataBroker, vpnUuid.getValue());
} else {
LOG.debug("removeNaptFibExternalOutputFlows : vpnUuid is null");
}
} else {
LOG.debug("removeNaptFibExternalOutputFlows : networkId is null");
extVpnId = NatUtil.getNetworkVpnIdFromRouterId(dataBroker, routerId);
}
if (extVpnId == NatConstants.INVALID_ID) {
LOG.warn("removeNaptFibExternalOutputFlows : extVpnId not found for routerId {}", routerId);
extVpnId = routerId;
}
for (String ip : externalIps) {
String extIp = removeMaskFromIp(ip);
String naptFlowRef = getFlowRefNaptPreFib(dpnId, NwConstants.NAPT_PFIB_TABLE, extVpnId);
LOG.info("removeNaptFlowsFromActiveSwitch : Remove the flow in table {} for the active switch"
+ " with the DPN ID {} and router ID {} and IP {} flowRef {}",
NwConstants.NAPT_PFIB_TABLE, dpnId, routerId, extIp, naptFlowRef);
FlowEntity natPfibVpnFlowEntity = NatUtil.buildFlowEntity(dpnId, NwConstants.NAPT_PFIB_TABLE, naptFlowRef);
mdsalManager.removeFlow(writeFlowInvTx, natPfibVpnFlowEntity);
}
}
private String removeMaskFromIp(String ip) {
if (ip != null && !ip.trim().isEmpty()) {
return ip.split("/")[0];
}
return ip;
}
public void removeNaptFlowsFromActiveSwitchInternetVpn(long routerId, String routerName,
BigInteger dpnId, Uuid networkId, String vpnName,
TypedReadWriteTransaction<Configuration> writeFlowInvTx)
throws ExecutionException, InterruptedException {
LOG.debug("removeNaptFlowsFromActiveSwitchInternetVpn : Remove NAPT flows from Active switch Internet Vpn");
BigInteger cookieSnatFlow = NatUtil.getCookieNaptFlow(routerId);
//Remove the NAPT PFIB TABLE entry
long vpnId = -1;
if (vpnName != null) {
// ie called from disassociate vpn case
LOG.debug("removeNaptFlowsFromActiveSwitchInternetVpn : This is disassociate nw with vpn case "
+ "with vpnName {}", vpnName);
vpnId = NatUtil.getVpnId(dataBroker, vpnName);
LOG.debug("removeNaptFlowsFromActiveSwitchInternetVpn : vpnId for disassociate nw with vpn scenario {}",
vpnId);
}
if (vpnId != NatConstants.INVALID_ID && !NatUtil.checkForRoutersWithSameExtNetAndNaptSwitch(dataBroker,
networkId, routerName, dpnId)) {
//Remove the NAPT PFIB TABLE which forwards the outgoing packet to FIB Table matching on the VPN ID.
String natPfibVpnFlowRef = getFlowRefTs(dpnId, NwConstants.NAPT_PFIB_TABLE, vpnId);
FlowEntity natPfibVpnFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.NAPT_PFIB_TABLE, natPfibVpnFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitchInternetVpn : Remove the flow in the {} for the active switch "
+ "with the DPN ID {} and VPN ID {}", NwConstants.NAPT_PFIB_TABLE, dpnId, vpnId);
mdsalManager.removeFlow(writeFlowInvTx, natPfibVpnFlowEntity);
// Remove IP-PORT active NAPT entries and release port from IdManager
// For the router ID get the internal IP , internal port and the corresponding
// external IP and external Port.
IpPortMapping ipPortMapping = NatUtil.getIportMapping(dataBroker, routerId);
if (ipPortMapping == null) {
LOG.error("removeNaptFlowsFromActiveSwitchInternetVpn : Unable to retrieve the IpPortMapping");
return;
}
for (IntextIpProtocolType intextIpProtocolType : requireNonNullElse(ipPortMapping.getIntextIpProtocolType(),
Collections.<IntextIpProtocolType>emptyList())) {
for (IpPortMap ipPortMap : requireNonNullElse(intextIpProtocolType.getIpPortMap(),
Collections.<IpPortMap>emptyList())) {
String ipPortInternal = ipPortMap.getIpPortInternal();
String[] ipPortParts = ipPortInternal.split(":");
if (ipPortParts.length != 2) {
LOG.error("removeNaptFlowsFromActiveSwitchInternetVpn : Unable to retrieve the Internal IP "
+ "and port");
return;
}
String internalIp = ipPortParts[0];
String internalPort = ipPortParts[1];
//Build the flow for the outbound NAPT table
naptPacketInHandler.removeIncomingPacketMap(routerId + NatConstants.COLON_SEPARATOR + internalIp
+ NatConstants.COLON_SEPARATOR + internalPort);
String switchFlowRef = NatUtil.getNaptFlowRef(dpnId, NwConstants.OUTBOUND_NAPT_TABLE,
String.valueOf(routerId), internalIp, Integer.parseInt(internalPort));
FlowEntity outboundNaptFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitchInternetVpn : Remove the flow in the {} for the "
+ "active switch with the DPN ID {} and router ID {}",
NwConstants.OUTBOUND_NAPT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(writeFlowInvTx, outboundNaptFlowEntity);
IpPortExternal ipPortExternal = ipPortMap.getIpPortExternal();
String externalIp = ipPortExternal.getIpAddress();
int externalPort = ipPortExternal.getPortNum();
//Build the flow for the inbound NAPT table
switchFlowRef = NatUtil.getNaptFlowRef(dpnId, NwConstants.INBOUND_NAPT_TABLE,
String.valueOf(routerId), externalIp, externalPort);
FlowEntity inboundNaptFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.INBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
LOG.info("removeNaptFlowsFromActiveSwitchInternetVpn : Remove the flow in the {} for the "
+ "active active switch with the DPN ID {} and router ID {}",
NwConstants.INBOUND_NAPT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(writeFlowInvTx, inboundNaptFlowEntity);
// Finally release port from idmanager
String internalIpPort = internalIp + ":" + internalPort;
naptManager.removePortFromPool(internalIpPort, externalIp);
//Remove sessions from models
naptManager.removeIpPortMappingForRouterID(routerId);
naptManager.removeIntIpPortMappingForRouterID(routerId);
}
}
} else {
LOG.error("removeNaptFlowsFromActiveSwitchInternetVpn : Invalid vpnId {}", vpnId);
}
}
public void removeFlowsFromNonActiveSwitches(long routerId, String routerName,
BigInteger naptSwitchDpnId, TypedReadWriteTransaction<Configuration> removeFlowInvTx)
throws ExecutionException, InterruptedException {
LOG.debug("removeFlowsFromNonActiveSwitches : Remove NAPT related flows from non active switches");
// Remove the flows from the other switches which points to the primary and secondary switches
// for the flows related the router ID.
List<BigInteger> allSwitchList = naptSwitchSelector.getDpnsForVpn(routerName);
if (allSwitchList.isEmpty()) {
LOG.error("removeFlowsFromNonActiveSwitches : Unable to get the swithces for the router {}", routerName);
return;
}
for (BigInteger dpnId : allSwitchList) {
if (!naptSwitchDpnId.equals(dpnId)) {
LOG.info("removeFlowsFromNonActiveSwitches : Handle Ordinary switch");
//Remove the PSNAT entry which forwards the packet to Terminating Service table
String preSnatFlowRef = getFlowRefSnat(dpnId, NwConstants.PSNAT_TABLE, String.valueOf(routerName));
FlowEntity preSnatFlowEntity =
NatUtil.buildFlowEntity(dpnId, NwConstants.PSNAT_TABLE, preSnatFlowRef);
LOG.info("removeFlowsFromNonActiveSwitches : Remove the flow in the {} for the non active switch "
+ "with the DPN ID {} and router ID {}", NwConstants.PSNAT_TABLE, dpnId, routerId);
mdsalManager.removeFlow(removeFlowInvTx, preSnatFlowEntity);
//Remove the group entry which forwards the traffic to the out port (VXLAN tunnel).
long groupId = createGroupId(getGroupIdKey(routerName));
LOG.info("removeFlowsFromNonActiveSwitches : Remove the group {} for the non active switch with "
+ "the DPN ID {} and router ID {}", groupId, dpnId, routerId);
mdsalManager.removeGroup(removeFlowInvTx, dpnId, groupId);
}
}
}
public void clrRtsFromBgpAndDelFibTs(final BigInteger dpnId, Long routerId, @Nullable Uuid networkUuid,
@Nonnull Collection<String> externalIps, @Nullable String vpnName,
String extGwMacAddress, TypedReadWriteTransaction<Configuration> confTx)
throws ExecutionException, InterruptedException {
//Withdraw the corresponding routes from the BGP.
//Get the network ID using the router ID.
LOG.debug("clrRtsFromBgpAndDelFibTs : Advertise to BGP and remove routes for externalIps {} with routerId {},"
+ "network Id {} and vpnName {}", externalIps, routerId, networkUuid, vpnName);
if (networkUuid == null) {
LOG.error("clrRtsFromBgpAndDelFibTs : networkId is null");
return;
}
if (externalIps.isEmpty()) {
LOG.error("clrRtsFromBgpAndDelFibTs : externalIps is empty");
return;
}
if (vpnName == null) {
//Get the VPN Name using the network ID
vpnName = NatUtil.getAssociatedVPN(dataBroker, networkUuid);
if (vpnName == null) {
LOG.error("clrRtsFromBgpAndDelFibTs : No VPN associated with ext nw {} for the router {}",
networkUuid, routerId);
return;
}
}
LOG.debug("clrRtsFromBgpAndDelFibTs : Retrieved vpnName {} for networkId {}", vpnName, networkUuid);
//Remove custom FIB routes
//Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input);
for (String extIp : externalIps) {
clrRtsFromBgpAndDelFibTs(dpnId, routerId, extIp, vpnName, networkUuid, extGwMacAddress, confTx);
}
}
protected void clrRtsFromBgpAndDelFibTs(final BigInteger dpnId, long routerId, String extIp, final String vpnName,
final Uuid networkUuid, String extGwMacAddress,
TypedReadWriteTransaction<Configuration> removeFlowInvTx)
throws ExecutionException, InterruptedException {
clearBgpRoutes(extIp, vpnName);
delFibTsAndReverseTraffic(dpnId, routerId, extIp, vpnName, networkUuid, extGwMacAddress, false,
removeFlowInvTx);
}
protected void delFibTsAndReverseTraffic(final BigInteger dpnId, long routerId, String extIp,
final String vpnName, Uuid extNetworkId, long tempLabel,
String gwMacAddress, boolean switchOver,
TypedReadWriteTransaction<Configuration> removeFlowInvTx)
throws ExecutionException, InterruptedException {
LOG.debug("delFibTsAndReverseTraffic : Removing fib entry for externalIp {} in routerId {}", extIp, routerId);
String routerName = NatUtil.getRouterName(dataBroker,routerId);
if (routerName == null) {
LOG.error("delFibTsAndReverseTraffic : Could not retrieve Router Name from Router ID {} ", routerId);
return;
}
ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, extNetworkId);
if (extNwProvType == null) {
LOG.error("delFibTsAndReverseTraffic : External Network Provider Type Missing");
return;
}
/* Remove the flow table19->44 and table36->44 entries for SNAT reverse traffic flow if the
* external network provided type is VxLAN
*/
if (extNwProvType == ProviderTypes.VXLAN) {
evpnSnatFlowProgrammer.evpnDelFibTsAndReverseTraffic(dpnId, routerId, extIp, vpnName, gwMacAddress
);
return;
}
if (tempLabel < 0) {
LOG.error("delFibTsAndReverseTraffic : Label not found for externalIp {} with router id {}",
extIp, routerId);
return;
}
final long label = tempLabel;
final String externalIp = NatUtil.validateAndAddNetworkMask(extIp);
RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName)
.setSourceDpid(dpnId).setIpAddress(externalIp).setServiceId(label)
.setIpAddressSource(RemoveFibEntryInput.IpAddressSource.ExternalFixedIP).build();
ListenableFuture<RpcResult<RemoveFibEntryOutput>> future = fibService.removeFibEntry(input);
removeTunnelTableEntry(dpnId, label, removeFlowInvTx);
removeLFibTableEntry(dpnId, label, removeFlowInvTx);
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
//Remove the flow table 25->44 If there is no FIP Match on table 25 (PDNAT_TABLE)
NatUtil.removePreDnatToSnatTableEntry(removeFlowInvTx, mdsalManager, dpnId);
}
if (!switchOver) {
ListenableFuture<RpcResult<RemoveVpnLabelOutput>> labelFuture =
Futures.transformAsync(future, result -> {
//Release label
if (result.isSuccessful()) {
NatUtil.removePreDnatToSnatTableEntry(removeFlowInvTx, mdsalManager, dpnId);
RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder()
.setVpnName(vpnName).setIpPrefix(externalIp).build();
return vpnService.removeVpnLabel(labelInput);
} else {
String errMsg =
String.format("RPC call to remove custom FIB entries on dpn %s for "
+ "prefix %s Failed - %s", dpnId, externalIp, result.getErrors());
LOG.error(errMsg);
return Futures.immediateFailedFuture(new RuntimeException(errMsg));
}
}, MoreExecutors.directExecutor());
Futures.addCallback(labelFuture, new FutureCallback<RpcResult<RemoveVpnLabelOutput>>() {
@Override
public void onFailure(@Nonnull Throwable error) {
LOG.error("delFibTsAndReverseTraffic : Error in removing the label:{} or custom fib entries"
+ "got external ip {}", label, extIp, error);
}
@Override
public void onSuccess(@Nonnull RpcResult<RemoveVpnLabelOutput> result) {
if (result.isSuccessful()) {
LOG.debug("delFibTsAndReverseTraffic : Successfully removed the label for the prefix {} "
+ "from VPN {}", externalIp, vpnName);
} else {
LOG.error("delFibTsAndReverseTraffic : Error in removing the label for prefix {} "
+ " from VPN {}, {}", externalIp, vpnName, result.getErrors());
}
}
}, MoreExecutors.directExecutor());
} else {
LOG.debug("delFibTsAndReverseTraffic: switch-over is happened on DpnId {}. No need to release allocated "
+ "label {} for external fixed ip {} for router {}", dpnId, label, externalIp, routerId);
}
}
private void delFibTsAndReverseTraffic(final BigInteger dpnId, long routerId, String extIp, final String vpnName,
final Uuid networkUuid, String extGwMacAddress, boolean switchOver,
TypedReadWriteTransaction<Configuration> removeFlowInvTx)
throws ExecutionException, InterruptedException {
LOG.debug("delFibTsAndReverseTraffic : Removing fib entry for externalIp {} in routerId {}", extIp, routerId);
String routerName = NatUtil.getRouterName(dataBroker,routerId);
if (routerName == null) {
LOG.error("delFibTsAndReverseTraffic : Could not retrieve Router Name from Router ID {} ", routerId);
return;
}
//Get the external network provider type from networkId
ProviderTypes extNwProvType = NatUtil.getProviderTypefromNetworkId(dataBroker, networkUuid);
if (extNwProvType == null) {
LOG.error("delFibTsAndReverseTraffic : Could not retrieve provider type for external network {} ",
networkUuid);
return;
}
/* Remove the flow table19->44 and table36->44 entries for SNAT reverse traffic flow if the
* external network provided type is VxLAN
*/
if (extNwProvType == ProviderTypes.VXLAN) {
evpnSnatFlowProgrammer.evpnDelFibTsAndReverseTraffic(dpnId, routerId, extIp, vpnName, extGwMacAddress);
return;
}
//Get IPMaps from the DB for the router ID
List<IpMap> dbIpMaps = NaptManager.getIpMapList(dataBroker, routerId);
if (dbIpMaps.isEmpty()) {
LOG.error("delFibTsAndReverseTraffic : IPMaps not found for router {}", routerId);
return;
}
long tempLabel = NatConstants.INVALID_ID;
for (IpMap dbIpMap : dbIpMaps) {
String dbExternalIp = dbIpMap.getExternalIp();
LOG.debug("delFibTsAndReverseTraffic : Retrieved dbExternalIp {} for router id {}", dbExternalIp, routerId);
//Select the IPMap, whose external IP is the IP for which FIB is installed
if (extIp.equals(dbExternalIp)) {
tempLabel = dbIpMap.getLabel();
LOG.debug("delFibTsAndReverseTraffic : Retrieved label {} for dbExternalIp {} with router id {}",
tempLabel, dbExternalIp, routerId);
break;
}
}
if (tempLabel == NatConstants.INVALID_ID) {
LOG.error("delFibTsAndReverseTraffic : Label not found for externalIp {} with router id {}",
extIp, routerId);
return;
}
final long label = tempLabel;
final String externalIp = NatUtil.validateAndAddNetworkMask(extIp);
RemoveFibEntryInput input = new RemoveFibEntryInputBuilder()
.setVpnName(vpnName).setSourceDpid(dpnId).setIpAddress(externalIp)
.setIpAddressSource(RemoveFibEntryInput.IpAddressSource.ExternalFixedIP).setServiceId(label).build();
ListenableFuture<RpcResult<RemoveFibEntryOutput>> future = fibService.removeFibEntry(input);
removeTunnelTableEntry(dpnId, label, removeFlowInvTx);
removeLFibTableEntry(dpnId, label, removeFlowInvTx);
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
//Remove the flow table 25->44 If there is no FIP Match on table 25 (PDNAT_TABLE)
NatUtil.removePreDnatToSnatTableEntry(removeFlowInvTx, mdsalManager, dpnId);
}
if (!switchOver) {
ListenableFuture<RpcResult<RemoveVpnLabelOutput>> labelFuture =
Futures.transformAsync(future, result -> {
//Release label
if (result.isSuccessful()) {
RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder()
.setVpnName(vpnName).setIpPrefix(externalIp).build();
return vpnService.removeVpnLabel(labelInput);
} else {
String errMsg =
String.format("RPC call to remove custom FIB entries on dpn %s for "
+ "prefix %s Failed - %s",
dpnId, externalIp, result.getErrors());
LOG.error(errMsg);
return Futures.immediateFailedFuture(new RuntimeException(errMsg));
}
}, MoreExecutors.directExecutor());
Futures.addCallback(labelFuture, new FutureCallback<RpcResult<RemoveVpnLabelOutput>>() {
@Override
public void onFailure(@Nonnull Throwable error) {
LOG.error("delFibTsAndReverseTraffic : Error in removing the label or custom fib entries", error);
}
@Override
public void onSuccess(@Nonnull RpcResult<RemoveVpnLabelOutput> result) {
if (result.isSuccessful()) {
LOG.debug("delFibTsAndReverseTraffic : Successfully removed the label for the prefix {} "
+ "from VPN {}", externalIp, vpnName);
} else {
LOG.error("delFibTsAndReverseTraffic : Error in removing the label for prefix {} "
+ " from VPN {}, {}", externalIp, vpnName, result.getErrors());
}
}
}, MoreExecutors.directExecutor());
} else {
LOG.debug("delFibTsAndReverseTraffic: switch-over is happened on DpnId {}. No need to release allocated "
+ "label {} for external fixed ip {} for router {}", dpnId, label, externalIp, routerId);
}
}
protected void clearFibTsAndReverseTraffic(final BigInteger dpnId, Long routerId, Uuid networkUuid,
List<String> externalIps, @Nullable String vpnName, String extGwMacAddress,
TypedReadWriteTransaction<Configuration> writeFlowInvTx) throws ExecutionException, InterruptedException {
//Withdraw the corresponding routes from the BGP.
//Get the network ID using the router ID.
LOG.debug("clearFibTsAndReverseTraffic : for externalIps {} with routerId {},"
+ "network Id {} and vpnName {}", externalIps, routerId, networkUuid, vpnName);
if (networkUuid == null) {
LOG.error("clearFibTsAndReverseTraffic : networkId is null");
return;
}
if (externalIps == null || externalIps.isEmpty()) {
LOG.error("clearFibTsAndReverseTraffic : externalIps is null");
return;
}
if (vpnName == null) {
//Get the VPN Name using the network ID
vpnName = NatUtil.getAssociatedVPN(dataBroker, networkUuid);
if (vpnName == null) {
LOG.error("clearFibTsAndReverseTraffic : No VPN associated with ext nw {} for the router {}",
networkUuid, routerId);
return;
}
}
LOG.debug("Retrieved vpnName {} for networkId {}", vpnName, networkUuid);
//Remove custom FIB routes
//Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input);
for (String extIp : externalIps) {
delFibTsAndReverseTraffic(dpnId, routerId, extIp, vpnName, networkUuid, extGwMacAddress, false,
writeFlowInvTx);
}
}
protected void clearBgpRoutes(String externalIp, final String vpnName) {
//Inform BGP about the route removal
LOG.info("clearBgpRoutes : Informing BGP to remove route for externalIP {} of vpn {}", externalIp, vpnName);
String rd = NatUtil.getVpnRd(dataBroker, vpnName);
NatUtil.removePrefixFromBGP(bgpManager, fibManager, rd, externalIp, vpnName, LOG);
}
private void removeTunnelTableEntry(BigInteger dpnId, long serviceId,
TypedReadWriteTransaction<Configuration> writeFlowInvTx) throws ExecutionException, InterruptedException {
LOG.info("removeTunnelTableEntry : called with DpnId = {} and label = {}", dpnId, serviceId);
mdsalManager.removeFlow(writeFlowInvTx, dpnId,
getFlowRef(dpnId, NwConstants.INTERNAL_TUNNEL_TABLE, serviceId, ""), NwConstants.INTERNAL_TUNNEL_TABLE);
LOG.debug("removeTunnelTableEntry : dpID {} : label : {} removed successfully", dpnId, serviceId);
}
private void removeLFibTableEntry(BigInteger dpnId, long serviceId,
TypedReadWriteTransaction<Configuration> writeFlowInvTx) throws ExecutionException, InterruptedException {
String flowRef = getFlowRef(dpnId, NwConstants.L3_LFIB_TABLE, serviceId, "");
LOG.debug("removeLFibTableEntry : with flow ref {}", flowRef);
mdsalManager.removeFlow(writeFlowInvTx, dpnId, flowRef, NwConstants.L3_LFIB_TABLE);
LOG.debug("removeLFibTableEntry : dpID : {} label : {} removed successfully", dpnId, serviceId);
}
/**
* router association to vpn.
*
* @param routerName - Name of router
* @param routerId - router id
* @param bgpVpnName BGP VPN name
*/
public void changeLocalVpnIdToBgpVpnId(String routerName, long routerId, String bgpVpnName,
TypedWriteTransaction<Configuration> writeFlowInvTx, ProviderTypes extNwProvType) {
LOG.debug("changeLocalVpnIdToBgpVpnId : Router associated to BGP VPN");
if (chkExtRtrAndSnatEnbl(new Uuid(routerName))) {
long bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnName);
LOG.debug("changeLocalVpnIdToBgpVpnId : BGP VPN ID value {} ", bgpVpnId);
if (bgpVpnId != NatConstants.INVALID_ID) {
LOG.debug("changeLocalVpnIdToBgpVpnId : Populate the router-id-name container with the "
+ "mapping BGP VPN-ID {} -> BGP VPN-NAME {}", bgpVpnId, bgpVpnName);
RouterIds rtrs = new RouterIdsBuilder().withKey(new RouterIdsKey(bgpVpnId))
.setRouterId(bgpVpnId).setRouterName(bgpVpnName).build();
MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION,
getRoutersIdentifier(bgpVpnId), rtrs);
// Get the allocated Primary NAPT Switch for this router
LOG.debug("changeLocalVpnIdToBgpVpnId : Router ID value {} ", routerId);
LOG.debug("changeLocalVpnIdToBgpVpnId : Update the Router ID {} to the BGP VPN ID {} ",
routerId, bgpVpnId);
addDefaultFibRouteForSnatWithBgpVpn(routerName, routerId, bgpVpnId, writeFlowInvTx);
// Get the group ID
BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerName);
createGroupId(getGroupIdKey(routerName));
installFlowsWithUpdatedVpnId(primarySwitchId, routerName, bgpVpnId, routerId, true, writeFlowInvTx,
extNwProvType);
}
}
}
/**
* router disassociation from vpn.
*
* @param routerName - Name of router
* @param routerId - router id
* @param bgpVpnName BGP VPN name
*/
public void changeBgpVpnIdToLocalVpnId(String routerName, long routerId, String bgpVpnName,
TypedWriteTransaction<Configuration> writeFlowInvTx, ProviderTypes extNwProvType) {
LOG.debug("changeBgpVpnIdToLocalVpnId : Router dissociated from BGP VPN");
if (chkExtRtrAndSnatEnbl(new Uuid(routerName))) {
long bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnName);
LOG.debug("changeBgpVpnIdToLocalVpnId : BGP VPN ID value {} ", bgpVpnId);
// Get the allocated Primary NAPT Switch for this router
LOG.debug("changeBgpVpnIdToLocalVpnId : Router ID value {} ", routerId);
LOG.debug("changeBgpVpnIdToLocalVpnId : Update the BGP VPN ID {} to the Router ID {}", bgpVpnId, routerId);
addDefaultFibRouteForSnatWithBgpVpn(routerName, routerId, NatConstants.INVALID_ID, writeFlowInvTx);
// Get the group ID
createGroupId(getGroupIdKey(routerName));
BigInteger primarySwitchId = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerName);
installFlowsWithUpdatedVpnId(primarySwitchId, routerName, NatConstants.INVALID_ID, routerId, true,
writeFlowInvTx, extNwProvType);
}
}
boolean chkExtRtrAndSnatEnbl(Uuid routerUuid) {
InstanceIdentifier<Routers> routerInstanceIndentifier =
InstanceIdentifier.builder(ExtRouters.class)
.child(Routers.class, new RoutersKey(routerUuid.getValue())).build();
try {
Optional<Routers> routerData = SingleTransactionDataBroker
.syncReadOptional(dataBroker,
LogicalDatastoreType.CONFIGURATION, routerInstanceIndentifier);
return routerData.isPresent() && routerData.get().isEnableSnat();
} catch (ReadFailedException e) {
LOG.error("Failed to read data for router id {}", routerUuid, e);
return false;
}
}
public void installFlowsWithUpdatedVpnId(BigInteger primarySwitchId, String routerName, long bgpVpnId,
long routerId, boolean isSnatCfgd, TypedWriteTransaction<Configuration> confTx, ProviderTypes extNwProvType) {
long changedVpnId = bgpVpnId;
String idType = "BGP VPN";
if (bgpVpnId == NatConstants.INVALID_ID) {
changedVpnId = routerId;
idType = "router";
}
List<BigInteger> switches = NatUtil.getDpnsForRouter(dataBroker, routerName);
if (switches.isEmpty()) {
LOG.error("installFlowsWithUpdatedVpnId : No switches found for router {}", routerName);
return;
}
for (BigInteger dpnId : switches) {
// Update the BGP VPN ID in the SNAT miss entry to group
if (!dpnId.equals(primarySwitchId)) {
LOG.debug("installFlowsWithUpdatedVpnId : Install group in non NAPT switch {}", dpnId);
List<BucketInfo> bucketInfoForNonNaptSwitches =
getBucketInfoForNonNaptSwitches(dpnId, primarySwitchId, routerName, routerId);
long groupId = createGroupId(getGroupIdKey(routerName));
if (!isSnatCfgd) {
groupId = installGroup(dpnId, routerName, bucketInfoForNonNaptSwitches);
}
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the SNAT miss entry pointing to group "
+ "{} in the non NAPT switch {}", idType, changedVpnId, groupId, dpnId);
FlowEntity flowEntity = buildSnatFlowEntityWithUpdatedVpnId(dpnId, routerName, groupId, changedVpnId);
mdsalManager.addFlow(confTx, flowEntity);
} else {
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the SNAT miss entry pointing to group "
+ "in the primary switch {}", idType, changedVpnId, primarySwitchId);
FlowEntity flowEntity =
buildSnatFlowEntityWithUpdatedVpnIdForPrimrySwtch(primarySwitchId, routerName, changedVpnId);
mdsalManager.addFlow(confTx, flowEntity);
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the Terminating Service table (table "
+ "ID 36) which forwards the packet to the table 46 in the Primary switch {}",
idType, changedVpnId, primarySwitchId);
installTerminatingServiceTblEntryWithUpdatedVpnId(primarySwitchId, routerName, routerId,
changedVpnId, confTx, extNwProvType);
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the Outbound NAPT table (table ID 46) "
+ "which punts the packet to the controller in the Primary switch {}",
idType, changedVpnId, primarySwitchId);
createOutboundTblEntryWithBgpVpn(primarySwitchId, routerId, changedVpnId, confTx);
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the NAPT PFIB TABLE which forwards the"
+ " outgoing packet to FIB Table in the Primary switch {}",
idType, changedVpnId, primarySwitchId);
installNaptPfibEntryWithBgpVpn(primarySwitchId, routerId, changedVpnId, confTx);
LOG.debug(
"installFlowsWithUpdatedVpnId : Update the {} ID {} in the NAPT flows for the Outbound NAPT "
+ "table (table ID 46) and the INBOUND NAPT table (table ID 44) in the Primary switch"
+ " {}", idType, changedVpnId, primarySwitchId);
updateNaptFlowsWithVpnId(primarySwitchId, routerName, routerId, bgpVpnId);
LOG.debug("installFlowsWithUpdatedVpnId : Installing SNAT PFIB flow in the primary switch {}",
primarySwitchId);
Long vpnId = NatUtil.getNetworkVpnIdFromRouterId(dataBroker, routerId);
//Install the NAPT PFIB TABLE which forwards the outgoing packet to FIB Table matching on the VPN ID.
if (vpnId != NatConstants.INVALID_ID) {
installNaptPfibEntry(primarySwitchId, vpnId, confTx);
}
}
}
}
public void updateNaptFlowsWithVpnId(BigInteger dpnId, String routerName, long routerId, long bgpVpnId) {
//For the router ID get the internal IP , internal port and the corresponding external IP and external Port.
IpPortMapping ipPortMapping = NatUtil.getIportMapping(dataBroker, routerId);
if (ipPortMapping == null) {
LOG.error("updateNaptFlowsWithVpnId : Unable to retrieve the IpPortMapping");
return;
}
// Get the External Gateway MAC Address
String extGwMacAddress = NatUtil.getExtGwMacAddFromRouterName(dataBroker, routerName);
if (extGwMacAddress != null) {
LOG.debug("updateNaptFlowsWithVpnId : External Gateway MAC address {} found for External Router ID {}",
extGwMacAddress, routerId);
} else {
LOG.error("updateNaptFlowsWithVpnId : No External Gateway MAC address found for External Router ID {}",
routerId);
return;
}
for (IntextIpProtocolType intextIpProtocolType : requireNonNullElse(ipPortMapping.getIntextIpProtocolType(),
Collections.<IntextIpProtocolType>emptyList())) {
for (IpPortMap ipPortMap : requireNonNullElse(intextIpProtocolType.getIpPortMap(),
Collections.<IpPortMap>emptyList())) {
String ipPortInternal = ipPortMap.getIpPortInternal();
String[] ipPortParts = ipPortInternal.split(":");
if (ipPortParts.length != 2) {
LOG.error("updateNaptFlowsWithVpnId : Unable to retrieve the Internal IP and port");
return;
}
String internalIp = ipPortParts[0];
String internalPort = ipPortParts[1];
LOG.debug("updateNaptFlowsWithVpnId : Found Internal IP {} and Internal Port {}",
internalIp, internalPort);
ProtocolTypes protocolTypes = intextIpProtocolType.getProtocol();
NAPTEntryEvent.Protocol protocol;
switch (protocolTypes) {
case TCP:
protocol = NAPTEntryEvent.Protocol.TCP;
break;
case UDP:
protocol = NAPTEntryEvent.Protocol.UDP;
break;
default:
protocol = NAPTEntryEvent.Protocol.TCP;
}
SessionAddress internalAddress = new SessionAddress(internalIp, Integer.parseInt(internalPort));
SessionAddress externalAddress =
naptManager.getExternalAddressMapping(routerId, internalAddress, protocol);
long internetVpnid = NatUtil.getNetworkVpnIdFromRouterId(dataBroker, routerId);
naptEventHandler.buildAndInstallNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, internetVpnid,
routerId, bgpVpnId, externalAddress, internalAddress, protocol, extGwMacAddress);
naptEventHandler.buildAndInstallNatFlows(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, internetVpnid,
routerId, bgpVpnId, internalAddress, externalAddress, protocol, extGwMacAddress);
}
}
}
public FlowEntity buildSnatFlowEntityWithUpdatedVpnId(BigInteger dpId, String routerName, long groupId,
long changedVpnId) {
LOG.debug("buildSnatFlowEntityWithUpdatedVpnId : called for dpId {}, routerName {} groupId {} "
+ "changed VPN ID {}", dpId, routerName, groupId, changedVpnId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(changedVpnId), MetaDataUtil.METADATA_MASK_VRFID));
List<ActionInfo> actionsInfo = new ArrayList<>();
long tunnelId = NatUtil.getTunnelIdForNonNaptToNaptFlow(dataBroker, natOverVxlanUtil,
elanManager, idManager, changedVpnId, routerName);
actionsInfo.add(new ActionSetFieldTunnelId(BigInteger.valueOf(tunnelId)));
LOG.debug("buildSnatFlowEntityWithUpdatedVpnId : Setting the tunnel to the list of action infos {}",
actionsInfo);
actionsInfo.add(new ActionGroup(groupId));
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionApplyActions(actionsInfo));
String flowRef = getFlowRefSnat(dpId, NwConstants.PSNAT_TABLE, routerName);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions);
LOG.debug("buildSnatFlowEntityWithUpdatedVpnId : Returning SNAT Flow Entity {}", flowEntity);
return flowEntity;
}
public FlowEntity buildSnatFlowEntityWithUpdatedVpnIdForPrimrySwtch(BigInteger dpId, String routerName,
long changedVpnId) {
LOG.debug("buildSnatFlowEntityWithUpdatedVpnIdForPrimrySwtch : called for dpId {}, routerName {} "
+ "changed VPN ID {}", dpId, routerName, changedVpnId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(changedVpnId), MetaDataUtil.METADATA_MASK_VRFID));
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionGotoTable(NwConstants.OUTBOUND_NAPT_TABLE));
String flowRef = getFlowRefSnat(dpId, NwConstants.PSNAT_TABLE, routerName);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructions);
LOG.debug("buildSnatFlowEntityWithUpdatedVpnIdForPrimrySwtch : Returning SNAT Flow Entity {}", flowEntity);
return flowEntity;
}
// TODO : Replace this with ITM Rpc once its available with full functionality
protected void installTerminatingServiceTblEntryWithUpdatedVpnId(BigInteger dpnId, String routerName,
long routerId, long changedVpnId, TypedWriteTransaction<Configuration> confTx, ProviderTypes extNwProvType) {
LOG.debug("installTerminatingServiceTblEntryWithUpdatedVpnId : called for switch {}, "
+ "routerName {}, BGP VPN ID {}", dpnId, routerName, changedVpnId);
FlowEntity flowEntity = buildTsFlowEntityWithUpdatedVpnId(dpnId, routerName, routerId, changedVpnId,
extNwProvType);
mdsalManager.addFlow(confTx, flowEntity);
}
private FlowEntity buildTsFlowEntityWithUpdatedVpnId(BigInteger dpId, String routerName,
long routerIdLongVal, long changedVpnId, ProviderTypes extNwProvType) {
LOG.debug("buildTsFlowEntityWithUpdatedVpnId : called for switch {}, routerName {}, BGP VPN ID {}",
dpId, routerName, changedVpnId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
BigInteger tunnelId = BigInteger.valueOf(changedVpnId);
if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
tunnelId = natOverVxlanUtil.getRouterVni(routerName, changedVpnId);
}
matches.add(new MatchTunnelId(tunnelId));
List<InstructionInfo> instructions = new ArrayList<>();
instructions.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(changedVpnId),
MetaDataUtil.METADATA_MASK_VRFID));
instructions.add(new InstructionGotoTable(NwConstants.OUTBOUND_NAPT_TABLE));
BigInteger routerId = BigInteger.valueOf(routerIdLongVal);
String flowRef = getFlowRefTs(dpId, NwConstants.INTERNAL_TUNNEL_TABLE, routerId.longValue());
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.INTERNAL_TUNNEL_TABLE, flowRef,
NatConstants.DEFAULT_TS_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_TS_TABLE, matches, instructions);
return flowEntity;
}
public void createOutboundTblEntryWithBgpVpn(BigInteger dpnId, long routerId, long changedVpnId,
TypedWriteTransaction<Configuration> writeFlowInvTx) {
LOG.debug("createOutboundTblEntryWithBgpVpn : called for dpId {} and routerId {}, BGP VPN ID {}",
dpnId, routerId, changedVpnId);
FlowEntity tcpFlowEntity = buildOutboundFlowEntityWithBgpVpn(dpnId, routerId, changedVpnId,
NwConstants.IP_PROT_TCP);
LOG.debug("createOutboundTblEntryWithBgpVpn : Installing tcp flow {}", tcpFlowEntity);
mdsalManager.addFlow(writeFlowInvTx, tcpFlowEntity);
FlowEntity udpFlowEntity = buildOutboundFlowEntityWithBgpVpn(dpnId, routerId, changedVpnId,
NwConstants.IP_PROT_UDP);
LOG.debug("createOutboundTblEntryWithBgpVpn : Installing udp flow {}", udpFlowEntity);
mdsalManager.addFlow(writeFlowInvTx, udpFlowEntity);
FlowEntity icmpDropFlow = buildIcmpDropFlow(dpnId, routerId, changedVpnId);
LOG.debug("createOutboundTblEntry: Installing icmp drop flow {}", icmpDropFlow);
mdsalManager.addFlow(writeFlowInvTx, icmpDropFlow);
}
protected FlowEntity buildOutboundFlowEntityWithBgpVpn(BigInteger dpId, long routerId,
long changedVpnId, int protocol) {
LOG.debug("buildOutboundFlowEntityWithBgpVpn : called for dpId {} and routerId {}, BGP VPN ID {}",
dpId, routerId, changedVpnId);
BigInteger cookie = getCookieOutboundFlow(routerId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchIpProtocol((short)protocol));
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(changedVpnId), MetaDataUtil.METADATA_MASK_VRFID));
List<InstructionInfo> instructions = new ArrayList<>();
List<ActionInfo> actionsInfos = new ArrayList<>();
actionsInfos.add(new ActionPuntToController());
if (snatPuntTimeout != 0) {
actionsInfos.add(getLearnActionForPunt(protocol, snatPuntTimeout, cookie));
}
instructions.add(new InstructionApplyActions(actionsInfos));
String flowRef = getFlowRefOutbound(dpId, NwConstants.OUTBOUND_NAPT_TABLE, routerId, protocol);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.OUTBOUND_NAPT_TABLE,
flowRef, 5, flowRef, 0, 0, cookie, matches, instructions);
LOG.debug("createOutboundTblEntryWithBgpVpn : returning flowEntity {}", flowEntity);
return flowEntity;
}
public void installNaptPfibEntryWithBgpVpn(BigInteger dpnId, long segmentId, long changedVpnId,
TypedWriteTransaction<Configuration> writeFlowInvTx) {
LOG.debug("installNaptPfibEntryWithBgpVpn : called for dpnId {} and segmentId {} ,BGP VPN ID {}",
dpnId, segmentId, changedVpnId);
FlowEntity naptPfibFlowEntity = buildNaptPfibFlowEntityWithUpdatedVpnId(dpnId, segmentId, changedVpnId);
mdsalManager.addFlow(writeFlowInvTx, naptPfibFlowEntity);
}
public FlowEntity buildNaptPfibFlowEntityWithUpdatedVpnId(BigInteger dpId, long segmentId, long changedVpnId) {
LOG.debug("buildNaptPfibFlowEntityWithUpdatedVpnId : called for dpId {}, "
+ "segmentId {}, BGP VPN ID {}", dpId, segmentId, changedVpnId);
List<MatchInfo> matches = new ArrayList<>();
matches.add(MatchEthernetType.IPV4);
matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(changedVpnId), MetaDataUtil.METADATA_MASK_VRFID));
ArrayList<ActionInfo> listActionInfo = new ArrayList<>();
ArrayList<InstructionInfo> instructionInfo = new ArrayList<>();
listActionInfo.add(new ActionNxLoadInPort(BigInteger.ZERO));
listActionInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
instructionInfo.add(new InstructionApplyActions(listActionInfo));
String flowRef = getFlowRefTs(dpId, NwConstants.NAPT_PFIB_TABLE, segmentId);
FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.NAPT_PFIB_TABLE, flowRef,
NatConstants.DEFAULT_PSNAT_FLOW_PRIORITY, flowRef, 0, 0,
NwConstants.COOKIE_SNAT_TABLE, matches, instructionInfo);
LOG.debug("buildNaptPfibFlowEntityWithUpdatedVpnId : Returning NaptPFib Flow Entity {}", flowEntity);
return flowEntity;
}
@Override
protected ExternalRoutersListener getDataTreeChangeListener() {
return ExternalRoutersListener.this;
}
protected void installNaptPfibEntriesForExternalSubnets(String routerName, BigInteger dpnId,
@Nullable TypedWriteTransaction<Configuration> writeFlowInvTx) {
Collection<Uuid> externalSubnetIdsForRouter = NatUtil.getExternalSubnetIdsForRouter(dataBroker,
routerName);
for (Uuid externalSubnetId : externalSubnetIdsForRouter) {
long subnetVpnId = NatUtil.getVpnId(dataBroker, externalSubnetId.getValue());
if (subnetVpnId != -1) {
LOG.debug("installNaptPfibEntriesForExternalSubnets : called for dpnId {} "
+ "and vpnId {}", dpnId, subnetVpnId);
installNaptPfibEntry(dpnId, subnetVpnId, writeFlowInvTx);
}
}
}
}
|
package org.navalplanner.business.test.planner.daos;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.navalplanner.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.navalplanner.business.test.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_TEST_FILE;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.navalplanner.business.IDataBootstrap;
import org.navalplanner.business.common.IAdHocTransactionService;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.common.daos.IConfigurationDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.entities.HoursGroup;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.business.orders.entities.OrderLine;
import org.navalplanner.business.orders.entities.TaskSource;
import org.navalplanner.business.orders.entities.TaskSource.TaskSourceSynchronization;
import org.navalplanner.business.planner.daos.ITaskElementDAO;
import org.navalplanner.business.planner.daos.ITaskSourceDAO;
import org.navalplanner.business.planner.daos.TaskElementDAO;
import org.navalplanner.business.planner.entities.Dependency;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.planner.entities.TaskElement;
import org.navalplanner.business.planner.entities.TaskGroup;
import org.navalplanner.business.planner.entities.TaskMilestone;
import org.navalplanner.business.planner.entities.Dependency.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.NotTransactional;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
/**
* Test cases for {@link TaskElementDAO}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { BUSINESS_SPRING_CONFIG_FILE,
BUSINESS_SPRING_CONFIG_TEST_FILE })
@Transactional
public class TaskElementDAOTest {
@Resource
private IDataBootstrap defaultAdvanceTypesBootstrapListener;
@Resource
private IDataBootstrap configurationBootstrap;
@Before
public void loadRequiredaData() {
defaultAdvanceTypesBootstrapListener.loadRequiredData();
configurationBootstrap.loadRequiredData();
}
@Autowired
private ITaskElementDAO taskElementDAO;
@Autowired
private IOrderDAO orderDAO;
@Autowired
private ITaskSourceDAO taskSourceDAO;
@Autowired
private SessionFactory sessionFactory;
@Autowired
private IAdHocTransactionService transactionService;
@Autowired
private IConfigurationDAO configurationDAO;
private HoursGroup associatedHoursGroup;
private Task createValidTask() {
associatedHoursGroup = new HoursGroup();
associatedHoursGroup.setCode("hours-group-code-" + UUID.randomUUID());
OrderLine orderLine = createOrderLine();
orderLine.addHoursGroup(associatedHoursGroup);
TaskSource taskSource = TaskSource
.create(orderLine, Arrays
.asList(associatedHoursGroup));
TaskSourceSynchronization mustAdd = TaskSource.mustAdd(taskSource);
mustAdd.apply(taskSourceDAO);
Task task = (Task) taskSource.getTask();
return task;
}
private OrderLine createOrderLine() {
OrderLine orderLine = OrderLine.create();
orderLine.setName("bla");
orderLine.setCode("code-" + UUID.randomUUID());
HoursGroup hoursGroup = new HoursGroup();
hoursGroup.setCode("hours-group-code-" + UUID.randomUUID());
orderLine.addHoursGroup(hoursGroup);
Order order = Order.create();
order.setName("bla");
order.setInitDate(new Date());
order.setCode("code-" + UUID.randomUUID());
order.add(orderLine);
order.setCalendar(configurationDAO.getConfiguration()
.getDefaultCalendar());
try {
orderDAO.save(order);
sessionFactory.getCurrentSession().flush();
} catch (ValidationException e) {
throw new RuntimeException(e);
}
return orderLine;
}
private TaskGroup createValidTaskGroup() {
OrderLine orderLine = createOrderLine();
TaskSource taskSource = TaskSource.createForGroup(orderLine);
TaskSourceSynchronization synchronization = TaskSource
.mustAddGroup(taskSource, Collections
.<TaskSourceSynchronization> emptyList());
synchronization.apply(taskSourceDAO);
return (TaskGroup) taskSource.getTask();
}
private TaskMilestone createValidTaskMilestone() {
TaskMilestone result = TaskMilestone.create();
return result;
}
private void checkProperties(TaskElement inMemory, TaskElement fromDB) {
assertThat(fromDB.getStartDate(), equalTo(inMemory.getStartDate()));
assertThat(fromDB.getEndDate(), equalTo(inMemory.getEndDate()));
}
private void flushAndEvict(Object entity) {
sessionFactory.getCurrentSession().flush();
sessionFactory.getCurrentSession().evict(entity);
}
@Test
public void canSaveTask() {
Task task = createValidTask();
taskElementDAO.save(task);
flushAndEvict(task);
TaskElement fromDB;
try {
fromDB = taskElementDAO.find(task.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
assertThat(fromDB.getId(), equalTo(task.getId()));
assertThat(fromDB, is(Task.class));
checkProperties(task, fromDB);
HoursGroup reloaded = ((Task) fromDB).getHoursGroup();
assertThat(reloaded.getId(), equalTo(reloaded.getId()));
}
@Test
public void canSaveMilestone() {
TaskMilestone milestone = createValidTaskMilestone();
taskElementDAO.save(milestone);
flushAndEvict(milestone);
TaskElement fromDB;
try {
fromDB = taskElementDAO.find(milestone.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
assertThat(fromDB.getId(), equalTo(milestone.getId()));
assertThat(fromDB, is(TaskMilestone.class));
}
@Test
public void afterSavingTheVersionIsIncreased() {
Task task = createValidTask();
assertNull(task.getVersion());
taskElementDAO.save(task);
task.dontPoseAsTransientObjectAnymore();
assertNotNull(task.getVersion());
}
@Test
public void canSaveTaskGroup() {
TaskGroup taskGroup = createValidTaskGroup();
taskElementDAO.save(taskGroup);
flushAndEvict(taskGroup);
TaskElement reloaded;
try {
reloaded = taskElementDAO.find(taskGroup.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
assertThat(reloaded.getId(), equalTo(taskGroup.getId()));
assertThat(reloaded, is(TaskGroup.class));
checkProperties(taskGroup, reloaded);
}
@Test
public void theParentPropertyIsPresentWhenRetrievingTasks() {
TaskGroup taskGroup = createValidTaskGroup();
taskGroup.addTaskElement(createValidTask());
taskElementDAO.save(taskGroup);
flushAndEvict(taskGroup);
TaskElement reloaded;
try {
reloaded = taskElementDAO.find(taskGroup.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
TaskElement child = reloaded.getChildren().get(0);
assertThat(child.getParent(), equalTo(reloaded));
}
@Test
public void savingGroupSavesAssociatedTaskElements() {
Task child1 = createValidTask();
Task child2 = createValidTask();
TaskGroup taskGroup = createValidTaskGroup();
taskGroup.addTaskElement(child1);
taskGroup.addTaskElement(child2);
taskElementDAO.save(taskGroup);
flushAndEvict(taskGroup);
TaskGroup reloaded;
try {
reloaded = (TaskGroup) taskElementDAO.find(taskGroup.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
List<TaskElement> taskElements = reloaded.getChildren();
assertThat(taskElements.size(), equalTo(2));
assertThat(taskElements.get(0).getId(), equalTo(child1.getId()));
assertThat(taskElements.get(1).getId(), equalTo(child2.getId()));
}
@Test
@NotTransactional
public void savingTaskElementSavesAssociatedDependencies()
throws InstanceNotFoundException {
IOnTransaction<Task> createValidTask = new IOnTransaction<Task>() {
@Override
public Task execute() {
return createValidTask();
}
};
final Task child1 = transactionService
.runOnTransaction(createValidTask);
final Task child2 = transactionService
.runOnTransaction(createValidTask);
IOnTransaction<Void> createDependency = new IOnTransaction<Void>() {
@Override
public Void execute() {
child1.dontPoseAsTransientObjectAnymore();
child2.dontPoseAsTransientObjectAnymore();
Dependency.create(child1, child2, Type.START_END);
taskElementDAO.save(child1);
return null;
}
};
transactionService.runOnTransaction(createDependency);
assertThat(child2.getDependenciesWithThisDestination().size(),
equalTo(1));
assertTrue(child2.getDependenciesWithThisOrigin().isEmpty());
IOnTransaction<Void> checkDependencyWasSaved = new IOnTransaction<Void>() {
@Override
public Void execute() {
TaskElement fromDB = (TaskElement) taskElementDAO
.findExistingEntity(child1.getId());
assertThat(fromDB.getDependenciesWithThisOrigin()
.size(), equalTo(1));
assertTrue(fromDB.getDependenciesWithThisDestination()
.isEmpty());
return null;
}
};
transactionService.runOnTransaction(checkDependencyWasSaved);
}
public void aTaskCanBeRemoved() {
Task task = createValidTask();
taskElementDAO.save(task);
flushAndEvict(task);
try {
taskElementDAO.remove(task.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
sessionFactory.getCurrentSession().flush();
assertNull(sessionFactory.getCurrentSession().get(TaskElement.class,
task.getId()));
}
@NotTransactional
public void testInverseManyToOneRelationshipInOrderElementIsSavedCorrectly() {
final Task task = transactionService
.runOnTransaction(new IOnTransaction<Task>() {
@Override
public Task execute() {
return createValidTask();
}
});
transactionService.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
TaskElement fromDB = taskElementDAO.findExistingEntity(task
.getId());
OrderElement orderElement = fromDB.getOrderElement();
assertThat(orderElement.getTaskElements().size(), equalTo(1));
assertThat(orderElement.getTaskElements().iterator().next(),
equalTo(fromDB));
return null;
}
});
}
@Test
@NotTransactional
public void aTaskCanBeRemovedFromItsTaskSource() {
final Task task = transactionService.runOnTransaction(new IOnTransaction<Task>(){
@Override
public Task execute() {
Task task = createValidTask();
taskElementDAO.save(task);
return task;
}});
transactionService.runOnTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
try {
taskSourceDAO.remove(task.getTaskSource().getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
sessionFactory.getCurrentSession().flush();
assertNull(sessionFactory.getCurrentSession().get(TaskElement.class,
task.getId()));
return null;
}});
}
@Test
@NotTransactional
public void aTaskGroupCanBeRemovedFromItsTaskSourceIfBelowTasksSourcesAreRemovedFirst() {
final TaskGroup taskGroupWithOneChild = transactionService
.runOnTransaction(new IOnTransaction<TaskGroup>() {
@Override
public TaskGroup execute() {
TaskGroup taskGroup = createValidTaskGroup();
Task task = createValidTask();
taskGroup.addTaskElement(task);
return taskGroup;
}
});
transactionService.runOnTransaction(new IOnTransaction<Void>() {
@Override
public Void execute() {
try {
taskSourceDAO.remove(taskGroupWithOneChild.getChildren()
.get(0).getTaskSource().getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
try {
taskSourceDAO.remove(taskGroupWithOneChild.getTaskSource()
.getId());
} catch (InstanceNotFoundException e) {
throw new RuntimeException(e);
}
sessionFactory.getCurrentSession().flush();
assertNull(sessionFactory.getCurrentSession().get(
TaskElement.class, taskGroupWithOneChild.getId()));
return null;
}
});
}
}
|
package org.eclipse.dawnsci.analysis.dataset.impl;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.text.Format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.api.dataset.ILazyDataset;
import org.eclipse.dawnsci.analysis.api.dataset.Slice;
import org.eclipse.dawnsci.analysis.api.dataset.SliceND;
import org.eclipse.dawnsci.analysis.api.metadata.ErrorMetadata;
import org.eclipse.dawnsci.analysis.api.metadata.MetadataType;
import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;
import org.eclipse.dawnsci.analysis.dataset.metadata.ErrorMetadataImpl;
/**
* Generic container class for data
* <p/>
* Each subclass has an array of primitive types, elements of this array are grouped or
* compounded to make items
* <p/>
* Data items can be boolean, integer, float, complex float, vector float, etc
*/
public abstract class AbstractDataset extends LazyDatasetBase implements Dataset {
/**
* Boolean
*/
public static final int BOOL = Dataset.BOOL;
/**
* Signed 8-bit integer
*/
public static final int INT8 = Dataset.INT8;
/**
* Signed 16-bit integer
*/
public static final int INT16 = Dataset.INT16;
/**
* Signed 32-bit integer
*/
public static final int INT32 = Dataset.INT32;
/**
* Integer (same as signed 32-bit integer)
*/
public static final int INT = Dataset.INT;
/**
* Signed 64-bit integer
*/
public static final int INT64 = Dataset.INT64;
/**
* 32-bit floating point
*/
public static final int FLOAT32 = Dataset.FLOAT32;
/**
* 64-bit floating point
*/
public static final int FLOAT64 = Dataset.FLOAT64;
/**
* Floating point (same as 64-bit floating point)
*/
public static final int FLOAT = Dataset.FLOAT;
/**
* 64-bit complex floating point (real and imaginary parts are 32-bit floats)
*/
public static final int COMPLEX64 = Dataset.COMPLEX64;
/**
* 128-bit complex floating point (real and imaginary parts are 64-bit floats)
*/
public static final int COMPLEX128 = Dataset.COMPLEX128;
/**
* Complex floating point (same as 64-bit floating point)
*/
public static final int COMPLEX = Dataset.COMPLEX;
/**
* Date
*/
public static final int DATE = Dataset.DATE;
/**
* String
*/
public static final int STRING = Dataset.STRING;
/**
* Object
*/
public static final int OBJECT = Dataset.OBJECT;
/**
* Array of signed 8-bit integers
*/
public static final int ARRAYINT8 = Dataset.ARRAYINT8;
/**
* Array of signed 16-bit integers
*/
public static final int ARRAYINT16 = Dataset.ARRAYINT16;
/**
* Array of three signed 16-bit integers for RGB values
*/
public static final int RGB = Dataset.RGB;
/**
* Array of signed 32-bit integers
*/
public static final int ARRAYINT32 = Dataset.ARRAYINT32;
/**
* Array of signed 64-bit integers
*/
public static final int ARRAYINT64 = Dataset.ARRAYINT64;
/**
* Array of 32-bit floating points
*/
public static final int ARRAYFLOAT32 = Dataset.ARRAYFLOAT32;
/**
* Array of 64-bit floating points
*/
public static final int ARRAYFLOAT64 = Dataset.ARRAYFLOAT64;
protected static boolean isDTypeElemental(int dtype) {
return dtype <= COMPLEX128 || dtype == RGB;
}
protected static boolean isDTypeInteger(int dtype) {
return dtype == INT8 || dtype == INT16 || dtype == INT32 || dtype == INT64 ||
dtype == ARRAYINT8 || dtype == ARRAYINT16 || dtype == ARRAYINT32 || dtype == ARRAYINT64 || dtype == RGB;
}
protected static boolean isDTypeFloating(int dtype) {
return dtype == FLOAT32 || dtype == FLOAT64 || dtype == COMPLEX64 || dtype == COMPLEX128 ||
dtype == ARRAYFLOAT32 || dtype == ARRAYFLOAT64;
}
protected static boolean isDTypeComplex(int dtype) {
return dtype == COMPLEX64 || dtype == COMPLEX128;
}
/**
* @param dtype
* @return true if dataset type is numerical, i.e. a dataset contains numbers
*/
public static boolean isDTypeNumerical(int dtype) {
return isDTypeInteger(dtype) || isDTypeFloating(dtype) || dtype == BOOL;
}
protected int size; // number of items
transient protected AbstractDataset base; // is null when not a view
protected int[] stride; // can be null for row-major, contiguous datasets
protected int offset;
/**
* The data itself, held in a 1D array, but the object will wrap it to appear as possessing as many dimensions as
* wanted
*/
protected Serializable odata = null;
/**
* Set aliased data as base data
*/
abstract protected void setData();
/**
* These members hold cached values. If their values are null, then recalculate, otherwise just use the values
*/
transient protected HashMap<String, Object> storedValues = null;
/**
* Constructor required for serialisation.
*/
public AbstractDataset() {
}
@Override
public synchronized Dataset synchronizedCopy() {
return clone();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(obj.getClass())) {
if (getRank() == 0) // for zero-rank datasets
return obj.equals(getObjectAbs(0));
return false;
}
Dataset other = (Dataset) obj;
if (getElementsPerItem() != other.getElementsPerItem())
return false;
if (size != other.getSize())
return false;
if (!Arrays.equals(shape, other.getShapeRef())) {
return false;
}
if (getRank() == 0) // for zero-rank datasets
return other.getObjectAbs(0).equals(getObjectAbs(0));
return true;
}
@Override
public int hashCode() {
return getHash();
}
@Override
abstract public AbstractDataset clone();
protected Format stringFormat = null;
@Override
public void setStringFormat(Format format) {
stringFormat = format;
}
@Override
public Dataset cast(final int dtype) {
if (getDtype() == dtype) {
return this;
}
return DatasetUtils.cast(this, dtype);
}
@Override
public Dataset cast(final boolean repeat, final int dtype, final int isize) {
if (getDtype() == dtype && getElementsPerItem() == isize) {
return this;
}
return DatasetUtils.cast(this, repeat, dtype, isize);
}
@Override
abstract public AbstractDataset getView();
/**
* Copy fields from original to view
* @param orig
* @param view
* @param clone if true, then clone everything but bulk data
* @param cloneMetadata if true, clone metadata
*/
protected static void copyToView(Dataset orig, AbstractDataset view, boolean clone, boolean cloneMetadata) {
view.name = orig.getName();
view.size = orig.getSize();
view.odata = orig.getBuffer();
view.offset = orig.getOffset();
view.base = orig instanceof AbstractDataset ? ((AbstractDataset) orig).base : null;
if (clone) {
view.shape = orig.getShape();
copyStoredValues(orig, view, false);
view.stride = orig instanceof AbstractDataset && ((AbstractDataset) orig).stride != null ?
((AbstractDataset) orig).stride.clone() : null;
} else {
view.shape = orig.getShapeRef();
view.stride = orig instanceof AbstractDataset ? ((AbstractDataset) orig).stride : null;
}
view.metadata = getMetadataMap(orig, cloneMetadata);
int odtype = orig.getDtype();
int vdtype = view.getDtype();
if (getBestDType(odtype, vdtype) != vdtype) {
view.storedValues = null; // as copy is a demotion
}
if (odtype != vdtype && view.storedValues != null) {
view.storedValues.remove(STORE_SHAPELESS_HASH);
view.storedValues.remove(STORE_HASH);
}
}
protected static Map<Class<? extends MetadataType>, List<MetadataType>> getMetadataMap(Dataset a, boolean clone) {
if (a == null)
return null;
List<MetadataType> all = null;
try {
all = a.getMetadata(null);
} catch (Exception e) {
}
if (all == null)
return null;
HashMap<Class<? extends MetadataType>, List<MetadataType>> map = new HashMap<Class<? extends MetadataType>, List<MetadataType>>();
for (MetadataType m : all) {
if (m == null) {
continue;
}
Class<? extends MetadataType> c = findMetadataTypeSubInterfaces(m.getClass());
List<MetadataType> l = map.get(c);
if (l == null) {
l = new ArrayList<MetadataType>();
map.put(c, l);
}
if (clone)
m = m.clone();
l.add(m);
}
return map;
}
@Override
public IntegerDataset getIndices() {
final IntegerDataset ret = DatasetUtils.indices(shape);
if (getName() != null) {
ret.setName("Indices of " + getName());
}
return ret;
}
@Override
public Dataset getTransposedView(int... axes) {
axes = checkPermutatedAxes(shape, axes);
AbstractDataset t = getView();
if (axes == null || getRank() == 1)
return t;
int rank = shape.length;
int[] tstride = new int[rank];
int[] toffset = new int[1];
int[] nshape = createStrides(new SliceND(shape), this, tstride, toffset);
int[] nstride = new int[rank];
for (int i = 0; i < rank; i++) {
final int ax = axes[i];
nstride[i] = tstride[ax];
nshape[i] = shape[ax];
}
t.shape = nshape;
t.stride = nstride;
t.offset = toffset[0];
t.base = base == null ? this : base;
copyStoredValues(this, t, true);
t.transposeMetadata(axes);
return t;
}
@Override
public Dataset transpose(int... axes) {
Dataset t = getTransposedView(axes);
return t == null ? clone() : t.clone();
}
@Override
public Dataset swapAxes(int axis1, int axis2) {
int rank = shape.length;
if (axis1 < 0)
axis1 += rank;
if (axis2 < 0)
axis2 += rank;
if (axis1 < 0 || axis2 < 0 || axis1 >= rank || axis2 >= rank) {
logger.error("Axis value invalid - out of range");
throw new IllegalArgumentException("Axis value invalid - out of range");
}
if (rank == 1 || axis1 == axis2) {
return this;
}
int[] axes = new int[rank];
for (int i = 0; i < rank; i++) {
axes[i] = i;
}
axes[axis1] = axis2;
axes[axis2] = axis1;
return getTransposedView(axes);
}
@Override
public Dataset flatten() {
if (stride != null) { // need to make a copy if not contiguous
return clone().flatten();
}
return reshape(size);
}
/**
* Calculate total number of items in given shape
* @param shape
* @return size
*/
public static long calcLongSize(final int[] shape) {
double dsize = 1.0;
if (shape == null || shape.length == 0) // special case of zero-rank shape
return 1;
for (int i = 0; i < shape.length; i++) {
// make sure the indexes isn't zero or negative
if (shape[i] == 0) {
return 0;
} else if (shape[i] < 0) {
throw new IllegalArgumentException(String.format(
"The %d-th is %d which is an illegal argument as it is negative", i, shape[i]));
}
dsize *= shape[i];
}
// check to see if the size is larger than an integer, i.e. we can't allocate it
if (dsize > Long.MAX_VALUE) {
throw new IllegalArgumentException("Size of the dataset is too large to allocate");
}
return (long) dsize;
}
/**
* Calculate total number of items in given shape
* @param shape
* @return size
*/
public static int calcSize(final int[] shape) {
long lsize = calcLongSize(shape);
// check to see if the size is larger than an integer, i.e. we can't allocate it
if (lsize > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Size of the dataset is too large to allocate");
}
return (int) lsize;
}
/**
* Find dataset type that best fits given types The best type takes into account complex and array datasets
*
* @param atype
* first dataset type
* @param btype
* second dataset type
* @return best dataset type
*/
public static int getBestDType(final int atype, final int btype) {
int besttype;
int a = atype >= ARRAYINT8 ? atype / ARRAYMUL : atype;
int b = btype >= ARRAYINT8 ? btype / ARRAYMUL : btype;
if (isDTypeFloating(a)) {
if (!isDTypeFloating(b)) {
b = getBestFloatDType(b);
if (isDTypeComplex(a)) {
b += COMPLEX64 - FLOAT32;
}
}
} else if (isDTypeFloating(b)) {
a = getBestFloatDType(a);
if (isDTypeComplex(b)) {
a += COMPLEX64 - FLOAT32;
}
}
besttype = a > b ? a : b;
if (atype >= ARRAYINT8 || btype >= ARRAYINT8) {
if (besttype >= COMPLEX64) {
throw new IllegalArgumentException("Complex type cannot be promoted to compound type");
}
besttype *= ARRAYMUL;
}
return besttype;
}
/**
* The largest dataset type suitable for a summation of around a few thousand items without changing from the "kind"
* of dataset
*
* @param otype
* @return largest dataset type available for given dataset type
*/
public static int getLargestDType(final int otype) {
switch (otype) {
case BOOL:
case INT8:
case INT16:
return INT32;
case INT32:
case INT64:
return INT64;
case FLOAT32:
case FLOAT64:
return FLOAT64;
case COMPLEX64:
case COMPLEX128:
return COMPLEX128;
case ARRAYINT8:
case ARRAYINT16:
return ARRAYINT32;
case ARRAYINT32:
case ARRAYINT64:
return ARRAYINT64;
case ARRAYFLOAT32:
case ARRAYFLOAT64:
return ARRAYFLOAT64;
case STRING:
case RGB:
case OBJECT:
return otype;
}
throw new IllegalArgumentException("Unsupported dataset type");
}
/**
* Find floating point dataset type that best fits given types The best type takes into account complex and array
* datasets
*
* @param otype
* old dataset type
* @return best dataset type
*/
public static int getBestFloatDType(final int otype) {
int btype;
switch (otype) {
case BOOL:
case INT8:
case INT16:
case ARRAYINT8:
case ARRAYINT16:
case FLOAT32:
case ARRAYFLOAT32:
case COMPLEX64:
btype = FLOAT32; // demote, if necessary
break;
case INT32:
case INT64:
case ARRAYINT32:
case ARRAYINT64:
case FLOAT64:
case ARRAYFLOAT64:
case COMPLEX128:
btype = FLOAT64; // promote, if necessary
break;
default:
btype = otype; // for array datasets, preserve type
break;
}
return btype;
}
/**
* Find floating point dataset type that best fits given class The best type takes into account complex and array
* datasets
*
* @param cls
* of an item or element
* @return best dataset type
*/
public static int getBestFloatDType(Class<? extends Object> cls) {
return getBestFloatDType(getDTypeFromClass(cls));
}
transient private static final Map<Class<?>, Integer> dtypeMap = createDTypeMap();
private static Map<Class<?>, Integer> createDTypeMap() {
Map<Class<?>, Integer> result = new HashMap<Class<?>, Integer>();
result.put(Boolean.class, BOOL);
result.put(Byte.class, INT8);
result.put(Short.class, INT16);
result.put(Integer.class, INT32);
result.put(Long.class, INT64);
result.put(Float.class, FLOAT32);
result.put(Double.class, FLOAT64);
result.put(boolean.class, BOOL);
result.put(byte.class, INT8);
result.put(short.class, INT16);
result.put(int.class, INT32);
result.put(long.class, INT64);
result.put(float.class, FLOAT32);
result.put(double.class, FLOAT64);
result.put(Complex.class, COMPLEX128);
result.put(String.class, STRING);
result.put(Date.class, DATE);
result.put(Object.class, OBJECT);
return result;
}
/**
* Get dataset type from a class
*
* @param cls
* @return dataset type
*/
public static int getDTypeFromClass(Class<? extends Object> cls) {
return getDTypeFromClass(cls, 1);
}
/**
* Get dataset type from a class
*
* @param cls
* @return dataset type
*/
public static int getDTypeFromClass(Class<? extends Object> cls, int isize) {
Integer dtype = dtypeMap.get(cls);
if (dtype == null) {
throw new IllegalArgumentException("Class of object not supported");
}
if (isize != 1) {
if (dtype < FLOAT64)
dtype *= ARRAYMUL;
}
return dtype;
}
/**
* Get dataset type from an object. The following are supported: Java Number objects, Apache common math Complex
* objects, Java arrays and lists
*
* @param obj
* @return dataset type
*/
public static int getDTypeFromObject(Object obj) {
int dtype = -1;
if (obj == null) {
return dtype;
}
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
for (int i = 0; i < l; i++) {
int ldtype = getDTypeFromObject(jl.get(i));
if (ldtype > dtype) {
dtype = ldtype;
}
}
} else if (obj.getClass().isArray()) {
Class<?> ca = obj.getClass().getComponentType();
if (isComponentSupported(ca)) {
return getDTypeFromClass(ca);
}
int l = Array.getLength(obj);
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
int ldtype = getDTypeFromObject(lo);
if (ldtype > dtype) {
dtype = ldtype;
}
}
} else if (obj instanceof Dataset) {
return ((Dataset) obj).getDtype();
} else if (obj instanceof ILazyDataset) {
dtype = getDTypeFromClass(((ILazyDataset) obj).elementClass(), ((ILazyDataset) obj).getElementsPerItem());
} else {
dtype = getDTypeFromClass(obj.getClass());
}
return dtype;
}
/**
* @param comp
* @return true if supported
*/
public static boolean isComponentSupported(Class<? extends Object> comp) {
return comp.isPrimitive() || Number.class.isAssignableFrom(comp) || comp.equals(Boolean.class) || comp.equals(Complex.class) || comp.equals(String.class);
}
/**
* Get dataset type from given dataset
* @param d
* @return dataset type
*/
public static int getDType(ILazyDataset d) {
if (d instanceof LazyDatasetBase)
return ((LazyDatasetBase) d).getDtype();
return getDTypeFromClass(d.elementClass(), d.getElementsPerItem());
}
/**
* Get shape from object (array or list supported)
* @param obj
* @return shape
*/
public static int[] getShapeFromObject(final Object obj) {
ArrayList<Integer> lshape = new ArrayList<Integer>();
getShapeFromObj(lshape, obj, 0);
if (obj != null && lshape.size() == 0) {
return new int[0]; // cope with a single item
}
final int rank = lshape.size();
final int[] shape = new int[rank];
for (int i = 0; i < rank; i++) {
shape[i] = lshape.get(i);
}
return shape;
}
/**
* Get shape from object
* @param ldims
* @param obj
* @param depth
* @return true if there is a possibility of differing lengths
*/
private static boolean getShapeFromObj(final ArrayList<Integer> ldims, Object obj, int depth) {
if (obj == null)
return true;
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
updateShape(ldims, depth, l);
for (int i = 0; i < l; i++) {
Object lo = jl.get(i);
if (!getShapeFromObj(ldims, lo, depth + 1)) {
break;
}
}
return true;
}
Class<? extends Object> ca = obj.getClass().getComponentType();
if (ca != null) {
final int l = Array.getLength(obj);
updateShape(ldims, depth, l);
if (isComponentSupported(ca)) {
return true;
}
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
if (!getShapeFromObj(ldims, lo, depth + 1)) {
break;
}
}
return true;
} else if (obj instanceof IDataset) {
int[] s = ((IDataset) obj).getShape();
for (int i = 0; i < s.length; i++) {
updateShape(ldims, depth++, s[i]);
}
return true;
} else {
return false; // not an array of any type
}
}
private static void updateShape(final ArrayList<Integer> ldims, final int depth, final int l) {
if (depth >= ldims.size()) {
ldims.add(l);
} else if (l > ldims.get(depth)) {
ldims.set(depth, l);
}
}
/**
* Fill dataset from object at depth dimension
* @param obj
* @param depth
* @param pos position
*/
protected void fillData(Object obj, final int depth, final int[] pos) {
if (obj == null) {
int dtype = getDtype();
if (dtype == FLOAT32)
set(Float.NaN, pos);
else if (dtype == FLOAT64)
set(Double.NaN, pos);
return;
}
Class<?> clazz = obj.getClass();
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
for (int i = 0; i < l; i++) {
Object lo = jl.get(i);
fillData(lo, depth + 1, pos);
pos[depth]++;
}
pos[depth] = 0;
} else if (clazz.isArray()) {
int l = Array.getLength(obj);
if (clazz.equals(odata.getClass())) {
System.arraycopy(obj, 0, odata, get1DIndex(pos), l);
} else if (clazz.getComponentType().isPrimitive()) {
for (int i = 0; i < l; i++) {
set(Array.get(obj, i), pos);
pos[depth]++;
}
pos[depth] = 0;
} else {
for (int i = 0; i < l; i++) {
fillData(Array.get(obj, i), depth + 1, pos);
pos[depth]++;
}
pos[depth] = 0;
}
} else if (obj instanceof IDataset) {
boolean[] a = new boolean[shape.length];
for (int i = depth; i < a.length; i++)
a[i] = true;
setSlice(obj, getSliceIteratorFromAxes(pos, a));
} else {
set(obj, pos);
}
}
protected static boolean toBoolean(final Object b) {
if (b instanceof Number) {
return ((Number) b).longValue() != 0;
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue();
} else if (b instanceof Complex) {
return ((Complex) b).getReal() != 0;
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toBoolean(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (IDataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toBoolean(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static long toLong(final Object b) {
if (b instanceof Number) {
return ((Number) b).longValue();
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue() ? 1 : 0;
} else if (b instanceof Complex) {
return (long) ((Complex) b).getReal();
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toLong(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (IDataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toLong(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static double toReal(final Object b) {
if (b instanceof Number) {
return ((Number) b).doubleValue();
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue() ? 1 : 0;
} else if (b instanceof Complex) {
return ((Complex) b).getReal();
} else if (b.getClass().isArray()) {
if (Array.getLength(b) == 0)
return 0;
return toReal(Array.get(b, 0));
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toReal(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toReal(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static double toImag(final Object b) {
if (b instanceof Number) {
return 0;
} else if (b instanceof Boolean) {
return 0;
} else if (b instanceof Complex) {
return ((Complex) b).getImaginary();
} else if (b.getClass().isArray()) {
if (Array.getLength(b) < 2)
return 0;
return toReal(Array.get(b, 1));
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toImag(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toImag(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
@Override
public IndexIterator getIterator(final boolean withPosition) {
if (stride != null)
return new StrideIterator(shape, stride, offset);
return withPosition ? new ContiguousIteratorWithPosition(shape, size) : new ContiguousIterator(size);
}
@Override
public IndexIterator getIterator() {
return getIterator(false);
}
@Override
public PositionIterator getPositionIterator(final int... axes) {
return new PositionIterator(shape, axes);
}
@Override
public IndexIterator getSliceIterator(final int[] start, final int[] stop, final int[] step) {
return getSliceIterator(new SliceND(shape, start, stop, step));
}
/**
* @param slice
* @return an slice iterator that operates like an IndexIterator
*/
public IndexIterator getSliceIterator(SliceND slice) {
if (calcLongSize(slice.getShape()) == 0) {
return new NullIterator(shape, slice.getShape());
}
if (stride != null)
return new StrideIterator(getElementsPerItem(), shape, stride, offset, slice);
return new SliceIterator(shape, size, slice);
}
@Override
public SliceIterator getSliceIteratorFromAxes(final int[] pos, boolean[] axes) {
int rank = shape.length;
int[] start;
int[] stop = new int[rank];
int[] step = new int[rank];
if (pos == null) {
start = new int[rank];
} else if (pos.length == rank) {
start = pos.clone();
} else {
throw new IllegalArgumentException("pos array length is not equal to rank of dataset");
}
if (axes == null) {
axes = new boolean[rank];
Arrays.fill(axes, true);
} else if (axes.length != rank) {
throw new IllegalArgumentException("axes array length is not equal to rank of dataset");
}
for (int i = 0; i < rank; i++) {
if (axes[i]) {
stop[i] = shape[i];
} else {
stop[i] = start[i] + 1;
}
step[i] = 1;
}
return (SliceIterator) getSliceIterator(start, stop, step);
}
@Override
public BooleanIterator getBooleanIterator(Dataset choice) {
return getBooleanIterator(choice, true);
}
@Override
public BooleanIterator getBooleanIterator(Dataset choice, boolean value) {
return new BooleanIterator(getIterator(), choice, value);
}
@Override
public Dataset getByBoolean(Dataset selection) {
checkCompatibility(selection);
final int length = ((Number) selection.sum()).intValue();
final int is = getElementsPerItem();
Dataset r = DatasetFactory.zeros(is, new int[] { length }, getDtype());
BooleanIterator biter = getBooleanIterator(selection);
int i = 0;
while (biter.hasNext()) {
r.setObjectAbs(i, getObjectAbs(biter.index));
i += is;
}
return r;
}
@Override
public Dataset getBy1DIndex(IntegerDataset index) {
final int is = getElementsPerItem();
final Dataset r = DatasetFactory.zeros(is, index.getShape(), getDtype());
final IntegerIterator iter = new IntegerIterator(index, size, is);
int i = 0;
while (iter.hasNext()) {
r.setObjectAbs(i, getObjectAbs(iter.index));
i += is;
}
return r;
}
@Override
public Dataset getByIndexes(final Object... indexes) {
final IntegersIterator iter = new IntegersIterator(shape, indexes);
final int is = getElementsPerItem();
final Dataset r = DatasetFactory.zeros(is, iter.getShape(), getDtype());
final int[] pos = iter.getPos();
int i = 0;
while (iter.hasNext()) {
r.setObjectAbs(i, getObject(pos));
i += is;
}
return r;
}
/**
* @param dtype
* @return (boxed) class of constituent element
*/
public static Class<?> elementClass(final int dtype) {
switch (dtype) {
case BOOL:
return Boolean.class;
case INT8:
case ARRAYINT8:
return Byte.class;
case INT16:
case ARRAYINT16:
case RGB:
return Short.class;
case INT32:
case ARRAYINT32:
return Integer.class;
case INT64:
case ARRAYINT64:
return Long.class;
case FLOAT32:
case ARRAYFLOAT32:
return Float.class;
case FLOAT64:
case ARRAYFLOAT64:
return Double.class;
case COMPLEX64:
return Float.class;
case COMPLEX128:
return Double.class;
case STRING:
return String.class;
}
return Object.class;
}
@Override
public Class<?> elementClass() {
return elementClass(getDtype());
}
@Override
public boolean hasFloatingPointElements() {
Class<?> cls = elementClass();
return cls == Float.class || cls == Double.class;
}
@Override
public int getElementsPerItem() {
return getElementsPerItem(getDtype());
}
@Override
public int getItemsize() {
return getItemsize(getDtype(), getElementsPerItem());
}
/**
* @param dtype
* @return number of elements per item
*/
public static int getElementsPerItem(final int dtype) {
switch (dtype) {
case ARRAYINT8:
case ARRAYINT16:
case ARRAYINT32:
case ARRAYINT64:
case ARRAYFLOAT32:
case ARRAYFLOAT64:
throw new UnsupportedOperationException("Multi-element type unsupported");
case COMPLEX64:
case COMPLEX128:
return 2;
}
return 1;
}
/**
* @param dtype
* @return length of single item in bytes
*/
public static int getItemsize(final int dtype) {
return getItemsize(dtype, getElementsPerItem(dtype));
}
/**
* @param dtype
* @param isize
* number of elements in an item
* @return length of single item in bytes
*/
public static int getItemsize(final int dtype, final int isize) {
int size;
switch (dtype) {
case BOOL:
size = 1; // How is this defined?
break;
case INT8:
case ARRAYINT8:
size = Byte.SIZE / 8;
break;
case INT16:
case ARRAYINT16:
case RGB:
size = Short.SIZE / 8;
break;
case INT32:
case ARRAYINT32:
size = Integer.SIZE / 8;
break;
case INT64:
case ARRAYINT64:
size = Long.SIZE / 8;
break;
case FLOAT32:
case ARRAYFLOAT32:
case COMPLEX64:
size = Float.SIZE / 8;
break;
case FLOAT64:
case ARRAYFLOAT64:
case COMPLEX128:
size = Double.SIZE / 8;
break;
default:
size = 0;
break;
}
return size * isize;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(final String name) {
this.name = name;
}
@Override
public int getSize() {
if (odata == null) {
throw new NullPointerException("The data object inside the dataset has not been allocated, "
+ "this suggests a failed or absent construction of the dataset");
}
return size;
}
@Override
public int[] getShape() {
// make a copy of the dimensions data, and put that out
if (shape == null) {
logger.warn("Shape is null!!!");
return new int[] {};
}
return shape.clone();
}
@Override
public int getRank() {
return shape.length;
}
@Override
public int getNbytes() {
return getSize() * getItemsize();
}
/**
* Check for -1 placeholder in shape and replace if necessary
* @param shape
* @param size
*/
private void checkShape(int[] shape, int size) {
int rank = shape.length;
int found = -1;
int nsize = 1;
for (int i = 0; i < rank; i++) {
int d = shape[i];
if (d == -1) {
if (found == -1) {
found = i;
} else {
logger.error("Can only have one -1 placeholder in shape");
throw new IllegalArgumentException("Can only have one -1 placeholder in shape");
}
} else {
nsize *= d;
}
}
if (found >= 0) {
shape[found] = size/nsize;
} else if (nsize != size) {
logger.error("New shape is not same size as old shape");
throw new IllegalArgumentException("New size is not same as the old size. Old size is "+size+" new size is "+nsize+" and shape is "+Arrays.toString(shape));
}
}
@Override
public void setShape(final int... shape) {
int[] nshape = shape.clone();
checkShape(nshape, size);
if (Arrays.equals(this.shape, nshape))
return;
if (stride != null) {
// the only compatible shapes are ones where new dimensions are factors of old dimensions
// or are combined adjacent old dimensions
int[] oshape = this.shape;
int orank = oshape.length;
int nrank = nshape.length;
int diff = nrank - orank;
int[] nstride = new int[nrank];
boolean ones = true;
// work forwards for broadcasting cases
for (int i = 0, j = 0; i < orank || j < nrank;) {
if (j >= diff && i < orank && j < nrank && oshape[i] == nshape[j]) {
nstride[j++] = stride[i++];
} else if (j < nrank && nshape[j] == 1) {
nstride[j++] = 0;
} else if (i < orank && oshape[i] == 1) {
i++;
} else {
if (j < nrank)
j++;
if (i < orank)
i++;
ones = false;
}
}
if (!ones) { // not just ones differ in shapes
int[] ostride = stride;
int ob = 0;
int oe = 1;
int nb = 0;
int ne = 1;
while (ob < orank && nb < nrank) {
int ol = oshape[ob];
int nl = nshape[nb];
if (nl < ol) { // find group of shape dimensions that form common size
do { // case where new shape spreads single dimension over several dimensions
if (ne == nrank) {
break;
}
nl *= nshape[ne++];
} while (nl < ol);
if (nl != ol) {
logger.error("Subshape is incompatible with single dimension");
throw new IllegalArgumentException("Subshape is incompatible with single dimension");
}
int on = ne - 1;
while (nshape[on] == 1) {
on
}
nstride[on] = ostride[ob];
for (int n = on - 1; n >= nb; n
if (nshape[n] == 1)
continue;
nstride[n] = nshape[on] * nstride[on];
on = n;
}
} else if (ol < nl) {
do { // case where new shape combines several dimensions into one dimension
if (oe == orank) {
break;
}
ol *= oshape[oe++];
} while (ol < nl);
if (nl != ol) {
logger.error("Single dimension is incompatible with subshape");
throw new IllegalArgumentException("Single dimension is incompatible with subshape");
}
int oo = oe - 1;
while (oshape[oo] == 1) {
oo
}
int os = ostride[oo];
for (int o = oo - 1; o >= ob; o
if (oshape[o] == 1)
continue;
if (ostride[o] != oshape[oo] * ostride[oo]) {
logger.error("Subshape cannot be a non-contiguous view");
throw new IllegalArgumentException("Subshape cannot be a non-contiguous view");
}
oo = o;
}
nstride[nb] = os;
} else {
nstride[nb] = ostride[ob];
}
ob = oe++;
nb = ne++;
}
}
stride = nstride;
}
reshapeMetadata(this.shape, nshape);
this.shape = nshape;
if (storedValues != null)
filterStoredValues(storedValues); // as it is dependent on shape
}
@Override
public int[] getShapeRef() {
return shape;
}
@Override
public int getOffset() {
return offset;
}
@Override
public int[] getStrides() {
return stride;
}
@Override
public Serializable getBuffer() {
return odata;
}
/**
* Create a stride array from dataset
* @param a dataset
* @param offset output offset
* @return new strides
*/
public static int[] createStrides(Dataset a, final int[] offset) {
return createStrides(a.getElementsPerItem(), a.getShapeRef(), a.getStrides(), a.getOffset(), offset);
}
/**
* Create a stride array from dataset
* @param isize
* @param shape
* @param oStride original stride
* @param oOffset original offset (only used if there is an original stride)
* @param offset output offset
* @return new strides
*/
public static int[] createStrides(final int isize, final int[] shape, final int[] oStride, final int oOffset, final int[] offset) {
int rank = shape.length;
final int[] stride;
if (oStride == null) {
offset[0] = 0;
stride = new int[rank];
int s = isize;
for (int j = rank - 1; j >= 0; j
stride[j] = s;
s *= shape[j];
}
} else {
offset[0] = oOffset;
stride = oStride.clone();
}
return stride;
}
/**
* Create a stride array from slice information and a dataset
* @param slice
* @param a dataset
* @param stride output stride
* @param offset output offset
* @return new shape
*/
public static int[] createStrides(final SliceND slice, final Dataset a, final int[] stride, final int[] offset) {
return createStrides(slice, a.getElementsPerItem(), a.getShapeRef(), a.getStrides(), a.getOffset(), stride, offset);
}
/**
* Create a stride array from slice and dataset information
* @param slice
* @param isize
* @param shape
* @param oStride original stride
* @param oOffset original offset (only used if there is an original stride)
* @param stride output stride
* @param offset output offset
* @return new shape
*/
public static int[] createStrides(final SliceND slice, final int isize, final int[] shape, final int[] oStride, final int oOffset, final int[] stride, final int[] offset) {
int[] lstart = slice.getStart();
int[] lstep = slice.getStep();
int[] newShape = slice.getShape();
int rank = shape.length;
if (oStride == null) {
int s = isize;
offset[0] = 0;
for (int j = rank - 1; j >= 0; j
stride[j] = s * lstep[j];
offset[0] += s * lstart[j];
s *= shape[j];
}
} else {
offset[0] = oOffset;
for (int j = 0; j < rank; j++) {
int s = oStride[j];
stride[j] = lstep[j] * s;
offset[0] += lstart[j] * s;
}
}
return newShape;
}
@Override
public Dataset getBroadcastView(int... broadcastShape) {
AbstractDataset view = getView();
if (!Arrays.equals(shape, broadcastShape)) {
List<int[]> nShapes = BroadcastUtils.broadcastShapesToMax(broadcastShape, shape);
view.setShape(nShapes.get(0));
view.stride = BroadcastUtils.createBroadcastStrides(view, broadcastShape);
view.shape = broadcastShape.clone();
view.size = calcSize(broadcastShape);
if (view.name == null || view.name.isEmpty()) {
view.name = "Broadcast from " + Arrays.toString(shape);
} else {
view.name = "Broadcast of " + view.name + " from " + Arrays.toString(shape);
}
}
return view;
}
@Override
public Dataset getSliceView(final int[] start, final int[] stop, final int[] step) {
return getSliceView(new SliceND(shape, start, stop, step));
}
@Override
public Dataset getSliceView(Slice... slice) {
if (slice == null || slice.length == 0) {
return getView();
}
return getSliceView(new SliceND(shape, slice));
}
/**
* Get a slice of the dataset. The returned dataset is a view on a selection of items
* @param slice
* @return slice view
*/
@Override
public Dataset getSliceView(SliceND slice) {
if (slice.isAll()) {
return getView();
}
final int rank = shape.length;
int[] sStride = new int[rank];
int[] sOffset = new int[1];
int[] sShape = createStrides(slice, this, sStride, sOffset);
AbstractDataset s = getView();
s.shape = sShape;
s.size = calcSize(sShape);
s.stride = sStride;
s.offset = sOffset[0];
s.base = base == null ? this : base;
s.metadata = copyMetadata();
s.sliceMetadata(true, slice);
s.setDirty();
s.setName(name + BLOCK_OPEN + slice + BLOCK_CLOSE);
return s;
}
/**
* Get flattened view index of given position
* @param pos
* the integer array specifying the n-D position
* @return the index on the flattened dataset
*/
private int getFlat1DIndex(final int[] pos) {
final int imax = pos.length;
if (imax == 0) {
return 0;
}
return get1DIndexFromShape(pos);
}
/**
* Get flattened view index of given position
* @param shape
* @param pos
* the integer array specifying the n-D position
* @return the index on the flattened dataset
*/
public static int getFlat1DIndex(final int[] shape, final int[] pos) {
final int imax = pos.length;
if (imax == 0) {
return 0;
}
return get1DIndexFromShape(shape, pos);
}
@Override
public int get1DIndex(final int... n) {
final int imax = n.length;
final int rank = shape.length;
if (imax == 0) {
if (rank == 0 || (rank == 1 && shape[0] <= 1))
return stride == null ? 0 : offset;
throw new IllegalArgumentException("One or more index parameters must be supplied");
} else if (imax > rank) {
throw new IllegalArgumentException("No of index parameters is different to the shape of data: " + imax
+ " given " + rank + " required");
}
return stride == null ? get1DIndexFromShape(n) : get1DIndexFromStrides(n);
}
private static void throwAIOOBException(int i, int s, int d) {
throw new ArrayIndexOutOfBoundsException("Index (" + i + ") out of range [-" + s + "," + s
+ "] in dimension " + d);
}
/**
* @param i
* @return the index on the data array corresponding to that location
*/
protected int get1DIndex(int i) {
if (shape.length > 1) {
logger.debug("This dataset is not 1D but was addressed as such");
return get1DIndex(new int[] {i});
}
if (i < 0) {
i += shape[0];
}
if (i < 0 || i >= shape[0]) {
throwAIOOBException(i, shape[0], 0);
}
return stride == null ? i : i*stride[0] + offset;
}
/**
* @param i
* @param j
* @return the index on the data array corresponding to that location
*/
protected int get1DIndex(int i, int j) {
if (shape.length != 2) {
logger.debug("This dataset is not 2D but was addressed as such");
return get1DIndex(new int[] {i, j});
}
if (i < 0) {
i += shape[0];
}
if (i < 0 || i >= shape[0]) {
throwAIOOBException(i, shape[0], 0);
}
if (j < 0) {
j += shape[1];
}
if (j < 0 || j >= shape[1]) {
throwAIOOBException(i, shape[1], 1);
}
return stride == null ? i*shape[1] + j : i*stride[0] + j*stride[1] + offset;
}
protected int get1DIndexFromShape(final int... n) {
return get1DIndexFromShape(shape, n);
}
protected static int get1DIndexFromShape(final int[] shape, final int... n) {
final int imax = n.length;
final int rank = shape.length;
// if (rank != imax) {
int index = 0;
int i = 0;
for (; i < imax; i++) {
final int si = shape[i];
int ni = n[i];
if (ni < 0) {
ni += si;
}
if (ni < 0 || ni >= si) {
throwAIOOBException(ni, si, i);
}
index = index * si + ni;
}
for (; i < rank; i++) {
index *= shape[i];
}
return index;
}
private int get1DIndexFromStrides(final int... n) {
return get1DIndexFromStrides(shape, stride, offset, n);
}
private static int get1DIndexFromStrides(final int[] shape, final int[] stride, final int offset, final int... n) {
final int rank = shape.length;
if (rank != n.length) {
throw new IllegalArgumentException("Number of position indexes must be equal to rank");
}
int index = offset;
for (int i = 0; i < rank; i++) {
final int st = stride[i];
if (st != 0) { // not broadcasted
final int si = shape[i];
int ni = n[i];
if (ni < 0) {
ni += si;
}
if (ni < 0 || ni >= si) {
throwAIOOBException(ni, si, i);
}
index += st * ni;
}
}
return index;
}
@Override
public int[] getNDPosition(final int n) {
if (isIndexInRange(n)) {
throw new IllegalArgumentException("Index provided " + n
+ "is larger then the size of the containing array");
}
return stride == null ? getNDPositionFromShape(n, shape) : getNDPositionFromStrides(n);
}
private boolean isIndexInRange(final int n) {
if (stride == null) {
return n >= size;
}
return n >= getBufferLength();
}
/**
* @return entire buffer length
*/
abstract protected int getBufferLength();
/**
* Get n-D position from given index
* @param n index
* @param shape
* @return n-D position
*/
public static int[] getNDPositionFromShape(int n, int[] shape) {
if (shape == null || shape.length == 0)
return new int[0];
int rank = shape.length;
if (rank == 1) {
return new int[] { n };
}
int[] output = new int[rank];
for (rank--; rank > 0; rank--) {
output[rank] = n % shape[rank];
n /= shape[rank];
}
output[0] = n;
return output;
}
private int[] getNDPositionFromStrides(int n) {
n -= offset;
int rank = shape.length;
if (rank == 1) {
return new int[] { n / stride[0] };
}
int[] output = new int[rank];
int i = 0;
while (i != n) { // TODO find more efficient way than this exhaustive search
int j = rank - 1;
for (; j >= 0; j
output[j]++;
i += stride[j];
if (output[j] >= shape[j]) {
output[j] = 0;
i -= shape[j] * stride[j];
} else {
break;
}
}
if (j == -1) {
logger.error("Index was not found in this strided dataset");
throw new IllegalArgumentException("Index was not found in this strided dataset");
}
}
return output;
}
@Override
public int checkAxis(int axis) {
return checkAxis(shape.length, axis);
}
/**
* Check that axis is in range [-rank,rank)
*
* @param rank
* @param axis
* @return sanitized axis in range [0, rank)
*/
protected static int checkAxis(int rank, int axis) {
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
throw new IndexOutOfBoundsException("Axis " + axis + " given is out of range [0, " + rank + ")");
}
return axis;
}
protected static final char BLOCK_OPEN = '[';
protected static final char BLOCK_CLOSE = ']';
@Override
public String toString() {
return toString(false);
}
@Override
public String toString(boolean showData) {
final int rank = shape == null ? 0 : shape.length;
final StringBuilder out = new StringBuilder();
if (!showData) {
if (name != null && name.length() > 0) {
out.append("Dataset '");
out.append(name);
out.append("' has shape ");
} else {
out.append("Dataset shape is ");
}
out.append(BLOCK_OPEN);
if (rank > 0) {
out.append(shape[0]);
}
for (int i = 1; i < rank; i++) {
out.append(", " + shape[i]);
}
out.append(BLOCK_CLOSE);
return out.toString();
}
if (size == 0) {
return out.toString();
}
if (rank > 0) {
int[] pos = new int[rank];
final StringBuilder lead = new StringBuilder();
printBlocks(out, lead, 0, pos);
} else {
out.append(getString());
}
return out.toString();
}
/**
* Limit to strings output via the toString() method
*/
private static int maxStringLength = 120;
/**
* Set maximum line length for toString() method
* @param maxLineLength
*/
public static void setMaxLineLength(int maxLineLength) {
maxStringLength = maxLineLength;
}
/**
* @return maximum line length for toString() method
*/
public static int getMaxLineLength() {
return maxStringLength;
}
/**
* Limit to number of sub-blocks output via the toString() method
*/
private static final int MAX_SUBBLOCKS = 6;
private final static String SEPARATOR = ",";
private final static String SPACE = " ";
private final static String ELLIPSIS = "...";
private final static String NEWLINE = "\n";
/**
* Make a line of output for last dimension of dataset
*
* @param start
* @return line
*/
private StringBuilder makeLine(final int end, final int... start) {
StringBuilder line = new StringBuilder();
final int[] pos;
if (end >= start.length) {
pos = Arrays.copyOf(start, end + 1);
} else {
pos = start;
}
pos[end] = 0;
line.append(BLOCK_OPEN);
line.append(getString(pos));
final int length = shape[end];
// trim elements printed if length exceed estimate of maximum elements
int excess = length - maxStringLength / 3; // space + number + separator
if (excess > 0) {
int index = (length - excess) / 2;
for (int y = 1; y < index; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
index = (length + excess) / 2;
for (int y = index; y < length; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
} else {
for (int y = 1; y < length; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
}
line.append(BLOCK_CLOSE);
// trim string down to limit
excess = line.length() - maxStringLength - ELLIPSIS.length() - 1;
if (excess > 0) {
int index = line.substring(0, (line.length() - excess) / 2).lastIndexOf(SEPARATOR) + 2;
StringBuilder out = new StringBuilder(line.subSequence(0, index));
out.append(ELLIPSIS + SEPARATOR);
index = line.substring((line.length() + excess) / 2).indexOf(SEPARATOR) + (line.length() + excess) / 2 + 1;
out.append(line.subSequence(index, line.length()));
return out;
}
return line;
}
/**
* recursive method to print blocks
*/
private void printBlocks(final StringBuilder out, final StringBuilder lead, final int level, final int[] pos) {
if (out.length() > 0) {
char last = out.charAt(out.length() - 1);
if (last != BLOCK_OPEN) {
out.append(lead);
}
}
final int end = getRank() - 1;
if (level != end) {
out.append(BLOCK_OPEN);
int length = shape[level];
// first sub-block
pos[level] = 0;
StringBuilder newlead = new StringBuilder(lead);
newlead.append(SPACE);
printBlocks(out, newlead, level + 1, pos);
if (length < 2) { // escape
out.append(BLOCK_CLOSE);
return;
}
out.append(SEPARATOR + NEWLINE);
for (int i = level + 1; i < end; i++) {
out.append(NEWLINE);
}
// middle sub-blocks
if (length < MAX_SUBBLOCKS) {
for (int x = 1; x < length - 1; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
} else {
final int excess = length - MAX_SUBBLOCKS;
int xmax = (length - excess) / 2;
for (int x = 1; x < xmax; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
out.append(newlead);
out.append(ELLIPSIS + SEPARATOR + NEWLINE);
xmax = (length + excess) / 2;
for (int x = xmax; x < length - 1; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
}
// last sub-block
pos[level] = length - 1;
printBlocks(out, newlead, level + 1, pos);
out.append(BLOCK_CLOSE);
} else {
out.append(makeLine(end, pos));
}
}
@Override
public void setDirty() {
if (storedValues != null)
storedValues.clear();
}
@Override
public Dataset squeezeEnds() {
return squeeze(true);
}
@Override
public Dataset squeeze() {
return squeeze(false);
}
@Override
public Dataset squeeze(boolean onlyFromEnds) {
final int[] tshape = squeezeShape(shape, onlyFromEnds);
final int[] oshape = shape;
if (stride == null) {
shape = tshape;
} else {
int rank = shape.length;
int trank = tshape.length;
if (trank < rank) {
int[] tstride = new int[tshape.length];
if (onlyFromEnds) {
for (int i = 0; i < rank; i++) {
if (shape[i] != 1) {
for (int k = 0; k < trank; k++) {
tstride[k] = stride[i++];
}
break;
}
}
} else {
int t = 0;
for (int i = 0; i < rank; i++) {
if (shape[i] != 1) {
tstride[t++] = stride[i];
}
}
}
shape = tshape;
stride = tstride;
}
}
reshapeMetadata(oshape, shape);
return this;
}
/**
* Remove dimensions of 1 in given shape - from both ends only, if true
*
* @param oshape
* @param onlyFromEnds
* @return newly squeezed shape (or original if unsqueezed)
*/
public static int[] squeezeShape(final int[] oshape, boolean onlyFromEnds) {
int unitDims = 0;
int rank = oshape.length;
int start = 0;
if (onlyFromEnds) {
int i = rank - 1;
for (; i >= 0; i
if (oshape[i] == 1) {
unitDims++;
} else {
break;
}
}
for (int j = 0; j <= i; j++) {
if (oshape[j] == 1) {
unitDims++;
} else {
start = j;
break;
}
}
} else {
for (int i = 0; i < rank; i++) {
if (oshape[i] == 1) {
unitDims++;
}
}
}
if (unitDims == 0) {
return oshape;
}
int[] newDims = new int[rank - unitDims];
if (unitDims == rank)
return newDims; // zero-rank dataset
if (onlyFromEnds) {
rank = newDims.length;
for (int i = 0; i < rank; i++) {
newDims[i] = oshape[i+start];
}
} else {
int j = 0;
for (int i = 0; i < rank; i++) {
if (oshape[i] > 1) {
newDims[j++] = oshape[i];
if (j >= newDims.length)
break;
}
}
}
return newDims;
}
/**
* Remove dimension of 1 in given shape
*
* @param oshape
* @param axis
* @return newly squeezed shape
*/
public static int[] squeezeShape(final int[] oshape, int axis) {
if (oshape == null || oshape.length == 0) {
return new int[0];
}
int rank = oshape.length;
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
logger.error("Axis argument is outside allowed range");
throw new IllegalArgumentException("Axis argument is outside allowed range");
}
int[] nshape = new int[rank-1];
for (int i = 0; i < axis; i++) {
nshape[i] = oshape[i];
}
for (int i = axis+1; i < rank; i++) {
nshape[i-1] = oshape[i];
}
return nshape;
}
/**
* Check if shapes are broadcast compatible
*
* @param ashape
* @param bshape
* @return true if they are compatible
*/
public static boolean areShapesBroadcastCompatible(final int[] ashape, final int[] bshape) {
if (ashape.length < bshape.length) {
return areShapesBroadcastCompatible(bshape, ashape);
}
for (int a = ashape.length - bshape.length, b = 0; a < ashape.length && b < bshape.length; a++, b++) {
if (ashape[a] != bshape[b] && ashape[a] != 1 && bshape[b] != 1) {
return false;
}
}
return true;
}
/**
* Check if shapes are compatible, ignoring extra axes of length 1
*
* @param ashape
* @param bshape
* @return true if they are compatible
*/
public static boolean areShapesCompatible(final int[] ashape, final int[] bshape) {
List<Integer> alist = new ArrayList<Integer>();
for (int a : ashape) {
if (a > 1) alist.add(a);
}
final int imax = alist.size();
int i = 0;
for (int b : bshape) {
if (b == 1)
continue;
if (i >= imax || b != alist.get(i++))
return false;
}
return i == imax;
}
/**
* Check if shapes are compatible but skip axis
*
* @param ashape
* @param bshape
* @param axis
* @return true if they are compatible
*/
public static boolean areShapesCompatible(final int[] ashape, final int[] bshape, final int axis) {
if (ashape.length != bshape.length) {
return false;
}
final int rank = ashape.length;
for (int i = 0; i < rank; i++) {
if (i != axis && ashape[i] != bshape[i]) {
return false;
}
}
return true;
}
@Override
public boolean isCompatibleWith(final ILazyDataset g) {
return areShapesCompatible(shape, g.getShape());
}
@Override
public void checkCompatibility(final ILazyDataset g) throws IllegalArgumentException {
checkCompatibility(this, g);
}
public static void checkCompatibility(final ILazyDataset g, final ILazyDataset h) throws IllegalArgumentException {
if (!areShapesCompatible(g.getShape(), h.getShape())) {
throw new IllegalArgumentException("Shapes do not match");
}
}
@Override
public Dataset reshape(final int... shape) {
Dataset a = getView();
try {
a.setShape(shape);
} catch (IllegalArgumentException e) {
a = a.clone();
a.setShape(shape);
}
return a;
}
/**
* Create a dataset from object (automatically detect dataset type)
*
* @param obj
* can be a Java list, array or Number
* @return dataset
*/
public static Dataset array(final Object obj) {
return DatasetFactory.createFromObject(obj);
}
/**
* Create a dataset from object (automatically detect dataset type)
*
* @param obj
* can be a Java list, array or Number
* @param isUnsigned
* if true, interpret integer values as unsigned by increasing element bit width
* @return dataset
*/
public static Dataset array(final Object obj, boolean isUnsigned) {
return DatasetFactory.createFromObject(obj, isUnsigned);
}
/**
* Create a dataset from object
*
* @param obj
* can be a Java list, array or Number
* @param dtype
* @return dataset
*/
public static Dataset array(final Object obj, final int dtype) {
return DatasetFactory.createFromObject(obj, dtype);
}
/**
* Create dataset of appropriate type from list
*
* @param objectList
* @return dataset filled with values from list
*/
public static Dataset createFromList(List<?> objectList) {
return DatasetFactory.createFromList(objectList);
}
/**
* @param shape
* @param dtype
* @return a new dataset of given shape and type, filled with zeros
*/
public static Dataset zeros(final int[] shape, final int dtype) {
return DatasetFactory.zeros(shape, dtype);
}
/**
* @param itemSize
* if equal to 1, then non-compound dataset is returned
* @param shape
* @param dtype
* @return a new dataset of given item size, shape and type, filled with zeros
*/
public static Dataset zeros(final int itemSize, final int[] shape, final int dtype) {
return DatasetFactory.zeros(itemSize, shape, dtype);
}
/**
* @param dataset
* @return a new dataset of same shape and type as input dataset, filled with zeros
*/
public static Dataset zeros(final Dataset dataset) {
return zeros(dataset, dataset.getDtype());
}
/**
* Create a new dataset of same shape as input dataset, filled with zeros. If dtype is not
* explicitly compound then an elemental dataset is created
* @param dataset
* @param dtype
* @return a new dataset
*/
public static Dataset zeros(final Dataset dataset, final int dtype) {
final int[] shape = dataset.getShapeRef();
final int isize = isDTypeElemental(dtype) ? 1 :dataset.getElementsPerItem();
return zeros(isize, shape, dtype);
}
/**
* @param dataset
* @return a new dataset of same shape and type as input dataset, filled with ones
*/
public static Dataset ones(final Dataset dataset) {
return ones(dataset, dataset.getDtype());
}
/**
* Create a new dataset of same shape as input dataset, filled with ones. If dtype is not
* explicitly compound then an elemental dataset is created
* @param dataset
* @param dtype
* @return a new dataset
*/
public static Dataset ones(final Dataset dataset, final int dtype) {
final int[] shape = dataset.getShapeRef();
final int isize = isDTypeElemental(dtype) ? 1 :dataset.getElementsPerItem();
return ones(isize, shape, dtype);
}
/**
* @param shape
* @param dtype
* @return a new dataset of given shape and type, filled with ones
*/
public static Dataset ones(final int[] shape, final int dtype) {
return DatasetFactory.ones(shape, dtype);
}
/**
* @param itemSize
* if equal to 1, then non-compound dataset is returned
* @param shape
* @param dtype
* @return a new dataset of given item size, shape and type, filled with ones
*/
public static Dataset ones(final int itemSize, final int[] shape, final int dtype) {
return DatasetFactory.ones(itemSize, shape, dtype);
}
/**
* @param stop
* @param dtype
* @return a new dataset of given shape and type, filled with values determined by parameters
*/
public static Dataset arange(final double stop, final int dtype) {
return arange(0, stop, 1, dtype);
}
/**
* @param start
* @param stop
* @param step
* @param dtype
* @return a new 1D dataset of given type, filled with values determined by parameters
*/
public static Dataset arange(final double start, final double stop, final double step, final int dtype) {
return DatasetFactory.createRange(start, stop, step, dtype);
}
/**
* @param start
* @param stop
* @param step
* @return number of steps to take
*/
public static int calcSteps(final double start, final double stop, final double step) {
if (step > 0) {
return (int) Math.ceil((stop - start) / step);
}
return (int) Math.ceil((stop - start) / step);
}
@Override
public boolean isComplex() {
int type = getDtype();
return type == COMPLEX64 || type == COMPLEX128;
}
@Override
public Dataset real() {
return this;
}
@Override
public Dataset realView() {
return getView();
}
@Override
public Dataset getSlice(final int[] start, final int[] stop, final int[] step) {
return getSlice(new SliceND(shape, start, stop, step));
}
@Override
public Dataset getSlice(Slice... slice) {
return getSlice(new SliceND(shape, slice));
}
@Override
public Dataset getSlice(IMonitor monitor, Slice... slice) {
return getSlice(slice);
}
@Override
public Dataset getSlice(IMonitor monitor, SliceND slice) {
return getSlice(slice);
}
@Override
public Dataset getSlice(IMonitor monitor, int[] start, int[] stop, int[] step) {
return getSlice(start, stop, step);
}
/**
* Get a slice of the dataset. The returned dataset is a copied selection of items
* @param slice
* @return The dataset of the sliced data
*/
@Override
public Dataset getSlice(final SliceND slice) {
SliceIterator it = (SliceIterator) getSliceIterator(slice);
AbstractDataset s = getSlice(it);
s.metadata = copyMetadata();
s.sliceMetadata(true, slice);
return s;
}
/**
* Get a slice of the dataset. The returned dataset is a copied selection of items
*
* @param iterator Slice iterator
* @return The dataset of the sliced data
*/
abstract public AbstractDataset getSlice(final SliceIterator iterator);
@Override
public Dataset setSlice(final Object obj, final SliceND slice) {
Dataset ds;
if (obj instanceof Dataset) {
ds = (Dataset) obj;
} else if (obj instanceof IDataset) {
ds = DatasetUtils.convertToDataset((IDataset) obj);
} else {
int dtype = getDtype();
if (dtype != Dataset.BOOL) {
dtype = getLargestDType(dtype);
}
ds = DatasetFactory.createFromObject(obj, dtype);
}
return setSlicedView(getSliceView(slice), ds);
}
@Override
public Dataset setSlice(final Object obj, final int[] start, final int[] stop, final int[] step) {
return setSlice(obj, new SliceND(shape, start, stop, step));
}
/**
* Set a view of current dataset to given dataset with broadcasting
* @param view
* @param d
* @return this dataset
*/
abstract Dataset setSlicedView(Dataset view, Dataset d);
@Override
public Dataset setSlice(Object obj, Slice... slice) {
if (slice == null || slice.length == 0) {
return setSlice(obj, new SliceND(shape));
}
return setSlice(obj, new SliceND(shape, slice));
}
@Override
public boolean all() {
return Comparisons.allTrue(this);
}
@Override
public BooleanDataset all(final int axis) {
return Comparisons.allTrue(this, axis);
}
@Override
public boolean any() {
return Comparisons.anyTrue(this);
}
@Override
public BooleanDataset any(final int axis) {
return Comparisons.anyTrue(this, axis);
}
@Override
public Dataset ifloorDivide(final Object o) {
return idivide(o).ifloor();
}
@Override
public double residual(final Object o) {
return residual(o, null, false);
}
@Override
public double residual(final Object o, boolean ignoreNaNs) {
return residual(o, null, ignoreNaNs);
}
public static final String STORE_HASH = "hash";
protected static final String STORE_SHAPELESS_HASH = "shapelessHash";
public static final String STORE_MAX = "max";
public static final String STORE_MIN = "min";
protected static final String STORE_MAX_POS = "maxPos";
protected static final String STORE_MIN_POS = "minPos";
protected static final String STORE_STATS = "stats";
protected static final String STORE_SUM = "sum";
protected static final String STORE_MEAN = "mean";
protected static final String STORE_VAR = "var";
private static final String STORE_POS_MAX = "+max";
private static final String STORE_POS_MIN = "+min";
protected static final String STORE_COUNT = "count";
private static final String STORE_INDEX = "Index";
protected static final String STORE_BROADCAST = "Broadcast";
/**
* Get value from store
*
* @param key
* @return value
*/
public Object getStoredValue(String key) {
if (storedValues == null) {
return null;
}
return storedValues.get(key);
}
/**
* Set value in store
* <p>
* This is a <b>private method</b>: do not use!
*
* @param key
* @param obj
*/
public void setStoredValue(String key, Object obj) {
if (storedValues == null) {
storedValues = new HashMap<String, Object>();
}
storedValues.put(key, obj);
}
protected static String storeName(boolean ignoreNaNs, String name) {
return storeName(ignoreNaNs, false, name);
}
protected static String storeName(boolean ignoreNaNs, boolean ignoreInfs, String name) {
return (ignoreInfs ? "inf" : "") + (ignoreNaNs ? "nan" : "") + name;
}
/**
* Copy stored values from original to derived dataset
* @param orig
* @param derived
* @param shapeChanged
*/
protected static void copyStoredValues(IDataset orig, AbstractDataset derived, boolean shapeChanged) {
if (orig instanceof AbstractDataset && ((AbstractDataset) orig).storedValues != null) {
derived.storedValues = new HashMap<String, Object>(((AbstractDataset) orig).storedValues);
if (shapeChanged) {
filterStoredValues(derived.storedValues);
}
}
}
private static void filterStoredValues(Map<String, Object> map) {
map.remove(STORE_HASH);
List<String> keys = new ArrayList<String>();
for (String n : map.keySet()) {
if (n.contains("-")) { // remove anything which is axis-specific
keys.add(n);
}
}
for (String n : keys) {
map.remove(n);
}
}
/**
* Calculate minimum and maximum for a dataset
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
*/
protected void calculateMaxMin(final boolean ignoreNaNs, final boolean ignoreInfs) {
IndexIterator iter = getIterator();
double amax = Double.NEGATIVE_INFINITY;
double amin = Double.POSITIVE_INFINITY;
double pmax = Double.MIN_VALUE;
double pmin = Double.POSITIVE_INFINITY;
double hash = 0;
boolean hasNaNs = false;
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (Double.isNaN(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreNaNs)
continue;
hasNaNs = true;
} else if (Double.isInfinite(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreInfs)
continue;
} else {
hash = (hash * 19 + val) % Integer.MAX_VALUE;
}
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
if (val > 0) {
if (val < pmin) {
pmin = val;
}
if (val > pmax) {
pmax = val;
}
}
}
int ihash = ((int) hash) * 19 + getDtype() * 17 + getElementsPerItem();
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_SHAPELESS_HASH), ihash);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(amax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(amin));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(pmax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(pmin));
}
/**
* Calculate summary statistics for a dataset
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
* @param name
*/
protected void calculateSummaryStats(final boolean ignoreNaNs, final boolean ignoreInfs, final String name) {
final IndexIterator iter = getIterator();
final SummaryStatistics stats = new SummaryStatistics();
//sum of logs is slow and we dont use it, so blocking its calculation here
stats.setSumLogImpl(new NullStorelessUnivariateStatistic());
if (storedValues == null || !storedValues.containsKey(STORE_HASH)) {
boolean hasNaNs = false;
double hash = 0;
double pmax = Double.MIN_VALUE;
double pmin = Double.POSITIVE_INFINITY;
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (Double.isNaN(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreNaNs)
continue;
hasNaNs = true;
} else if (Double.isInfinite(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreInfs)
continue;
} else {
hash = (hash * 19 + val) % Integer.MAX_VALUE;
}
if (val > 0) {
if (val < pmin) {
pmin = val;
}
if (val > pmax) {
pmax = val;
}
}
stats.addValue(val);
}
int ihash = ((int) hash) * 19 + getDtype() * 17 + getElementsPerItem();
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_SHAPELESS_HASH), ihash);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(stats.getMax()));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(stats.getMin()));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(pmax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(pmin));
storedValues.put(name, stats);
} else {
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (ignoreNaNs && Double.isNaN(val)) {
continue;
}
if (ignoreInfs && Double.isInfinite(val)) {
continue;
}
stats.addValue(val);
}
storedValues.put(name, stats);
}
}
/**
* Calculate summary statistics for a dataset along an axis
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
* @param axis
*/
protected void calculateSummaryStats(final boolean ignoreNaNs, final boolean ignoreInfs, final int axis) {
int rank = getRank();
int[] oshape = getShape();
int alen = oshape[axis];
oshape[axis] = 1;
int[] nshape = new int[rank - 1];
for (int i = 0; i < axis; i++) {
nshape[i] = oshape[i];
}
for (int i = axis + 1; i < rank; i++) {
nshape[i - 1] = oshape[i];
}
final int dtype = getDtype();
IntegerDataset count = new IntegerDataset(nshape);
Dataset max = DatasetFactory.zeros(nshape, dtype);
Dataset min = DatasetFactory.zeros(nshape, dtype);
IntegerDataset maxIndex = new IntegerDataset(nshape);
IntegerDataset minIndex = new IntegerDataset(nshape);
Dataset sum = DatasetFactory.zeros(nshape, getLargestDType(dtype));
DoubleDataset mean = new DoubleDataset(nshape);
DoubleDataset var = new DoubleDataset(nshape);
IndexIterator qiter = max.getIterator(true);
int[] qpos = qiter.getPos();
int[] spos = oshape.clone();
while (qiter.hasNext()) {
int i = 0;
for (; i < axis; i++) {
spos[i] = qpos[i];
}
spos[i++] = 0;
for (; i < rank; i++) {
spos[i] = qpos[i - 1];
}
final SummaryStatistics stats = new SummaryStatistics();
//sum of logs is slow and we dont use it, so blocking its calculation here
stats.setSumLogImpl(new NullStorelessUnivariateStatistic());
double amax = Double.NEGATIVE_INFINITY;
double amin = Double.POSITIVE_INFINITY;
boolean hasNaNs = false;
if (ignoreNaNs) {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val)) {
hasNaNs = true;
continue;
} else if (ignoreInfs && Double.isInfinite(val)) {
continue;
}
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
stats.addValue(val);
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (hasNaNs) {
if (!Double.isNaN(val))
stats.addValue(0);
continue;
}
if (Double.isNaN(val)) {
amax = Double.NaN;
amin = Double.NaN;
hasNaNs = true;
} else if (ignoreInfs && Double.isInfinite(val)) {
continue;
} else {
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
}
stats.addValue(val);
}
}
count.setAbs(qiter.index, (int) stats.getN());
max.setObjectAbs(qiter.index, amax);
min.setObjectAbs(qiter.index, amin);
boolean fmax = false;
boolean fmin = false;
if (hasNaNs) {
if (ignoreNaNs) {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val))
continue;
if (!fmax && val == amax) {
maxIndex.setAbs(qiter.index, j);
fmax = true;
if (fmin)
break;
}
if (!fmin && val == amin) {
minIndex.setAbs(qiter.index, j);
fmin = true;
if (fmax)
break;
}
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val)) {
maxIndex.setAbs(qiter.index, j);
minIndex.setAbs(qiter.index, j);
break;
}
}
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (!fmax && val == amax) {
maxIndex.setAbs(qiter.index, j);
fmax = true;
if (fmin)
break;
}
if (!fmin && val == amin) {
minIndex.setAbs(qiter.index, j);
fmin = true;
if (fmax)
break;
}
}
}
sum.setObjectAbs(qiter.index, stats.getSum());
mean.setAbs(qiter.index, stats.getMean());
var.setAbs(qiter.index, stats.getVariance());
}
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_COUNT + "-" + axis), count);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX + "-" + axis), max);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN + "-" + axis), min);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_SUM + "-" + axis), sum);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MEAN + "-" + axis), mean);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_VAR + "-" + axis), var);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX + STORE_INDEX + "-" + axis), maxIndex);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN + STORE_INDEX + "-" + axis), minIndex);
}
/**
* @param x
* @return number from given double
*/
abstract protected Number fromDoubleToNumber(double x);
// return biggest native primitive if integer (should test for 64bit?)
private static Number fromDoubleToBiggestNumber(double x, int dtype) {
switch (dtype) {
case BOOL:
case INT8:
case INT16:
case INT32:
return Integer.valueOf((int) (long) x);
case INT64:
return Long.valueOf((long) x);
case FLOAT32:
return Float.valueOf((float) x);
case FLOAT64:
return Double.valueOf(x);
}
return null;
}
private SummaryStatistics getStatistics(boolean ignoreNaNs) {
boolean ignoreInfs = false; // TODO
if (!hasFloatingPointElements()) {
ignoreNaNs = false;
}
String n = storeName(ignoreNaNs, ignoreInfs, STORE_STATS);
SummaryStatistics stats = (SummaryStatistics) getStoredValue(n);
if (stats == null) {
calculateSummaryStats(ignoreNaNs, ignoreInfs, n);
stats = (SummaryStatistics) getStoredValue(n);
}
return stats;
}
@Override
public int[] maxPos() {
return maxPos(false);
}
@Override
public int[] minPos() {
return minPos(false);
}
private int getHash() {
Object value = getStoredValue(STORE_HASH);
if (value == null) {
value = getStoredValue(STORE_SHAPELESS_HASH);
if (value == null) {
calculateMaxMin(false, false);
value = getStoredValue(STORE_SHAPELESS_HASH);
}
int ihash = (Integer) value;
int rank = shape.length;
for (int i = 0; i < rank; i++) {
ihash = ihash * 17 + shape[i];
}
storedValues.put(STORE_HASH, ihash);
return ihash;
}
return (Integer) value;
}
protected Object getMaxMin(boolean ignoreNaNs, boolean ignoreInfs, String key) {
if (!hasFloatingPointElements()) {
ignoreNaNs = false;
ignoreInfs = false;
}
key = storeName(ignoreNaNs, ignoreInfs , key);
Object value = getStoredValue(key);
if (value == null) {
calculateMaxMin(ignoreNaNs, ignoreInfs);
value = getStoredValue(key);
}
return value;
}
private Object getStatistics(boolean ignoreNaNs, int axis, String stat) {
if (!hasFloatingPointElements())
ignoreNaNs = false;
boolean ignoreInfs = false; // TODO
stat = storeName(ignoreNaNs, ignoreInfs , stat);
axis = checkAxis(axis);
Object obj = getStoredValue(stat);
if (obj == null) {
calculateSummaryStats(ignoreNaNs, ignoreInfs, axis);
obj = getStoredValue(stat);
}
return obj;
}
@Override
public Number max(boolean... ignoreInvalids) {
boolean igNan = ignoreInvalids!=null && ignoreInvalids.length>0 ? ignoreInvalids[0] : false;
boolean igInf = ignoreInvalids!=null && ignoreInvalids.length>1 ? ignoreInvalids[1] : igNan;
return (Number) getMaxMin(igNan, igInf, STORE_MAX);
}
@Override
public Number positiveMax(boolean ignoreInvalids) {
return (Number) getMaxMin(ignoreInvalids, ignoreInvalids, STORE_POS_MAX);
}
@Override
public Number positiveMax(boolean ignoreNaNs, boolean ignoreInfs) {
return (Number) getMaxMin(ignoreNaNs, ignoreInfs, STORE_POS_MAX);
}
@Override
public Dataset max(int axis) {
return max(false, axis);
}
@Override
public Dataset max(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MAX + "-" + axis);
}
@Override
public Number min(boolean... ignoreInvalids) {
boolean igNan = ignoreInvalids!=null && ignoreInvalids.length>0 ? ignoreInvalids[0] : false;
boolean igInf = ignoreInvalids!=null && ignoreInvalids.length>1 ? ignoreInvalids[1] : igNan;
return (Number) getMaxMin(igNan, igInf, STORE_MIN);
}
@Override
public Number positiveMin(boolean ignoreInvalids) {
return (Number) getMaxMin(ignoreInvalids, ignoreInvalids, STORE_POS_MIN);
}
@Override
public Number positiveMin(boolean ignoreNaNs, boolean ignoreInfs) {
return (Number) getMaxMin(ignoreNaNs, ignoreInfs, STORE_POS_MIN);
}
@Override
public Dataset min(int axis) {
return min(false, axis);
}
@Override
public Dataset min(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MIN + "-" + axis);
}
@Override
public int argMax() {
return argMax(false);
}
@Override
public int argMax(boolean ignoreInvalids) {
return getFlat1DIndex(maxPos(ignoreInvalids));
}
@Override
public IntegerDataset argMax(int axis) {
return argMax(false, axis);
}
@Override
public IntegerDataset argMax(boolean ignoreNaNs, int axis) {
return (IntegerDataset) getStatistics(ignoreNaNs, axis, STORE_MAX + STORE_INDEX + "-" + axis);
}
@Override
public int argMin() {
return argMin(false);
}
@Override
public int argMin(boolean ignoreInvalids) {
return getFlat1DIndex(minPos(ignoreInvalids));
}
@Override
public IntegerDataset argMin(int axis) {
return argMin(false, axis);
}
@Override
public IntegerDataset argMin(boolean ignoreNaNs, int axis) {
return (IntegerDataset) getStatistics(ignoreNaNs, axis, STORE_MIN + STORE_INDEX + "-" + axis);
}
@Override
public Number peakToPeak() {
return fromDoubleToNumber(max().doubleValue() - min().doubleValue());
}
@Override
public Dataset peakToPeak(int axis) {
return Maths.subtract(max(axis), min(axis));
}
@Override
public long count() {
return count(false);
}
@Override
public long count(boolean ignoreNaNs) {
return getStatistics(ignoreNaNs).getN();
}
@Override
public Dataset count(int axis) {
return count(false, axis);
}
@Override
public Dataset count(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_COUNT + "-" + axis);
}
@Override
public Object sum() {
return sum(false);
}
@Override
public Object sum(boolean ignoreNaNs) {
return getStatistics(ignoreNaNs).getSum();
}
@Override
public Dataset sum(int axis) {
return sum(false, axis);
}
@Override
public Dataset sum(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_SUM + "-" + axis);
}
@Override
public Object typedSum() {
return typedSum(getDtype());
}
@Override
public Object typedSum(int dtype) {
return fromDoubleToBiggestNumber(getStatistics(false).getSum(), dtype);
}
@Override
public Dataset typedSum(int dtype, int axis) {
return DatasetUtils.cast(sum(axis), dtype);
}
@Override
public Object product() {
return Stats.product(this);
}
@Override
public Dataset product(int axis) {
return Stats.product(this, axis);
}
@Override
public Object typedProduct(int dtype) {
return Stats.typedProduct(this, dtype);
}
@Override
public Dataset typedProduct(int dtype, int axis) {
return Stats.typedProduct(this, dtype, axis);
}
@Override
public Object mean(boolean... ignoreNaNs) {
boolean ig = ignoreNaNs!=null && ignoreNaNs.length>0 ? ignoreNaNs[0] : false;
return getStatistics(ig).getMean();
}
@Override
public Dataset mean(int axis) {
return mean(false, axis);
}
@Override
public Dataset mean(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MEAN + "-" + axis);
}
@Override
public Number variance() {
return variance(false);
}
@Override
public Number variance(boolean isDatasetWholePopulation) {
SummaryStatistics stats = getStatistics(false);
if (isDatasetWholePopulation) {
Variance newVar = (Variance) stats.getVarianceImpl().copy();
newVar.setBiasCorrected(false);
return newVar.getResult();
}
return stats.getVariance();
}
@Override
public Dataset variance(int axis) {
return (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
}
@Override
public Number stdDeviation() {
return Math.sqrt(variance().doubleValue());
}
@Override
public Number stdDeviation(boolean isDatasetWholePopulation) {
return Math.sqrt(variance(isDatasetWholePopulation).doubleValue());
}
@Override
public Dataset stdDeviation(int axis) {
final Dataset v = (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
return Maths.sqrt(v);
}
@Override
public Number rootMeanSquare() {
final SummaryStatistics stats = getStatistics(false);
final double mean = stats.getMean();
return Math.sqrt(stats.getVariance() + mean * mean);
}
@Override
public Dataset rootMeanSquare(int axis) {
Dataset v = (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
Dataset m = (Dataset) getStatistics(false, axis, STORE_MEAN + "-" + axis);
Dataset result = Maths.power(m, 2);
return Maths.sqrt(result.iadd(v));
}
/**
* Set item from compatible dataset in a direct and speedy way. Remember to setDirty afterwards.
*
* @param dindex
* @param sindex
* @param src
* is the source data buffer
*/
protected abstract void setItemDirect(final int dindex, final int sindex, final Object src);
@Override
public boolean hasErrors() {
return super.getError() != null;
}
protected Dataset getInternalError() {
ILazyDataset led = super.getError();
if (led == null)
return null;
Dataset ed = DatasetUtils.sliceAndConvertLazyDataset(led);
if (!(led instanceof Dataset)) {
setError(ed); // set back
}
// check for broadcast strides
Object bs = getStoredValue(STORE_BROADCAST);
if (bs == null) {
bs = new BroadcastStride(ed, shape);
setStoredValue(STORE_BROADCAST, bs);
}
return ed;
}
class BroadcastStride {
private int[] bStride;
private int[] nShape;
private int bOffset;
public BroadcastStride(Dataset d, final int[] newShape) {
d.setShape(BroadcastUtils.padShape(d.getShapeRef(), newShape.length - d.getRank())); // set to padded shape
bStride = BroadcastUtils.createBroadcastStrides(d, newShape);
nShape = newShape.clone();
bOffset = d.getOffset();
}
public int get1DIndex(int i) {
if (i < 0) {
i += nShape[0];
}
if (i < 0 || i >= nShape[0]) {
throwAIOOBException(i, nShape[0], 0);
}
return i*bStride[0] + bOffset;
}
protected int get1DIndex(int i, int j) {
if (i < 0) {
i += nShape[0];
}
if (i < 0 || i >= nShape[0]) {
throwAIOOBException(i, nShape[0], 0);
}
if (j < 0) {
j += nShape[1];
}
if (j < 0 || j >= nShape[1]) {
throwAIOOBException(i, nShape[1], 1);
}
return i*bStride[0] + j*bStride[1] + bOffset;
}
protected int get1DIndex(int... n) {
return get1DIndexFromStrides(nShape, bStride, bOffset, n);
}
}
@Override
public Dataset getError() {
Dataset ed = getInternalError();
if (ed == null)
return null;
if (ed.getSize() != getSize()) {
DoubleDataset errors = new DoubleDataset(shape);
errors.setSlice(ed);
return errors;
}
return ed;
}
@Override
public double getError(final int i) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(i));
}
@Override
public double getError(final int i, final int j) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(i, j));
}
@Override
public double getError(int... pos) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(pos));
}
@Override
public double[] getErrorArray(final int i) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(i)};
}
@Override
public double[] getErrorArray(final int i, final int j) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(i, j)};
}
@Override
public double[] getErrorArray(int... pos) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(pos)};
}
protected Dataset getInternalSquaredError() {
Dataset sed = getErrorBuffer();
// check for broadcast strides
Object bs = getStoredValue(STORE_BROADCAST);
if (bs == null) {
bs = new BroadcastStride(sed, shape);
setStoredValue(STORE_BROADCAST, bs);
}
return sed;
}
@Override
public Dataset getErrorBuffer() {
ErrorMetadata emd = getErrorMetadata();
if (emd == null)
return null;
if (!(emd instanceof ErrorMetadataImpl)) {
ILazyDataset led = emd.getError();
Dataset ed = DatasetUtils.sliceAndConvertLazyDataset(led);
emd = new ErrorMetadataImpl();
setMetadata(emd);
((ErrorMetadataImpl) emd).setError(ed);
}
return ((ErrorMetadataImpl) emd).getSquaredError();
}
@Override
public void setError(Serializable errors) {
super.setError(errors);
Object bs = getStoredValue(STORE_BROADCAST);
if (bs != null) {
setStoredValue(STORE_BROADCAST, null);
}
}
/**
* Set a copy of the buffer that backs the (squared) error data
* @param buffer can be null, anything that can be used to create a DoubleDataset or CompoundDoubleDataset
*/
@Override
public void setErrorBuffer(Serializable buffer) {
Object bs = getStoredValue(STORE_BROADCAST);
if (bs != null) {
setStoredValue(STORE_BROADCAST, null);
}
if (buffer == null) {
clearMetadata(ErrorMetadata.class);
return;
}
IDataset d = (IDataset) createFromSerializable(buffer, false);
ErrorMetadata emd = getErrorMetadata();
if (!(emd instanceof ErrorMetadataImpl)) {
emd = new ErrorMetadataImpl();
setMetadata(emd);
}
((ErrorMetadataImpl) emd).setSquaredError(d);
}
}
|
package org.eclipse.dawnsci.analysis.dataset.impl;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.text.Format;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.complex.Complex;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.api.dataset.ILazyDataset;
import org.eclipse.dawnsci.analysis.api.dataset.Slice;
import org.eclipse.dawnsci.analysis.api.dataset.SliceND;
import org.eclipse.dawnsci.analysis.api.metadata.ErrorMetadata;
import org.eclipse.dawnsci.analysis.api.metadata.MetadataType;
import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;
import org.eclipse.dawnsci.analysis.dataset.metadata.ErrorMetadataImpl;
/**
* Generic container class for data
* <p/>
* Each subclass has an array of primitive types, elements of this array are grouped or
* compounded to make items
* <p/>
* Data items can be boolean, integer, float, complex float, vector float, etc
*/
public abstract class AbstractDataset extends LazyDatasetBase implements Dataset {
/**
* Boolean
*/
public static final int BOOL = Dataset.BOOL;
/**
* Signed 8-bit integer
*/
public static final int INT8 = Dataset.INT8;
/**
* Signed 16-bit integer
*/
public static final int INT16 = Dataset.INT16;
/**
* Signed 32-bit integer
*/
public static final int INT32 = Dataset.INT32;
/**
* Integer (same as signed 32-bit integer)
*/
public static final int INT = Dataset.INT;
/**
* Signed 64-bit integer
*/
public static final int INT64 = Dataset.INT64;
/**
* 32-bit floating point
*/
public static final int FLOAT32 = Dataset.FLOAT32;
/**
* 64-bit floating point
*/
public static final int FLOAT64 = Dataset.FLOAT64;
/**
* Floating point (same as 64-bit floating point)
*/
public static final int FLOAT = Dataset.FLOAT;
/**
* 64-bit complex floating point (real and imaginary parts are 32-bit floats)
*/
public static final int COMPLEX64 = Dataset.COMPLEX64;
/**
* 128-bit complex floating point (real and imaginary parts are 64-bit floats)
*/
public static final int COMPLEX128 = Dataset.COMPLEX128;
/**
* Complex floating point (same as 64-bit floating point)
*/
public static final int COMPLEX = Dataset.COMPLEX;
/**
* Date
*/
public static final int DATE = Dataset.DATE;
/**
* String
*/
public static final int STRING = Dataset.STRING;
/**
* Object
*/
public static final int OBJECT = Dataset.OBJECT;
/**
* Array of signed 8-bit integers
*/
public static final int ARRAYINT8 = Dataset.ARRAYINT8;
/**
* Array of signed 16-bit integers
*/
public static final int ARRAYINT16 = Dataset.ARRAYINT16;
/**
* Array of three signed 16-bit integers for RGB values
*/
public static final int RGB = Dataset.RGB;
/**
* Array of signed 32-bit integers
*/
public static final int ARRAYINT32 = Dataset.ARRAYINT32;
/**
* Array of signed 64-bit integers
*/
public static final int ARRAYINT64 = Dataset.ARRAYINT64;
/**
* Array of 32-bit floating points
*/
public static final int ARRAYFLOAT32 = Dataset.ARRAYFLOAT32;
/**
* Array of 64-bit floating points
*/
public static final int ARRAYFLOAT64 = Dataset.ARRAYFLOAT64;
protected static boolean isDTypeElemental(int dtype) {
return dtype <= COMPLEX128 || dtype == RGB;
}
protected static boolean isDTypeFloating(int dtype) {
return dtype == FLOAT32 || dtype == FLOAT64 || dtype == COMPLEX64 || dtype == COMPLEX128 ||
dtype == ARRAYFLOAT32 || dtype == ARRAYFLOAT64;
}
protected static boolean isDTypeComplex(int dtype) {
return dtype == COMPLEX64 || dtype == COMPLEX128;
}
protected int size; // number of items
transient protected AbstractDataset base; // is null when not a view
protected int[] stride; // can be null for row-major, contiguous datasets
protected int offset;
/**
* The data itself, held in a 1D array, but the object will wrap it to appear as possessing as many dimensions as
* wanted
*/
protected Serializable odata = null;
/**
* Set aliased data as base data
*/
abstract protected void setData();
/**
* These members hold cached values. If their values are null, then recalculate, otherwise just use the values
*/
transient protected HashMap<String, Object> storedValues = null;
/**
* Constructor required for serialisation.
*/
public AbstractDataset() {
}
@Override
public synchronized Dataset synchronizedCopy() {
return clone();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(obj.getClass())) {
if (getRank() == 0) // for zero-rank datasets
return obj.equals(getObjectAbs(0));
return false;
}
Dataset other = (Dataset) obj;
if (getElementsPerItem() != other.getElementsPerItem())
return false;
if (size != other.getSize())
return false;
if (!Arrays.equals(shape, other.getShapeRef())) {
return false;
}
if (getRank() == 0) // for zero-rank datasets
return other.getObjectAbs(0).equals(getObjectAbs(0));
return true;
}
@Override
public int hashCode() {
return getHash();
}
@Override
abstract public AbstractDataset clone();
protected Format stringFormat = null;
@Override
public void setStringFormat(Format format) {
stringFormat = format;
}
@Override
public Dataset cast(final int dtype) {
if (getDtype() == dtype) {
return this;
}
return DatasetUtils.cast(this, dtype);
}
@Override
public Dataset cast(final boolean repeat, final int dtype, final int isize) {
if (getDtype() == dtype && getElementsPerItem() == isize) {
return this;
}
return DatasetUtils.cast(this, repeat, dtype, isize);
}
@Override
abstract public AbstractDataset getView();
/**
* Copy fields from original to view
* @param orig
* @param view
* @param clone if true, then clone everything but bulk data
* @param cloneMetadata if true, clone metadata
*/
protected static void copyToView(Dataset orig, AbstractDataset view, boolean clone, boolean cloneMetadata) {
view.name = orig.getName();
view.size = orig.getSize();
view.odata = orig.getBuffer();
view.offset = orig.getOffset();
view.base = orig instanceof AbstractDataset ? ((AbstractDataset) orig).base : null;
if (clone) {
view.shape = orig.getShape();
copyStoredValues(orig, view, false);
view.stride = orig instanceof AbstractDataset && ((AbstractDataset) orig).stride != null ?
((AbstractDataset) orig).stride.clone() : null;
} else {
view.shape = orig.getShapeRef();
view.stride = orig instanceof AbstractDataset ? ((AbstractDataset) orig).stride : null;
}
view.metadata = getMetadataMap(orig, cloneMetadata);
int odtype = orig.getDtype();
int vdtype = view.getDtype();
if (getBestDType(odtype, vdtype) != vdtype) {
view.storedValues = null; // as copy is a demotion
}
if (odtype != vdtype && view.storedValues != null) {
view.storedValues.remove(STORE_SHAPELESS_HASH);
view.storedValues.remove(STORE_HASH);
}
}
protected static Map<Class<? extends MetadataType>, List<MetadataType>> getMetadataMap(Dataset a, boolean clone) {
if (a == null)
return null;
List<MetadataType> all = null;
try {
all = a.getMetadata(null);
} catch (Exception e) {
}
if (all == null)
return null;
HashMap<Class<? extends MetadataType>, List<MetadataType>> map = new HashMap<Class<? extends MetadataType>, List<MetadataType>>();
for (MetadataType m : all) {
if (m == null) {
continue;
}
Class<? extends MetadataType> c = findMetadataTypeSubInterfaces(m.getClass());
List<MetadataType> l = map.get(c);
if (l == null) {
l = new ArrayList<MetadataType>();
map.put(c, l);
}
if (clone)
m = m.clone();
l.add(m);
}
return map;
}
@Override
public IntegerDataset getIndices() {
final IntegerDataset ret = DatasetUtils.indices(shape);
if (getName() != null) {
ret.setName("Indices of " + getName());
}
return ret;
}
@Override
public Dataset getTransposedView(int... axes) {
axes = checkPermutatedAxes(shape, axes);
AbstractDataset t = getView();
if (axes == null || getRank() == 1)
return t;
int rank = shape.length;
int[] tstride = new int[rank];
int[] toffset = new int[1];
int[] nshape = createStrides(new SliceND(shape), this, tstride, toffset);
int[] nstride = new int[rank];
for (int i = 0; i < rank; i++) {
final int ax = axes[i];
nstride[i] = tstride[ax];
nshape[i] = shape[ax];
}
t.shape = nshape;
t.stride = nstride;
t.offset = toffset[0];
t.base = base == null ? this : base;
copyStoredValues(this, t, true);
t.transposeMetadata(axes);
return t;
}
@Override
public Dataset transpose(int... axes) {
Dataset t = getTransposedView(axes);
return t == null ? clone() : t.clone();
}
@Override
public Dataset swapAxes(int axis1, int axis2) {
int rank = shape.length;
if (axis1 < 0)
axis1 += rank;
if (axis2 < 0)
axis2 += rank;
if (axis1 < 0 || axis2 < 0 || axis1 >= rank || axis2 >= rank) {
logger.error("Axis value invalid - out of range");
throw new IllegalArgumentException("Axis value invalid - out of range");
}
if (rank == 1 || axis1 == axis2) {
return this;
}
int[] axes = new int[rank];
for (int i = 0; i < rank; i++) {
axes[i] = i;
}
axes[axis1] = axis2;
axes[axis2] = axis1;
return getTransposedView(axes);
}
@Override
public Dataset flatten() {
if (stride != null) { // need to make a copy if not contiguous
return clone().flatten();
}
return reshape(size);
}
/**
* Calculate total number of items in given shape
* @param shape
* @return size
*/
public static long calcLongSize(final int[] shape) {
double dsize = 1.0;
if (shape == null || shape.length == 0) // special case of zero-rank shape
return 1;
for (int i = 0; i < shape.length; i++) {
// make sure the indexes isn't zero or negative
if (shape[i] == 0) {
return 0;
} else if (shape[i] < 0) {
throw new IllegalArgumentException(String.format(
"The %d-th is %d which is an illegal argument as it is negative", i, shape[i]));
}
dsize *= shape[i];
}
// check to see if the size is larger than an integer, i.e. we can't allocate it
if (dsize > Long.MAX_VALUE) {
throw new IllegalArgumentException("Size of the dataset is too large to allocate");
}
return (long) dsize;
}
/**
* Calculate total number of items in given shape
* @param shape
* @return size
*/
public static int calcSize(final int[] shape) {
long lsize = calcLongSize(shape);
// check to see if the size is larger than an integer, i.e. we can't allocate it
if (lsize > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Size of the dataset is too large to allocate");
}
return (int) lsize;
}
/**
* Find dataset type that best fits given types The best type takes into account complex and array datasets
*
* @param atype
* first dataset type
* @param btype
* second dataset type
* @return best dataset type
*/
public static int getBestDType(final int atype, final int btype) {
int besttype;
int a = atype >= ARRAYINT8 ? atype / ARRAYMUL : atype;
int b = btype >= ARRAYINT8 ? btype / ARRAYMUL : btype;
if (isDTypeFloating(a)) {
if (!isDTypeFloating(b)) {
b = getBestFloatDType(b);
if (isDTypeComplex(a)) {
b += COMPLEX64 - FLOAT32;
}
}
} else if (isDTypeFloating(b)) {
a = getBestFloatDType(a);
if (isDTypeComplex(b)) {
a += COMPLEX64 - FLOAT32;
}
}
besttype = a > b ? a : b;
if (atype >= ARRAYINT8 || btype >= ARRAYINT8) {
if (besttype >= COMPLEX64) {
throw new IllegalArgumentException("Complex type cannot be promoted to compound type");
}
besttype *= ARRAYMUL;
}
return besttype;
}
/**
* The largest dataset type suitable for a summation of around a few thousand items without changing from the "kind"
* of dataset
*
* @param otype
* @return largest dataset type available for given dataset type
*/
public static int getLargestDType(final int otype) {
switch (otype) {
case BOOL:
case INT8:
case INT16:
return INT32;
case INT32:
case INT64:
return INT64;
case FLOAT32:
case FLOAT64:
return FLOAT64;
case COMPLEX64:
case COMPLEX128:
return COMPLEX128;
case ARRAYINT8:
case ARRAYINT16:
return ARRAYINT32;
case ARRAYINT32:
case ARRAYINT64:
return ARRAYINT64;
case ARRAYFLOAT32:
case ARRAYFLOAT64:
return ARRAYFLOAT64;
}
throw new IllegalArgumentException("Unsupported dataset type");
}
/**
* Find floating point dataset type that best fits given types The best type takes into account complex and array
* datasets
*
* @param otype
* old dataset type
* @return best dataset type
*/
public static int getBestFloatDType(final int otype) {
int btype;
switch (otype) {
case BOOL:
case INT8:
case INT16:
case ARRAYINT8:
case ARRAYINT16:
case FLOAT32:
case ARRAYFLOAT32:
case COMPLEX64:
btype = FLOAT32; // demote, if necessary
break;
case INT32:
case INT64:
case ARRAYINT32:
case ARRAYINT64:
case FLOAT64:
case ARRAYFLOAT64:
case COMPLEX128:
btype = FLOAT64; // promote, if necessary
break;
default:
btype = otype; // for array datasets, preserve type
break;
}
return btype;
}
/**
* Find floating point dataset type that best fits given class The best type takes into account complex and array
* datasets
*
* @param cls
* of an item or element
* @return best dataset type
*/
public static int getBestFloatDType(Class<? extends Object> cls) {
return getBestFloatDType(getDTypeFromClass(cls));
}
transient private static final Map<Class<?>, Integer> dtypeMap = createDTypeMap();
private static Map<Class<?>, Integer> createDTypeMap() {
Map<Class<?>, Integer> result = new HashMap<Class<?>, Integer>();
result.put(Boolean.class, BOOL);
result.put(Byte.class, INT8);
result.put(Short.class, INT16);
result.put(Integer.class, INT32);
result.put(Long.class, INT64);
result.put(Float.class, FLOAT32);
result.put(Double.class, FLOAT64);
result.put(boolean.class, BOOL);
result.put(byte.class, INT8);
result.put(short.class, INT16);
result.put(int.class, INT32);
result.put(long.class, INT64);
result.put(float.class, FLOAT32);
result.put(double.class, FLOAT64);
result.put(Complex.class, COMPLEX128);
result.put(String.class, STRING);
result.put(Date.class, DATE);
result.put(Object.class, OBJECT);
return result;
}
/**
* Get dataset type from a class
*
* @param cls
* @return dataset type
*/
public static int getDTypeFromClass(Class<? extends Object> cls) {
return getDTypeFromClass(cls, 1);
}
/**
* Get dataset type from a class
*
* @param cls
* @return dataset type
*/
public static int getDTypeFromClass(Class<? extends Object> cls, int isize) {
Integer dtype = dtypeMap.get(cls);
if (dtype == null) {
throw new IllegalArgumentException("Class of object not supported");
}
if (isize != 1) {
if (dtype < FLOAT64)
dtype *= ARRAYMUL;
}
return dtype;
}
/**
* Get dataset type from an object. The following are supported: Java Number objects, Apache common math Complex
* objects, Java arrays and lists
*
* @param obj
* @return dataset type
*/
public static int getDTypeFromObject(Object obj) {
int dtype = -1;
if (obj == null) {
return dtype;
}
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
for (int i = 0; i < l; i++) {
int ldtype = getDTypeFromObject(jl.get(i));
if (ldtype > dtype) {
dtype = ldtype;
}
}
} else if (obj.getClass().isArray()) {
Class<?> ca = obj.getClass().getComponentType();
if (isComponentSupported(ca)) {
return getDTypeFromClass(ca);
}
int l = Array.getLength(obj);
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
int ldtype = getDTypeFromObject(lo);
if (ldtype > dtype) {
dtype = ldtype;
}
}
} else if (obj instanceof Dataset) {
return ((Dataset) obj).getDtype();
} else if (obj instanceof ILazyDataset) {
dtype = getDTypeFromClass(((ILazyDataset) obj).elementClass(), ((ILazyDataset) obj).getElementsPerItem());
} else {
dtype = getDTypeFromClass(obj.getClass());
}
return dtype;
}
/**
* @param comp
* @return true if supported
*/
public static boolean isComponentSupported(Class<? extends Object> comp) {
return comp.isPrimitive() || Number.class.isAssignableFrom(comp) || comp.equals(Boolean.class) || comp.equals(Complex.class) || comp.equals(String.class);
}
/**
* Get dataset type from given dataset
* @param d
* @return dataset type
*/
public static int getDType(ILazyDataset d) {
if (d instanceof LazyDatasetBase)
return ((LazyDatasetBase) d).getDtype();
return getDTypeFromClass(d.elementClass(), d.getElementsPerItem());
}
/**
* Get shape from object (array or list supported)
* @param obj
* @return shape
*/
public static int[] getShapeFromObject(final Object obj) {
ArrayList<Integer> lshape = new ArrayList<Integer>();
getShapeFromObj(lshape, obj, 0);
if (obj != null && lshape.size() == 0) {
return new int[0]; // cope with a single item
}
final int rank = lshape.size();
final int[] shape = new int[rank];
for (int i = 0; i < rank; i++) {
shape[i] = lshape.get(i);
}
return shape;
}
/**
* Get shape from object
* @param ldims
* @param obj
* @param depth
* @return true if there is a possibility of differing lengths
*/
private static boolean getShapeFromObj(final ArrayList<Integer> ldims, Object obj, int depth) {
if (obj == null)
return true;
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
updateShape(ldims, depth, l);
for (int i = 0; i < l; i++) {
Object lo = jl.get(i);
if (!getShapeFromObj(ldims, lo, depth + 1)) {
break;
}
}
return true;
}
Class<? extends Object> ca = obj.getClass().getComponentType();
if (ca != null) {
final int l = Array.getLength(obj);
updateShape(ldims, depth, l);
if (isComponentSupported(ca)) {
return true;
}
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
if (!getShapeFromObj(ldims, lo, depth + 1)) {
break;
}
}
return true;
} else if (obj instanceof IDataset) {
int[] s = ((IDataset) obj).getShape();
for (int i = 0; i < s.length; i++) {
updateShape(ldims, depth++, s[i]);
}
return true;
} else {
return false; // not an array of any type
}
}
private static void updateShape(final ArrayList<Integer> ldims, final int depth, final int l) {
if (depth >= ldims.size()) {
ldims.add(l);
} else if (l > ldims.get(depth)) {
ldims.set(depth, l);
}
}
/**
* Fill dataset from object at depth dimension
* @param obj
* @param depth
* @param pos position
*/
protected void fillData(Object obj, final int depth, final int[] pos) {
if (obj == null) {
int dtype = getDtype();
if (dtype == FLOAT32)
set(Float.NaN, pos);
else if (dtype == FLOAT64)
set(Double.NaN, pos);
return;
}
if (obj instanceof List<?>) {
List<?> jl = (List<?>) obj;
int l = jl.size();
for (int i = 0; i < l; i++) {
Object lo = jl.get(i);
fillData(lo, depth + 1, pos);
pos[depth]++;
}
pos[depth] = 0;
} else if (obj.getClass().isArray()) {
int l = Array.getLength(obj);
for (int i = 0; i < l; i++) {
Object lo = Array.get(obj, i);
fillData(lo, depth + 1, pos);
pos[depth]++;
}
pos[depth] = 0;
} else if (obj instanceof IDataset) {
boolean[] a = new boolean[shape.length];
for (int i = depth; i < a.length; i++)
a[i] = true;
setSlice(obj, getSliceIteratorFromAxes(pos, a));
} else {
set(obj, pos);
}
}
protected static boolean toBoolean(final Object b) {
if (b instanceof Number) {
return ((Number) b).longValue() != 0;
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue();
} else if (b instanceof Complex) {
return ((Complex) b).getReal() != 0;
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toBoolean(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (IDataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toBoolean(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static long toLong(final Object b) {
if (b instanceof Number) {
return ((Number) b).longValue();
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue() ? 1 : 0;
} else if (b instanceof Complex) {
return (long) ((Complex) b).getReal();
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toLong(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (IDataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toLong(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static double toReal(final Object b) {
if (b instanceof Number) {
return ((Number) b).doubleValue();
} else if (b instanceof Boolean) {
return ((Boolean) b).booleanValue() ? 1 : 0;
} else if (b instanceof Complex) {
return ((Complex) b).getReal();
} else if (b.getClass().isArray()) {
if (Array.getLength(b) == 0)
return 0;
return toReal(Array.get(b, 0));
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toReal(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toReal(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
protected static double toImag(final Object b) {
if (b instanceof Number) {
return 0;
} else if (b instanceof Boolean) {
return 0;
} else if (b instanceof Complex) {
return ((Complex) b).getImaginary();
} else if (b.getClass().isArray()) {
if (Array.getLength(b) < 2)
return 0;
return toReal(Array.get(b, 1));
} else if (b instanceof Dataset) {
Dataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toImag(db.getObjectAbs(0));
} else if (b instanceof IDataset) {
IDataset db = (Dataset) b;
if (db.getSize() != 1) {
logger.error("Given dataset must have only one item");
throw new IllegalArgumentException("Given dataset must have only one item");
}
return toImag(db.getObject(new int[db.getRank()]));
} else {
logger.error("Argument is of unsupported class");
throw new IllegalArgumentException("Argument is of unsupported class");
}
}
@Override
public IndexIterator getIterator(final boolean withPosition) {
if (stride != null)
return new StrideIterator(shape, stride, offset);
return withPosition ? new ContiguousIteratorWithPosition(shape, size) : new ContiguousIterator(size);
}
@Override
public IndexIterator getIterator() {
return getIterator(false);
}
@Override
public PositionIterator getPositionIterator(final int... axes) {
return new PositionIterator(shape, axes);
}
@Override
public IndexIterator getSliceIterator(final int[] start, final int[] stop, final int[] step) {
return getSliceIterator(new SliceND(shape, start, stop, step));
}
/**
* @param slice
* @return an slice iterator that operates like an IndexIterator
*/
public IndexIterator getSliceIterator(SliceND slice) {
if (calcLongSize(slice.getShape()) == 0) {
return new NullIterator(shape, slice.getShape());
}
if (stride != null)
return new StrideIterator(getElementsPerItem(), shape, stride, offset, slice);
return new SliceIterator(shape, size, slice);
}
@Override
public SliceIterator getSliceIteratorFromAxes(final int[] pos, boolean[] axes) {
int rank = shape.length;
int[] start;
int[] stop = new int[rank];
int[] step = new int[rank];
if (pos == null) {
start = new int[rank];
} else if (pos.length == rank) {
start = pos.clone();
} else {
throw new IllegalArgumentException("pos array length is not equal to rank of dataset");
}
if (axes == null) {
axes = new boolean[rank];
Arrays.fill(axes, true);
} else if (axes.length != rank) {
throw new IllegalArgumentException("axes array length is not equal to rank of dataset");
}
for (int i = 0; i < rank; i++) {
if (axes[i]) {
stop[i] = shape[i];
} else {
stop[i] = start[i] + 1;
}
step[i] = 1;
}
return (SliceIterator) getSliceIterator(start, stop, step);
}
@Override
public BooleanIterator getBooleanIterator(Dataset choice) {
return getBooleanIterator(choice, true);
}
@Override
public BooleanIterator getBooleanIterator(Dataset choice, boolean value) {
return new BooleanIterator(getIterator(), choice, value);
}
@Override
public Dataset getByBoolean(Dataset selection) {
checkCompatibility(selection);
final int length = ((Number) selection.sum()).intValue();
final int is = getElementsPerItem();
Dataset r = DatasetFactory.zeros(is, new int[] { length }, getDtype());
BooleanIterator biter = getBooleanIterator(selection);
int i = 0;
while (biter.hasNext()) {
r.setObjectAbs(i, getObjectAbs(biter.index));
i += is;
}
return r;
}
@Override
public Dataset getBy1DIndex(IntegerDataset index) {
final int is = getElementsPerItem();
final Dataset r = DatasetFactory.zeros(is, index.getShape(), getDtype());
final IntegerIterator iter = new IntegerIterator(index, size, is);
int i = 0;
while (iter.hasNext()) {
r.setObjectAbs(i, getObjectAbs(iter.index));
i += is;
}
return r;
}
@Override
public Dataset getByIndexes(final Object... indexes) {
final IntegersIterator iter = new IntegersIterator(shape, indexes);
final int is = getElementsPerItem();
final Dataset r = DatasetFactory.zeros(is, iter.getShape(), getDtype());
final int[] pos = iter.getPos();
int i = 0;
while (iter.hasNext()) {
r.setObjectAbs(i, getObject(pos));
i += is;
}
return r;
}
/**
* @param dtype
* @return (boxed) class of constituent element
*/
public static Class<?> elementClass(final int dtype) {
switch (dtype) {
case BOOL:
return Boolean.class;
case INT8:
case ARRAYINT8:
return Byte.class;
case INT16:
case ARRAYINT16:
case RGB:
return Short.class;
case INT32:
case ARRAYINT32:
return Integer.class;
case INT64:
case ARRAYINT64:
return Long.class;
case FLOAT32:
case ARRAYFLOAT32:
return Float.class;
case FLOAT64:
case ARRAYFLOAT64:
return Double.class;
case COMPLEX64:
return Float.class;
case COMPLEX128:
return Double.class;
case STRING:
return String.class;
}
return Object.class;
}
@Override
public Class<?> elementClass() {
return elementClass(getDtype());
}
@Override
public boolean hasFloatingPointElements() {
Class<?> cls = elementClass();
return cls == Float.class || cls == Double.class;
}
@Override
public int getElementsPerItem() {
return getElementsPerItem(getDtype());
}
@Override
public int getItemsize() {
return getItemsize(getDtype(), getElementsPerItem());
}
/**
* @param dtype
* @return number of elements per item
*/
public static int getElementsPerItem(final int dtype) {
switch (dtype) {
case ARRAYINT8:
case ARRAYINT16:
case ARRAYINT32:
case ARRAYINT64:
case ARRAYFLOAT32:
case ARRAYFLOAT64:
throw new UnsupportedOperationException("Multi-element type unsupported");
case COMPLEX64:
case COMPLEX128:
return 2;
}
return 1;
}
/**
* @param dtype
* @return length of single item in bytes
*/
public static int getItemsize(final int dtype) {
return getItemsize(dtype, getElementsPerItem(dtype));
}
/**
* @param dtype
* @param isize
* number of elements in an item
* @return length of single item in bytes
*/
public static int getItemsize(final int dtype, final int isize) {
int size;
switch (dtype) {
case BOOL:
size = 1; // How is this defined?
break;
case INT8:
case ARRAYINT8:
size = Byte.SIZE / 8;
break;
case INT16:
case ARRAYINT16:
case RGB:
size = Short.SIZE / 8;
break;
case INT32:
case ARRAYINT32:
size = Integer.SIZE / 8;
break;
case INT64:
case ARRAYINT64:
size = Long.SIZE / 8;
break;
case FLOAT32:
case ARRAYFLOAT32:
case COMPLEX64:
size = Float.SIZE / 8;
break;
case FLOAT64:
case ARRAYFLOAT64:
case COMPLEX128:
size = Double.SIZE / 8;
break;
default:
size = 0;
break;
}
return size * isize;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(final String name) {
this.name = name;
}
@Override
public int getSize() {
if (odata == null) {
throw new NullPointerException("The data object inside the dataset has not been allocated, "
+ "this suggests a failed or absent construction of the dataset");
}
return size;
}
@Override
public int[] getShape() {
// make a copy of the dimensions data, and put that out
if (shape == null) {
logger.warn("Shape is null!!!");
return new int[] {};
}
return shape.clone();
}
@Override
public int getRank() {
return shape.length;
}
@Override
public int getNbytes() {
return getSize() * getItemsize();
}
/**
* Check for -1 placeholder in shape and replace if necessary
* @param shape
* @param size
*/
private void checkShape(int[] shape, int size) {
int rank = shape.length;
int found = -1;
int nsize = 1;
for (int i = 0; i < rank; i++) {
int d = shape[i];
if (d == -1) {
if (found == -1) {
found = i;
} else {
logger.error("Can only have one -1 placeholder in shape");
throw new IllegalArgumentException("Can only have one -1 placeholder in shape");
}
} else {
nsize *= d;
}
}
if (found >= 0) {
shape[found] = size/nsize;
} else if (nsize != size) {
logger.error("New shape is not same size as old shape");
throw new IllegalArgumentException("New size is not same as the old size. Old size is "+size+" new size is "+nsize+" and shape is "+Arrays.toString(shape));
}
}
@Override
public void setShape(final int... shape) {
int[] nshape = shape.clone();
checkShape(nshape, size);
if (Arrays.equals(this.shape, nshape))
return;
if (stride != null) {
// the only compatible shapes are ones where new dimensions are factors of old dimensions
// or are combined adjacent old dimensions
int[] oshape = this.shape;
int orank = oshape.length;
int nrank = nshape.length;
int[] nstride = new int[nrank];
boolean ones = true;
for (int i = 0, j = 0; i < orank || j < nrank;) {
if (i < orank && j < nrank && oshape[i] == nshape[j]) {
nstride[j++] = stride[i++];
} else if (j < nrank && nshape[j] == 1) {
nstride[j++] = 0;
} else if (i < orank && oshape[i] == 1) {
i++;
} else {
if (j < nrank)
j++;
if (i < orank)
i++;
ones = false;
}
}
if (!ones) { // not just ones differ in shapes
int[] ostride = stride;
int ob = 0;
int oe = 1;
int nb = 0;
int ne = 1;
while (ob < orank && nb < nrank) {
int ol = oshape[ob];
int nl = nshape[nb];
if (nl < ol) { // find group of shape dimensions that form common size
do { // case where new shape spreads single dimension over several dimensions
if (ne == nrank) {
break;
}
nl *= nshape[ne++];
} while (nl < ol);
if (nl != ol) {
logger.error("Subshape is incompatible with single dimension");
throw new IllegalArgumentException("Subshape is incompatible with single dimension");
}
int on = ne - 1;
while (nshape[on] == 1) {
on
}
nstride[on] = ostride[ob];
for (int n = on - 1; n >= nb; n
if (nshape[n] == 1)
continue;
nstride[n] = nshape[on] * nstride[on];
on = n;
}
} else if (ol < nl) {
do { // case where new shape combines several dimensions into one dimension
if (oe == orank) {
break;
}
ol *= oshape[oe++];
} while (ol < nl);
if (nl != ol) {
logger.error("Single dimension is incompatible with subshape");
throw new IllegalArgumentException("Single dimension is incompatible with subshape");
}
int oo = oe - 1;
while (oshape[oo] == 1) {
oo
}
int os = ostride[oo];
for (int o = oo - 1; o >= ob; o
if (oshape[o] == 1)
continue;
if (ostride[o] != oshape[oo] * ostride[oo]) {
logger.error("Subshape cannot be a non-contiguous view");
throw new IllegalArgumentException("Subshape cannot be a non-contiguous view");
}
oo = o;
}
nstride[nb] = os;
} else {
nstride[nb] = ostride[ob];
}
ob = oe++;
nb = ne++;
}
}
stride = nstride;
}
reshapeMetadata(this.shape, nshape);
this.shape = nshape;
if (storedValues != null)
filterStoredValues(storedValues); // as it is dependent on shape
}
@Override
public int[] getShapeRef() {
return shape;
}
@Override
public int getOffset() {
return offset;
}
@Override
public int[] getStrides() {
return stride;
}
@Override
public Serializable getBuffer() {
return odata;
}
/**
* Create a stride array from dataset
* @param a dataset
* @param offset output offset
* @return new strides
*/
public static int[] createStrides(Dataset a, final int[] offset) {
return createStrides(a.getElementsPerItem(), a.getShapeRef(), a.getStrides(), a.getOffset(), offset);
}
/**
* Create a stride array from dataset
* @param isize
* @param shape
* @param oStride original stride
* @param oOffset original offset (only used if there is an original stride)
* @param offset output offset
* @return new strides
*/
public static int[] createStrides(final int isize, final int[] shape, final int[] oStride, final int oOffset, final int[] offset) {
int rank = shape.length;
final int[] stride;
if (oStride == null) {
offset[0] = 0;
stride = new int[rank];
int s = isize;
for (int j = rank - 1; j >= 0; j
stride[j] = s;
s *= shape[j];
}
} else {
offset[0] = oOffset;
stride = oStride.clone();
}
return stride;
}
/**
* Create a stride array from slice information and a dataset
* @param slice
* @param a dataset
* @param stride output stride
* @param offset output offset
* @return new shape
*/
public static int[] createStrides(final SliceND slice, final Dataset a, final int[] stride, final int[] offset) {
return createStrides(slice, a.getElementsPerItem(), a.getShapeRef(), a.getStrides(), a.getOffset(), stride, offset);
}
/**
* Create a stride array from slice and dataset information
* @param slice
* @param isize
* @param shape
* @param oStride original stride
* @param oOffset original offset (only used if there is an original stride)
* @param stride output stride
* @param offset output offset
* @return new shape
*/
public static int[] createStrides(final SliceND slice, final int isize, final int[] shape, final int[] oStride, final int oOffset, final int[] stride, final int[] offset) {
int[] lstart = slice.getStart();
int[] lstep = slice.getStep();
int[] newShape = slice.getShape();
int rank = shape.length;
if (oStride == null) {
int s = isize;
offset[0] = 0;
for (int j = rank - 1; j >= 0; j
stride[j] = s * lstep[j];
offset[0] += s * lstart[j];
s *= shape[j];
}
} else {
offset[0] = oOffset;
for (int j = 0; j < rank; j++) {
int s = oStride[j];
stride[j] = lstep[j] * s;
offset[0] += lstart[j] * s;
}
}
return newShape;
}
/**
* Create a stride array from a dataset to a broadcast shape
* @param a dataset
* @param broadcastShape
* @return stride array
*/
public static int[] createBroadcastStrides(Dataset a, final int[] broadcastShape) {
return createBroadcastStrides(a.getElementsPerItem(), a.getShapeRef(), a.getStrides(), broadcastShape);
}
/**
* Create a stride array from a dataset to a broadcast shape
* @param isize
* @param shape
* @param oStride original stride
* @param broadcastShape
* @return stride array
*/
public static int[] createBroadcastStrides(final int isize, final int[] shape, final int[] oStride, final int[] broadcastShape) {
int rank = shape.length;
if (broadcastShape.length != rank) {
throw new IllegalArgumentException("Dataset must have same rank as broadcast shape");
}
int[] stride = new int[rank];
if (oStride == null) {
int s = isize;
for (int j = rank - 1; j >= 0; j
if (broadcastShape[j] == shape[j]) {
stride[j] = s;
s *= shape[j];
} else {
stride[j] = 0;
}
}
} else {
for (int j = 0; j < rank; j++) {
if (broadcastShape[j] == shape[j]) {
stride[j] = oStride[j];
} else {
stride[j] = 0;
}
}
}
return stride;
}
@Override
public Dataset getSliceView(final int[] start, final int[] stop, final int[] step) {
return getSliceView(new SliceND(shape, start, stop, step));
}
@Override
public Dataset getSliceView(Slice... slice) {
if (slice == null || slice.length == 0) {
int[] sOffset = new int[1];
int[] sStride = createStrides(this, sOffset);
AbstractDataset s = getView();
s.stride = sStride;
s.offset = sOffset[0];
s.base = base == null ? this : base;
return s;
}
return getSliceView(new SliceND(shape, slice));
}
/**
* Get a slice of the dataset. The returned dataset is a view on a selection of items
* @param slice
* @return slice view
*/
@Override
public Dataset getSliceView(SliceND slice) {
final int rank = shape.length;
int[] sStride = new int[rank];
int[] sOffset = new int[1];
int[] sShape = createStrides(slice, this, sStride, sOffset);
AbstractDataset s = getView();
s.shape = sShape;
s.size = calcSize(sShape);
s.stride = sStride;
s.offset = sOffset[0];
s.base = base == null ? this : base;
s.metadata = copyMetadata();
s.sliceMetadata(true, slice);
if (slice.isAll()) {
s.setName(name);
} else {
s.setDirty();
s.setName(name + BLOCK_OPEN + slice + BLOCK_CLOSE);
}
return s;
}
/**
* Get flattened view index of given position
* @param pos
* the integer array specifying the n-D position
* @return the index on the flattened dataset
*/
private int getFlat1DIndex(final int[] pos) {
final int imax = pos.length;
if (imax == 0) {
return 0;
}
return get1DIndexFromShape(pos);
}
/**
* Get flattened view index of given position
* @param shape
* @param pos
* the integer array specifying the n-D position
* @return the index on the flattened dataset
*/
public static int getFlat1DIndex(final int[] shape, final int[] pos) {
final int imax = pos.length;
if (imax == 0) {
return 0;
}
return get1DIndexFromShape(shape, pos);
}
@Override
public int get1DIndex(final int... n) {
final int imax = n.length;
final int rank = shape.length;
if (imax == 0) {
if (rank == 0 || (rank == 1 && shape[0] <= 1))
return stride == null ? 0 : offset;
throw new IllegalArgumentException("One or more index parameters must be supplied");
} else if (imax > rank) {
throw new IllegalArgumentException("No of index parameters is different to the shape of data: " + imax
+ " given " + rank + " required");
}
return stride == null ? get1DIndexFromShape(n) : get1DIndexFromStrides(n);
}
private static void throwAIOOBException(int i, int s, int d) {
throw new ArrayIndexOutOfBoundsException("Index (" + i + ") out of range [-" + s + "," + s
+ "] in dimension " + d);
}
/**
* @param i
* @return the index on the data array corresponding to that location
*/
protected int get1DIndex(int i) {
if (shape.length > 1) {
logger.debug("This dataset is not 1D but was addressed as such");
return get1DIndex(new int[] {i});
}
if (i < 0) {
i += shape[0];
}
if (i < 0 || i >= shape[0]) {
throwAIOOBException(i, shape[0], 0);
}
return stride == null ? i : i*stride[0] + offset;
}
/**
* @param i
* @param j
* @return the index on the data array corresponding to that location
*/
protected int get1DIndex(int i, int j) {
if (shape.length != 2) {
logger.debug("This dataset is not 2D but was addressed as such");
return get1DIndex(new int[] {i, j});
}
if (i < 0) {
i += shape[0];
}
if (i < 0 || i >= shape[0]) {
throwAIOOBException(i, shape[0], 0);
}
if (j < 0) {
j += shape[1];
}
if (j < 0 || j >= shape[1]) {
throwAIOOBException(i, shape[1], 1);
}
return stride == null ? i*shape[1] + j : i*stride[0] + j*stride[1] + offset;
}
protected int get1DIndexFromShape(final int... n) {
return get1DIndexFromShape(shape, n);
}
protected static int get1DIndexFromShape(final int[] shape, final int... n) {
final int imax = n.length;
final int rank = shape.length;
// if (rank != imax) {
int index = 0;
int i = 0;
for (; i < imax; i++) {
final int si = shape[i];
int ni = n[i];
if (ni < 0) {
ni += si;
}
if (ni < 0 || ni >= si) {
throwAIOOBException(ni, si, i);
}
index = index * si + ni;
}
for (; i < rank; i++) {
index *= shape[i];
}
return index;
}
private int get1DIndexFromStrides(final int... n) {
return get1DIndexFromStrides(shape, stride, offset, n);
}
private static int get1DIndexFromStrides(final int[] shape, final int[] stride, final int offset, final int... n) {
final int rank = shape.length;
if (rank != n.length) {
throw new IllegalArgumentException("Number of position indexes must be equal to rank");
}
int index = offset;
for (int i = 0; i < rank; i++) {
final int si = shape[i];
int ni = n[i];
if (ni < 0) {
ni += si;
}
if (ni < 0 || ni >= si) {
throwAIOOBException(ni, si, i);
}
index += stride[i] * ni;
}
return index;
}
@Override
public int[] getNDPosition(final int n) {
if (isIndexInRange(n)) {
throw new IllegalArgumentException("Index provided " + n
+ "is larger then the size of the containing array");
}
return stride == null ? getNDPositionFromShape(n, shape) : getNDPositionFromStrides(n);
}
private boolean isIndexInRange(final int n) {
if (stride == null) {
return n >= size;
}
return n >= getBufferLength();
}
/**
* @return entire buffer length
*/
abstract protected int getBufferLength();
/**
* Get n-D position from given index
* @param n index
* @param shape
* @return n-D position
*/
public static int[] getNDPositionFromShape(int n, int[] shape) {
if (shape == null || shape.length == 0)
return new int[0];
int rank = shape.length;
if (rank == 1) {
return new int[] { n };
}
int[] output = new int[rank];
for (rank--; rank > 0; rank--) {
output[rank] = n % shape[rank];
n /= shape[rank];
}
output[0] = n;
return output;
}
private int[] getNDPositionFromStrides(int n) {
n -= offset;
int rank = shape.length;
if (rank == 1) {
return new int[] { n / stride[0] };
}
int[] output = new int[rank];
int i = 0;
while (i != n) { // TODO find more efficient way than this exhaustive search
int j = rank - 1;
for (; j >= 0; j
output[j]++;
i += stride[j];
if (output[j] >= shape[j]) {
output[j] = 0;
i -= shape[j] * stride[j];
} else {
break;
}
}
if (j == -1) {
logger.error("Index was not found in this strided dataset");
throw new IllegalArgumentException("Index was not found in this strided dataset");
}
}
return output;
}
@Override
public int checkAxis(int axis) {
return checkAxis(shape.length, axis);
}
/**
* Check that axis is in range [-rank,rank)
*
* @param rank
* @param axis
* @return sanitized axis in range [0, rank)
*/
protected static int checkAxis(int rank, int axis) {
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
throw new IndexOutOfBoundsException("Axis " + axis + " given is out of range [0, " + rank + ")");
}
return axis;
}
protected static final char BLOCK_OPEN = '[';
protected static final char BLOCK_CLOSE = ']';
@Override
public String toString() {
return toString(false);
}
@Override
public String toString(boolean showData) {
final int rank = shape == null ? 0 : shape.length;
final StringBuilder out = new StringBuilder();
if (!showData) {
if (name != null && name.length() > 0) {
out.append("Dataset '");
out.append(name);
out.append("' has shape ");
} else {
out.append("Dataset shape is ");
}
out.append(BLOCK_OPEN);
if (rank > 0) {
out.append(shape[0]);
}
for (int i = 1; i < rank; i++) {
out.append(", " + shape[i]);
}
out.append(BLOCK_CLOSE);
return out.toString();
}
if (size == 0) {
return out.toString();
}
if (rank > 0) {
int[] pos = new int[rank];
final StringBuilder lead = new StringBuilder();
printBlocks(out, lead, 0, pos);
} else {
out.append(getString());
}
return out.toString();
}
/**
* Limit to strings output via the toString() method
*/
private static int maxStringLength = 120;
/**
* Set maximum line length for toString() method
* @param maxLineLength
*/
public static void setMaxLineLength(int maxLineLength) {
maxStringLength = maxLineLength;
}
/**
* @return maximum line length for toString() method
*/
public static int getMaxLineLength() {
return maxStringLength;
}
/**
* Limit to number of sub-blocks output via the toString() method
*/
private static final int MAX_SUBBLOCKS = 6;
private final static String SEPARATOR = ",";
private final static String SPACE = " ";
private final static String ELLIPSIS = "...";
private final static String NEWLINE = "\n";
/**
* Make a line of output for last dimension of dataset
*
* @param start
* @return line
*/
private StringBuilder makeLine(final int end, final int... start) {
StringBuilder line = new StringBuilder();
final int[] pos;
if (end >= start.length) {
pos = Arrays.copyOf(start, end + 1);
} else {
pos = start;
}
pos[end] = 0;
line.append(BLOCK_OPEN);
line.append(getString(pos));
final int length = shape[end];
// trim elements printed if length exceed estimate of maximum elements
int excess = length - maxStringLength / 3; // space + number + separator
if (excess > 0) {
int index = (length - excess) / 2;
for (int y = 1; y < index; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
index = (length + excess) / 2;
for (int y = index; y < length; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
} else {
for (int y = 1; y < length; y++) {
line.append(SEPARATOR + SPACE);
pos[end] = y;
line.append(getString(pos));
}
}
line.append(BLOCK_CLOSE);
// trim string down to limit
excess = line.length() - maxStringLength - ELLIPSIS.length() - 1;
if (excess > 0) {
int index = line.substring(0, (line.length() - excess) / 2).lastIndexOf(SEPARATOR) + 2;
StringBuilder out = new StringBuilder(line.subSequence(0, index));
out.append(ELLIPSIS + SEPARATOR);
index = line.substring((line.length() + excess) / 2).indexOf(SEPARATOR) + (line.length() + excess) / 2 + 1;
out.append(line.subSequence(index, line.length()));
return out;
}
return line;
}
/**
* recursive method to print blocks
*/
private void printBlocks(final StringBuilder out, final StringBuilder lead, final int level, final int[] pos) {
if (out.length() > 0) {
char last = out.charAt(out.length() - 1);
if (last != BLOCK_OPEN) {
out.append(lead);
}
}
final int end = getRank() - 1;
if (level != end) {
out.append(BLOCK_OPEN);
int length = shape[level];
// first sub-block
pos[level] = 0;
StringBuilder newlead = new StringBuilder(lead);
newlead.append(SPACE);
printBlocks(out, newlead, level + 1, pos);
if (length < 2) { // escape
out.append(BLOCK_CLOSE);
return;
}
out.append(SEPARATOR + NEWLINE);
for (int i = level + 1; i < end; i++) {
out.append(NEWLINE);
}
// middle sub-blocks
if (length < MAX_SUBBLOCKS) {
for (int x = 1; x < length - 1; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
} else {
final int excess = length - MAX_SUBBLOCKS;
int xmax = (length - excess) / 2;
for (int x = 1; x < xmax; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
out.append(newlead);
out.append(ELLIPSIS + SEPARATOR + NEWLINE);
xmax = (length + excess) / 2;
for (int x = xmax; x < length - 1; x++) {
pos[level] = x;
printBlocks(out, newlead, level + 1, pos);
if (end <= level + 1) {
out.append(SEPARATOR + NEWLINE);
} else {
out.append(SEPARATOR + NEWLINE + NEWLINE);
}
}
}
// last sub-block
pos[level] = length - 1;
printBlocks(out, newlead, level + 1, pos);
out.append(BLOCK_CLOSE);
} else {
out.append(makeLine(end, pos));
}
}
@Override
public void setDirty() {
if (storedValues != null)
storedValues.clear();
}
@Override
public Dataset squeezeEnds() {
return squeeze(true);
}
@Override
public Dataset squeeze() {
return squeeze(false);
}
@Override
public Dataset squeeze(boolean onlyFromEnds) {
final int[] tshape = squeezeShape(shape, onlyFromEnds);
final int[] oshape = shape;
if (stride == null) {
shape = tshape;
} else {
int rank = shape.length;
int trank = tshape.length;
if (trank < rank) {
int[] tstride = new int[tshape.length];
if (onlyFromEnds) {
for (int i = 0; i < rank; i++) {
if (shape[i] != 1) {
for (int k = 0; k < trank; k++) {
tstride[k] = stride[i++];
}
break;
}
}
} else {
int t = 0;
for (int i = 0; i < rank; i++) {
if (shape[i] != 1) {
tstride[t++] = stride[i];
}
}
}
shape = tshape;
stride = tstride;
}
}
reshapeMetadata(oshape, shape);
return this;
}
/**
* Remove dimensions of 1 in given shape - from both ends only, if true
*
* @param oshape
* @param onlyFromEnds
* @return newly squeezed shape (or original if unsqueezed)
*/
public static int[] squeezeShape(final int[] oshape, boolean onlyFromEnds) {
int unitDims = 0;
int rank = oshape.length;
int start = 0;
if (onlyFromEnds) {
int i = rank - 1;
for (; i >= 0; i
if (oshape[i] == 1) {
unitDims++;
} else {
break;
}
}
for (int j = 0; j <= i; j++) {
if (oshape[j] == 1) {
unitDims++;
} else {
start = j;
break;
}
}
} else {
for (int i = 0; i < rank; i++) {
if (oshape[i] == 1) {
unitDims++;
}
}
}
if (unitDims == 0) {
return oshape;
}
int[] newDims = new int[rank - unitDims];
if (unitDims == rank)
return newDims; // zero-rank dataset
if (onlyFromEnds) {
rank = newDims.length;
for (int i = 0; i < rank; i++) {
newDims[i] = oshape[i+start];
}
} else {
int j = 0;
for (int i = 0; i < rank; i++) {
if (oshape[i] > 1) {
newDims[j++] = oshape[i];
if (j >= newDims.length)
break;
}
}
}
return newDims;
}
/**
* Remove dimension of 1 in given shape
*
* @param oshape
* @param axis
* @return newly squeezed shape
*/
public static int[] squeezeShape(final int[] oshape, int axis) {
if (oshape == null || oshape.length == 0) {
return new int[0];
}
int rank = oshape.length;
if (axis < 0) {
axis += rank;
}
if (axis < 0 || axis >= rank) {
logger.error("Axis argument is outside allowed range");
throw new IllegalArgumentException("Axis argument is outside allowed range");
}
int[] nshape = new int[rank-1];
for (int i = 0; i < axis; i++) {
nshape[i] = oshape[i];
}
for (int i = axis+1; i < rank; i++) {
nshape[i-1] = oshape[i];
}
return nshape;
}
/**
* Check if shapes are broadcast compatible
*
* @param ashape
* @param bshape
* @return true if they are compatible
*/
public static boolean areShapesBroadcastCompatible(final int[] ashape, final int[] bshape) {
if (ashape.length < bshape.length) {
return areShapesBroadcastCompatible(bshape, ashape);
}
for (int a = ashape.length - bshape.length, b = 0; a < ashape.length && b < bshape.length; a++, b++) {
if (ashape[a] != bshape[b] && ashape[a] != 1 && bshape[b] != 1) {
return false;
}
}
return true;
}
/**
* Check if shapes are compatible, ignoring extra axes of length 1
*
* @param ashape
* @param bshape
* @return true if they are compatible
*/
public static boolean areShapesCompatible(final int[] ashape, final int[] bshape) {
List<Integer> alist = new ArrayList<Integer>();
for (int a : ashape) {
if (a > 1) alist.add(a);
}
final int imax = alist.size();
int i = 0;
for (int b : bshape) {
if (b == 1)
continue;
if (i >= imax || b != alist.get(i++))
return false;
}
return i == imax;
}
/**
* Check if shapes are compatible but skip axis
*
* @param ashape
* @param bshape
* @param axis
* @return true if they are compatible
*/
public static boolean areShapesCompatible(final int[] ashape, final int[] bshape, final int axis) {
if (ashape.length != bshape.length) {
return false;
}
final int rank = ashape.length;
for (int i = 0; i < rank; i++) {
if (i != axis && ashape[i] != bshape[i]) {
return false;
}
}
return true;
}
@Override
public boolean isCompatibleWith(final ILazyDataset g) {
return areShapesCompatible(shape, g.getShape());
}
@Override
public void checkCompatibility(final ILazyDataset g) throws IllegalArgumentException {
checkCompatibility(this, g);
}
public static void checkCompatibility(final ILazyDataset g, final ILazyDataset h) throws IllegalArgumentException {
if (!areShapesCompatible(g.getShape(), h.getShape())) {
throw new IllegalArgumentException("Shapes do not match");
}
}
@Override
public Dataset reshape(final int... shape) {
Dataset a = getView();
try {
a.setShape(shape);
} catch (IllegalArgumentException e) {
a = a.clone();
a.setShape(shape);
}
return a;
}
/**
* Create a dataset from object (automatically detect dataset type)
*
* @param obj
* can be a Java list, array or Number
* @return dataset
*/
public static Dataset array(final Object obj) {
return DatasetFactory.createFromObject(obj);
}
/**
* Create a dataset from object (automatically detect dataset type)
*
* @param obj
* can be a Java list, array or Number
* @param isUnsigned
* if true, interpret integer values as unsigned by increasing element bit width
* @return dataset
*/
public static Dataset array(final Object obj, boolean isUnsigned) {
return DatasetFactory.createFromObject(obj, isUnsigned);
}
/**
* Create a dataset from object
*
* @param obj
* can be a Java list, array or Number
* @param dtype
* @return dataset
*/
public static Dataset array(final Object obj, final int dtype) {
return DatasetFactory.createFromObject(obj, dtype);
}
/**
* Create dataset of appropriate type from list
*
* @param objectList
* @return dataset filled with values from list
*/
public static Dataset createFromList(List<?> objectList) {
return DatasetFactory.createFromList(objectList);
}
/**
* @param shape
* @param dtype
* @return a new dataset of given shape and type, filled with zeros
*/
public static Dataset zeros(final int[] shape, final int dtype) {
return DatasetFactory.zeros(shape, dtype);
}
/**
* @param itemSize
* if equal to 1, then non-compound dataset is returned
* @param shape
* @param dtype
* @return a new dataset of given item size, shape and type, filled with zeros
*/
public static Dataset zeros(final int itemSize, final int[] shape, final int dtype) {
return DatasetFactory.zeros(itemSize, shape, dtype);
}
/**
* @param dataset
* @return a new dataset of same shape and type as input dataset, filled with zeros
*/
public static Dataset zeros(final Dataset dataset) {
return zeros(dataset, dataset.getDtype());
}
/**
* Create a new dataset of same shape as input dataset, filled with zeros. If dtype is not
* explicitly compound then an elemental dataset is created
* @param dataset
* @param dtype
* @return a new dataset
*/
public static Dataset zeros(final Dataset dataset, final int dtype) {
final int[] shape = dataset.getShapeRef();
final int isize = isDTypeElemental(dtype) ? 1 :dataset.getElementsPerItem();
return zeros(isize, shape, dtype);
}
/**
* @param dataset
* @return a new dataset of same shape and type as input dataset, filled with ones
*/
public static Dataset ones(final Dataset dataset) {
return ones(dataset, dataset.getDtype());
}
/**
* Create a new dataset of same shape as input dataset, filled with ones. If dtype is not
* explicitly compound then an elemental dataset is created
* @param dataset
* @param dtype
* @return a new dataset
*/
public static Dataset ones(final Dataset dataset, final int dtype) {
final int[] shape = dataset.getShapeRef();
final int isize = isDTypeElemental(dtype) ? 1 :dataset.getElementsPerItem();
return ones(isize, shape, dtype);
}
/**
* @param shape
* @param dtype
* @return a new dataset of given shape and type, filled with ones
*/
public static Dataset ones(final int[] shape, final int dtype) {
return DatasetFactory.ones(shape, dtype);
}
/**
* @param itemSize
* if equal to 1, then non-compound dataset is returned
* @param shape
* @param dtype
* @return a new dataset of given item size, shape and type, filled with ones
*/
public static Dataset ones(final int itemSize, final int[] shape, final int dtype) {
return DatasetFactory.ones(itemSize, shape, dtype);
}
/**
* @param stop
* @param dtype
* @return a new dataset of given shape and type, filled with values determined by parameters
*/
public static Dataset arange(final double stop, final int dtype) {
return arange(0, stop, 1, dtype);
}
/**
* @param start
* @param stop
* @param step
* @param dtype
* @return a new 1D dataset of given type, filled with values determined by parameters
*/
public static Dataset arange(final double start, final double stop, final double step, final int dtype) {
return DatasetFactory.createRange(start, stop, step, dtype);
}
/**
* @param start
* @param stop
* @param step
* @return number of steps to take
*/
public static int calcSteps(final double start, final double stop, final double step) {
if (step > 0) {
return (int) Math.ceil((stop - start) / step);
}
return (int) Math.ceil((stop - start) / step);
}
@Override
public boolean isComplex() {
int type = getDtype();
return type == COMPLEX64 || type == COMPLEX128;
}
@Override
public Dataset real() {
return this;
}
@Override
public Dataset realView() {
return getView();
}
@Override
public Dataset getSlice(final int[] start, final int[] stop, final int[] step) {
return getSlice(new SliceND(shape, start, stop, step));
}
@Override
public Dataset getSlice(Slice... slice) {
return getSlice(new SliceND(shape, slice));
}
@Override
public Dataset getSlice(IMonitor monitor, Slice... slice) {
return getSlice(slice);
}
@Override
public Dataset getSlice(IMonitor monitor, SliceND slice) {
return getSlice(slice);
}
@Override
public Dataset getSlice(IMonitor monitor, int[] start, int[] stop, int[] step) {
return getSlice(start, stop, step);
}
/**
* Get a slice of the dataset. The returned dataset is a copied selection of items
* @param slice
* @return The dataset of the sliced data
*/
@Override
public Dataset getSlice(final SliceND slice) {
SliceIterator it = (SliceIterator) getSliceIterator(slice);
AbstractDataset s = getSlice(it);
s.metadata = copyMetadata();
s.sliceMetadata(true, slice);
return s;
}
/**
* Get a slice of the dataset. The returned dataset is a copied selection of items
*
* @param iterator Slice iterator
* @return The dataset of the sliced data
*/
abstract public AbstractDataset getSlice(final SliceIterator iterator);
@Override
public Dataset setSlice(final Object obj, final SliceND slice) {
Dataset ds;
if (obj instanceof Dataset) {
ds = (Dataset) obj;
} else if (!(obj instanceof IDataset)) {
ds = DatasetFactory.createFromObject(obj, isComplex() || getElementsPerItem() == 1 ? FLOAT64 : ARRAYFLOAT64);
} else {
ds = DatasetUtils.convertToDataset((IDataset) obj);
}
return setSlicedView(getSliceView(slice), ds);
}
@Override
public Dataset setSlice(final Object obj, final int[] start, final int[] stop, final int[] step) {
return setSlice(obj, new SliceND(shape, start, stop, step));
}
/**
* Set a view of current dataset to given dataset with broadcasting
* @param view
* @param d
* @return this dataset
*/
abstract Dataset setSlicedView(Dataset view, Dataset d);
@Override
public Dataset setSlice(Object obj, Slice... slice) {
if (slice == null || slice.length == 0) {
return setSlice(obj, new SliceND(shape));
}
return setSlice(obj, new SliceND(shape, slice));
}
@Override
public boolean all() {
return Comparisons.allTrue(this);
}
@Override
public BooleanDataset all(final int axis) {
return Comparisons.allTrue(this, axis);
}
@Override
public boolean any() {
return Comparisons.anyTrue(this);
}
@Override
public BooleanDataset any(final int axis) {
return Comparisons.anyTrue(this, axis);
}
@Override
public Dataset ifloorDivide(final Object o) {
return idivide(o).ifloor();
}
@Override
public double residual(final Object o) {
return residual(o, null, false);
}
@Override
public double residual(final Object o, boolean ignoreNaNs) {
return residual(o, null, ignoreNaNs);
}
public static final String STORE_HASH = "hash";
protected static final String STORE_SHAPELESS_HASH = "shapelessHash";
public static final String STORE_MAX = "max";
public static final String STORE_MIN = "min";
protected static final String STORE_MAX_POS = "maxPos";
protected static final String STORE_MIN_POS = "minPos";
protected static final String STORE_STATS = "stats";
protected static final String STORE_SUM = "sum";
protected static final String STORE_MEAN = "mean";
protected static final String STORE_VAR = "var";
private static final String STORE_POS_MAX = "+max";
private static final String STORE_POS_MIN = "+min";
protected static final String STORE_COUNT = "count";
private static final String STORE_INDEX = "Index";
protected static final String STORE_BROADCAST = "Broadcast";
/**
* Get value from store
*
* @param key
* @return value
*/
public Object getStoredValue(String key) {
if (storedValues == null) {
return null;
}
return storedValues.get(key);
}
/**
* Set value in store
* <p>
* This is a <b>private method</b>: do not use!
*
* @param key
* @param obj
*/
public void setStoredValue(String key, Object obj) {
if (storedValues == null) {
storedValues = new HashMap<String, Object>();
}
storedValues.put(key, obj);
}
protected static String storeName(boolean ignoreNaNs, String name) {
return storeName(ignoreNaNs, false, name);
}
protected static String storeName(boolean ignoreNaNs, boolean ignoreInfs, String name) {
return (ignoreInfs ? "inf" : "") + (ignoreNaNs ? "nan" : "") + name;
}
/**
* Copy stored values from original to derived dataset
* @param orig
* @param derived
* @param shapeChanged
*/
protected static void copyStoredValues(IDataset orig, AbstractDataset derived, boolean shapeChanged) {
if (orig instanceof AbstractDataset && ((AbstractDataset) orig).storedValues != null) {
derived.storedValues = new HashMap<String, Object>(((AbstractDataset) orig).storedValues);
if (shapeChanged) {
filterStoredValues(derived.storedValues);
}
}
}
private static void filterStoredValues(Map<String, Object> map) {
map.remove(STORE_HASH);
List<String> keys = new ArrayList<String>();
for (String n : map.keySet()) {
if (n.contains("-")) { // remove anything which is axis-specific
keys.add(n);
}
}
for (String n : keys) {
map.remove(n);
}
}
/**
* Calculate minimum and maximum for a dataset
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
*/
protected void calculateMaxMin(final boolean ignoreNaNs, final boolean ignoreInfs) {
IndexIterator iter = getIterator();
double amax = Double.NEGATIVE_INFINITY;
double amin = Double.POSITIVE_INFINITY;
double pmax = Double.MIN_VALUE;
double pmin = Double.POSITIVE_INFINITY;
double hash = 0;
boolean hasNaNs = false;
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (Double.isNaN(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreNaNs)
continue;
hasNaNs = true;
} else if (Double.isInfinite(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreInfs)
continue;
} else {
hash = (hash * 19 + val) % Integer.MAX_VALUE;
}
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
if (val > 0) {
if (val < pmin) {
pmin = val;
}
if (val > pmax) {
pmax = val;
}
}
}
int ihash = ((int) hash) * 19 + getDtype() * 17 + getElementsPerItem();
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_SHAPELESS_HASH), ihash);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(amax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(amin));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(pmax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(pmin));
}
/**
* Calculate summary statistics for a dataset
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
* @param name
*/
protected void calculateSummaryStats(final boolean ignoreNaNs, final boolean ignoreInfs, final String name) {
final IndexIterator iter = getIterator();
final SummaryStatistics stats = new SummaryStatistics();
//sum of logs is slow and we dont use it, so blocking its calculation here
stats.setSumLogImpl(new NullStorelessUnivariateStatistic());
if (storedValues == null || !storedValues.containsKey(STORE_HASH)) {
boolean hasNaNs = false;
double hash = 0;
double pmax = Double.MIN_VALUE;
double pmin = Double.POSITIVE_INFINITY;
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (Double.isNaN(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreNaNs)
continue;
hasNaNs = true;
} else if (Double.isInfinite(val)) {
hash = (hash * 19) % Integer.MAX_VALUE;
if (ignoreInfs)
continue;
} else {
hash = (hash * 19 + val) % Integer.MAX_VALUE;
}
if (val > 0) {
if (val < pmin) {
pmin = val;
}
if (val > pmax) {
pmax = val;
}
}
stats.addValue(val);
}
int ihash = ((int) hash) * 19 + getDtype() * 17 + getElementsPerItem();
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_SHAPELESS_HASH), ihash);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(stats.getMax()));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(stats.getMin()));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MAX), hasNaNs ? Double.NaN : fromDoubleToNumber(pmax));
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_POS_MIN), hasNaNs ? Double.NaN : fromDoubleToNumber(pmin));
storedValues.put(name, stats);
} else {
while (iter.hasNext()) {
final double val = getElementDoubleAbs(iter.index);
if (ignoreNaNs && Double.isNaN(val)) {
continue;
}
if (ignoreInfs && Double.isInfinite(val)) {
continue;
}
stats.addValue(val);
}
storedValues.put(name, stats);
}
}
/**
* Calculate summary statistics for a dataset along an axis
* @param ignoreNaNs if true, ignore NaNs
* @param ignoreInfs if true, ignore infinities
* @param axis
*/
protected void calculateSummaryStats(final boolean ignoreNaNs, final boolean ignoreInfs, final int axis) {
int rank = getRank();
int[] oshape = getShape();
int alen = oshape[axis];
oshape[axis] = 1;
int[] nshape = new int[rank - 1];
for (int i = 0; i < axis; i++) {
nshape[i] = oshape[i];
}
for (int i = axis + 1; i < rank; i++) {
nshape[i - 1] = oshape[i];
}
final int dtype = getDtype();
IntegerDataset count = new IntegerDataset(nshape);
Dataset max = DatasetFactory.zeros(nshape, dtype);
Dataset min = DatasetFactory.zeros(nshape, dtype);
IntegerDataset maxIndex = new IntegerDataset(nshape);
IntegerDataset minIndex = new IntegerDataset(nshape);
Dataset sum = DatasetFactory.zeros(nshape, getLargestDType(dtype));
DoubleDataset mean = new DoubleDataset(nshape);
DoubleDataset var = new DoubleDataset(nshape);
IndexIterator qiter = max.getIterator(true);
int[] qpos = qiter.getPos();
int[] spos = oshape.clone();
while (qiter.hasNext()) {
int i = 0;
for (; i < axis; i++) {
spos[i] = qpos[i];
}
spos[i++] = 0;
for (; i < rank; i++) {
spos[i] = qpos[i - 1];
}
final SummaryStatistics stats = new SummaryStatistics();
//sum of logs is slow and we dont use it, so blocking its calculation here
stats.setSumLogImpl(new NullStorelessUnivariateStatistic());
double amax = Double.NEGATIVE_INFINITY;
double amin = Double.POSITIVE_INFINITY;
boolean hasNaNs = false;
if (ignoreNaNs) {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val)) {
hasNaNs = true;
continue;
} else if (ignoreInfs && Double.isInfinite(val)) {
continue;
}
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
stats.addValue(val);
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (hasNaNs) {
if (!Double.isNaN(val))
stats.addValue(0);
continue;
}
if (Double.isNaN(val)) {
amax = Double.NaN;
amin = Double.NaN;
hasNaNs = true;
} else if (ignoreInfs && Double.isInfinite(val)) {
continue;
} else {
if (val > amax) {
amax = val;
}
if (val < amin) {
amin = val;
}
}
stats.addValue(val);
}
}
count.setAbs(qiter.index, (int) stats.getN());
max.setObjectAbs(qiter.index, amax);
min.setObjectAbs(qiter.index, amin);
boolean fmax = false;
boolean fmin = false;
if (hasNaNs) {
if (ignoreNaNs) {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val))
continue;
if (!fmax && val == amax) {
maxIndex.setAbs(qiter.index, j);
fmax = true;
if (fmin)
break;
}
if (!fmin && val == amin) {
minIndex.setAbs(qiter.index, j);
fmin = true;
if (fmax)
break;
}
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (Double.isNaN(val)) {
maxIndex.setAbs(qiter.index, j);
minIndex.setAbs(qiter.index, j);
break;
}
}
}
} else {
for (int j = 0; j < alen; j++) {
spos[axis] = j;
final double val = getDouble(spos);
if (!fmax && val == amax) {
maxIndex.setAbs(qiter.index, j);
fmax = true;
if (fmin)
break;
}
if (!fmin && val == amin) {
minIndex.setAbs(qiter.index, j);
fmin = true;
if (fmax)
break;
}
}
}
sum.setObjectAbs(qiter.index, stats.getSum());
mean.setAbs(qiter.index, stats.getMean());
var.setAbs(qiter.index, stats.getVariance());
}
setStoredValue(storeName(ignoreNaNs, ignoreInfs, STORE_COUNT + "-" + axis), count);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX + "-" + axis), max);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN + "-" + axis), min);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_SUM + "-" + axis), sum);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MEAN + "-" + axis), mean);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_VAR + "-" + axis), var);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MAX + STORE_INDEX + "-" + axis), maxIndex);
storedValues.put(storeName(ignoreNaNs, ignoreInfs, STORE_MIN + STORE_INDEX + "-" + axis), minIndex);
}
/**
* @param x
* @return number from given double
*/
abstract protected Number fromDoubleToNumber(double x);
// return biggest native primitive if integer (should test for 64bit?)
private static Number fromDoubleToBiggestNumber(double x, int dtype) {
switch (dtype) {
case BOOL:
case INT8:
case INT16:
case INT32:
return Integer.valueOf((int) (long) x);
case INT64:
return Long.valueOf((long) x);
case FLOAT32:
return Float.valueOf((float) x);
case FLOAT64:
return Double.valueOf(x);
}
return null;
}
private SummaryStatistics getStatistics(boolean ignoreNaNs) {
boolean ignoreInfs = false; // TODO
if (!hasFloatingPointElements()) {
ignoreNaNs = false;
}
String n = storeName(ignoreNaNs, ignoreInfs, STORE_STATS);
SummaryStatistics stats = (SummaryStatistics) getStoredValue(n);
if (stats == null) {
calculateSummaryStats(ignoreNaNs, ignoreInfs, n);
stats = (SummaryStatistics) getStoredValue(n);
}
return stats;
}
@Override
public int[] maxPos() {
return maxPos(false);
}
@Override
public int[] minPos() {
return minPos(false);
}
private int getHash() {
Object value = getStoredValue(STORE_HASH);
if (value == null) {
value = getStoredValue(STORE_SHAPELESS_HASH);
if (value == null) {
calculateMaxMin(false, false);
value = getStoredValue(STORE_SHAPELESS_HASH);
}
int ihash = (Integer) value;
int rank = shape.length;
for (int i = 0; i < rank; i++) {
ihash = ihash * 17 + shape[i];
}
storedValues.put(STORE_HASH, ihash);
return ihash;
}
return (Integer) value;
}
protected Object getMaxMin(boolean ignoreNaNs, boolean ignoreInfs, String key) {
if (!hasFloatingPointElements()) {
ignoreNaNs = false;
ignoreInfs = false;
}
key = storeName(ignoreNaNs, ignoreInfs , key);
Object value = getStoredValue(key);
if (value == null) {
calculateMaxMin(ignoreNaNs, ignoreInfs);
value = getStoredValue(key);
}
return value;
}
private Object getStatistics(boolean ignoreNaNs, int axis, String stat) {
if (!hasFloatingPointElements())
ignoreNaNs = false;
boolean ignoreInfs = false; // TODO
stat = storeName(ignoreNaNs, ignoreInfs , stat);
axis = checkAxis(axis);
Object obj = getStoredValue(stat);
if (obj == null) {
calculateSummaryStats(ignoreNaNs, ignoreInfs, axis);
obj = getStoredValue(stat);
}
return obj;
}
@Override
public Number max(boolean... ignoreInvalids) {
boolean igNan = ignoreInvalids!=null && ignoreInvalids.length>0 ? ignoreInvalids[0] : false;
boolean igInf = ignoreInvalids!=null && ignoreInvalids.length>1 ? ignoreInvalids[1] : igNan;
return (Number) getMaxMin(igNan, igInf, STORE_MAX);
}
@Override
public Number positiveMax(boolean ignoreInvalids) {
return (Number) getMaxMin(ignoreInvalids, ignoreInvalids, STORE_POS_MAX);
}
@Override
public Number positiveMax(boolean ignoreNaNs, boolean ignoreInfs) {
return (Number) getMaxMin(ignoreNaNs, ignoreInfs, STORE_POS_MAX);
}
@Override
public Dataset max(int axis) {
return max(false, axis);
}
@Override
public Dataset max(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MAX + "-" + axis);
}
@Override
public Number min(boolean... ignoreInvalids) {
boolean igNan = ignoreInvalids!=null && ignoreInvalids.length>0 ? ignoreInvalids[0] : false;
boolean igInf = ignoreInvalids!=null && ignoreInvalids.length>1 ? ignoreInvalids[1] : igNan;
return (Number) getMaxMin(igNan, igInf, STORE_MIN);
}
@Override
public Number positiveMin(boolean ignoreInvalids) {
return (Number) getMaxMin(ignoreInvalids, ignoreInvalids, STORE_POS_MIN);
}
@Override
public Number positiveMin(boolean ignoreNaNs, boolean ignoreInfs) {
return (Number) getMaxMin(ignoreNaNs, ignoreInfs, STORE_POS_MIN);
}
@Override
public Dataset min(int axis) {
return min(false, axis);
}
@Override
public Dataset min(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MIN + "-" + axis);
}
@Override
public int argMax() {
return argMax(false);
}
@Override
public int argMax(boolean ignoreInvalids) {
return getFlat1DIndex(maxPos(ignoreInvalids));
}
@Override
public IntegerDataset argMax(int axis) {
return argMax(false, axis);
}
@Override
public IntegerDataset argMax(boolean ignoreNaNs, int axis) {
return (IntegerDataset) getStatistics(ignoreNaNs, axis, STORE_MAX + STORE_INDEX + "-" + axis);
}
@Override
public int argMin() {
return argMin(false);
}
@Override
public int argMin(boolean ignoreInvalids) {
return getFlat1DIndex(minPos(ignoreInvalids));
}
@Override
public IntegerDataset argMin(int axis) {
return argMin(false, axis);
}
@Override
public IntegerDataset argMin(boolean ignoreNaNs, int axis) {
return (IntegerDataset) getStatistics(ignoreNaNs, axis, STORE_MIN + STORE_INDEX + "-" + axis);
}
@Override
public Number peakToPeak() {
return fromDoubleToNumber(max().doubleValue() - min().doubleValue());
}
@Override
public Dataset peakToPeak(int axis) {
return Maths.subtract(max(axis), min(axis));
}
@Override
public long count() {
return count(false);
}
@Override
public long count(boolean ignoreNaNs) {
return getStatistics(ignoreNaNs).getN();
}
@Override
public Dataset count(int axis) {
return count(false, axis);
}
@Override
public Dataset count(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_COUNT + "-" + axis);
}
@Override
public Object sum() {
return sum(false);
}
@Override
public Object sum(boolean ignoreNaNs) {
return getStatistics(ignoreNaNs).getSum();
}
@Override
public Dataset sum(int axis) {
return sum(false, axis);
}
@Override
public Dataset sum(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_SUM + "-" + axis);
}
@Override
public Object typedSum() {
return typedSum(getDtype());
}
@Override
public Object typedSum(int dtype) {
return fromDoubleToBiggestNumber(getStatistics(false).getSum(), dtype);
}
@Override
public Dataset typedSum(int dtype, int axis) {
return DatasetUtils.cast(sum(axis), dtype);
}
@Override
public Object product() {
return Stats.product(this);
}
@Override
public Dataset product(int axis) {
return Stats.product(this, axis);
}
@Override
public Object typedProduct(int dtype) {
return Stats.typedProduct(this, dtype);
}
@Override
public Dataset typedProduct(int dtype, int axis) {
return Stats.typedProduct(this, dtype, axis);
}
@Override
public Object mean(boolean... ignoreNaNs) {
boolean ig = ignoreNaNs!=null && ignoreNaNs.length>0 ? ignoreNaNs[0] : false;
return getStatistics(ig).getMean();
}
@Override
public Dataset mean(int axis) {
return mean(false, axis);
}
@Override
public Dataset mean(boolean ignoreNaNs, int axis) {
return (Dataset) getStatistics(ignoreNaNs, axis, STORE_MEAN + "-" + axis);
}
@Override
public Number variance() {
return variance(false);
}
@Override
public Number variance(boolean isDatasetWholePopulation) {
SummaryStatistics stats = getStatistics(false);
if (isDatasetWholePopulation) {
Variance newVar = (Variance) stats.getVarianceImpl().copy();
newVar.setBiasCorrected(false);
return newVar.getResult();
}
return stats.getVariance();
}
@Override
public Dataset variance(int axis) {
return (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
}
@Override
public Number stdDeviation() {
return Math.sqrt(variance().doubleValue());
}
@Override
public Number stdDeviation(boolean isDatasetWholePopulation) {
return Math.sqrt(variance(isDatasetWholePopulation).doubleValue());
}
@Override
public Dataset stdDeviation(int axis) {
final Dataset v = (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
return Maths.sqrt(v);
}
@Override
public Number rootMeanSquare() {
final SummaryStatistics stats = getStatistics(false);
final double mean = stats.getMean();
return Math.sqrt(stats.getVariance() + mean * mean);
}
@Override
public Dataset rootMeanSquare(int axis) {
Dataset v = (Dataset) getStatistics(false, axis, STORE_VAR + "-" + axis);
Dataset m = (Dataset) getStatistics(false, axis, STORE_MEAN + "-" + axis);
Dataset result = Maths.power(m, 2);
return Maths.sqrt(result.iadd(v));
}
/**
* Set item from compatible dataset in a direct and speedy way. Remember to setDirty afterwards.
*
* @param dindex
* @param sindex
* @param src
* is the source data buffer
*/
protected abstract void setItemDirect(final int dindex, final int sindex, final Object src);
@Override
public boolean hasErrors() {
return super.getError() != null;
}
protected Dataset getInternalError() {
ILazyDataset led = super.getError();
if (led == null)
return null;
Dataset ed = DatasetUtils.sliceAndConvertLazyDataset(led);
if (!(led instanceof Dataset)) {
setError(ed); // set back
}
// check for broadcast strides
Object bs = getStoredValue(STORE_BROADCAST);
if (bs == null) {
bs = new BroadcastStride(ed, shape);
setStoredValue(STORE_BROADCAST, bs);
}
return ed;
}
class BroadcastStride {
private int[] bStride;
private int[] nShape;
private int bOffset;
public BroadcastStride(Dataset d, final int[] newShape) {
d.setShape(BroadcastIterator.padShape(d.getShapeRef(), newShape.length - d.getRank())); // set to padded shape
bStride = createBroadcastStrides(d, newShape);
nShape = newShape.clone();
bOffset = d.getOffset();
}
public int get1DIndex(int i) {
if (i < 0) {
i += nShape[0];
}
if (i < 0 || i >= nShape[0]) {
throwAIOOBException(i, nShape[0], 0);
}
return i*bStride[0] + bOffset;
}
protected int get1DIndex(int i, int j) {
if (i < 0) {
i += nShape[0];
}
if (i < 0 || i >= nShape[0]) {
throwAIOOBException(i, nShape[0], 0);
}
if (j < 0) {
j += nShape[1];
}
if (j < 0 || j >= nShape[1]) {
throwAIOOBException(i, nShape[1], 1);
}
return i*bStride[0] + j*bStride[1] + bOffset;
}
protected int get1DIndex(int... n) {
return get1DIndexFromStrides(nShape, bStride, bOffset, n);
}
}
@Override
public Dataset getError() {
Dataset ed = getInternalError();
if (ed == null)
return null;
if (ed.getSize() != getSize()) {
DoubleDataset errors = new DoubleDataset(shape);
errors.setSlice(ed);
return errors;
}
return ed;
}
@Override
public double getError(final int i) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(i));
}
@Override
public double getError(final int i, final int j) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(i, j));
}
@Override
public double getError(int... pos) {
Dataset ed = getInternalError();
if (ed == null)
return 0;
BroadcastStride bs = (BroadcastStride) getStoredValue(STORE_BROADCAST);
return ed.getElementDoubleAbs(bs.get1DIndex(pos));
}
@Override
public double[] getErrorArray(final int i) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(i)};
}
@Override
public double[] getErrorArray(final int i, final int j) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(i, j)};
}
@Override
public double[] getErrorArray(int... pos) {
Dataset ed = getInternalError();
if (ed == null)
return null;
return new double[] {getError(pos)};
}
protected Dataset getInternalSquaredError() {
Dataset sed = getErrorBuffer();
// check for broadcast strides
Object bs = getStoredValue(STORE_BROADCAST);
if (bs == null) {
bs = new BroadcastStride(sed, shape);
setStoredValue(STORE_BROADCAST, bs);
}
return sed;
}
@Override
public Dataset getErrorBuffer() {
ErrorMetadata emd = getErrorMetadata();
if (emd == null)
return null;
if (!(emd instanceof ErrorMetadataImpl)) {
ILazyDataset led = emd.getError();
Dataset ed = DatasetUtils.sliceAndConvertLazyDataset(led);
emd = new ErrorMetadataImpl();
setMetadata(emd);
((ErrorMetadataImpl) emd).setError(ed);
}
return ((ErrorMetadataImpl) emd).getSquaredError();
}
@Override
public void setError(Serializable errors) {
super.setError(errors);
Object bs = getStoredValue(STORE_BROADCAST);
if (bs != null) {
setStoredValue(STORE_BROADCAST, null);
}
}
/**
* Set a copy of the buffer that backs the (squared) error data
* @param buffer can be null, anything that can be used to create a DoubleDataset or CompoundDoubleDataset
*/
@Override
public void setErrorBuffer(Serializable buffer) {
Object bs = getStoredValue(STORE_BROADCAST);
if (bs != null) {
setStoredValue(STORE_BROADCAST, null);
}
if (buffer == null) {
clearMetadata(ErrorMetadata.class);
return;
}
IDataset d = (IDataset) createFromSerializable(buffer, false);
ErrorMetadata emd = getErrorMetadata();
if (!(emd instanceof ErrorMetadataImpl)) {
emd = new ErrorMetadataImpl();
setMetadata(emd);
}
((ErrorMetadataImpl) emd).setSquaredError(d);
}
}
|
package sk.henrichg.phoneprofilesplus;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;
import com.google.gson.Gson;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
public class BluetoothConnectionBroadcastReceiver extends WakefulBroadcastReceiver {
public static final String BROADCAST_RECEIVER_TYPE = "bluetoothConnection";
private static List<BluetoothDeviceData> connectedDevices = null;
@Override
public void onReceive(Context context, Intent intent) {
//Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler());
PPApplication.logE("
Context appContext = context.getApplicationContext();
getConnectedDevices(context);
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED) ||
action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED) ||
action.equals(BluetoothDevice.ACTION_NAME_CHANGED)/* ||
action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)*/) {
boolean connected = action.equals(BluetoothDevice.ACTION_ACL_CONNECTED);
try {
if (!action.equals(BluetoothDevice.ACTION_NAME_CHANGED)) {
PPApplication.logE("BluetoothConnectionBroadcastReceiver.onReceive", "connected=" + connected);
PPApplication.logE("BluetoothConnectionBroadcastReceiver.onReceive", "device.getName()=" + device.getName());
PPApplication.logE("BluetoothConnectionBroadcastReceiver.onReceive", "device.getAddress()=" + device.getAddress());
}
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED))
addConnectedDevice(device);
else if (action.equals(BluetoothDevice.ACTION_NAME_CHANGED)) {
String deviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
if (deviceName != null)
changeDeviceName(device, deviceName);
} else
removeConnectedDevice(device);
} catch (Exception ignored) {}
saveConnectedDevices(appContext);
if (!PPApplication.getApplicationStarted(appContext, true))
// application is not started
return;
//PPApplication.loadPreferences(appContext);
/*SharedPreferences preferences = appContext.getSharedPreferences(PPApplication.APPLICATION_PREFS_NAME, Context.MODE_PRIVATE);
int lastState = preferences.getInt(PPApplication.PREF_EVENT_BLUETOOTH_LAST_STATE, -1);
int currState = -1;
if (connected)
currState = 1;
if (!connected)
currState = 0;
Editor editor = preferences.edit();
editor.putInt(PPApplication.PREF_EVENT_BLUETOOTH_LAST_STATE, currState);
editor.commit();*/
if (Event.getGlobalEventsRuning(appContext)) {
//if (lastState != currState)
PPApplication.logE("@@@ BluetoothConnectionBroadcastReceiver.onReceive", "connected=" + connected);
if (!((BluetoothScanAlarmBroadcastReceiver.getScanRequest(appContext)) ||
(BluetoothScanAlarmBroadcastReceiver.getLEScanRequest(appContext)) ||
(BluetoothScanAlarmBroadcastReceiver.getWaitForResults(appContext)) ||
(BluetoothScanAlarmBroadcastReceiver.getWaitForLEResults(appContext)) ||
(BluetoothScanAlarmBroadcastReceiver.getBluetoothEnabledForScan(appContext)))) {
// bluetooth is not scanned
/*DataWrapper dataWrapper = new DataWrapper(appContext, false, false, 0);
boolean bluetoothEventsExists = dataWrapper.getDatabaseHandler().getTypeEventsCount(DatabaseHandler.ETYPE_BLUETOOTHCONNECTED) > 0;
dataWrapper.invalidateDataWrapper();
if (bluetoothEventsExists)
{
PPApplication.logE("@@@ BluetoothConnectionBroadcastReceiver.onReceive","bluetoothEventsExists="+bluetoothEventsExists);
*/
// start service
Intent eventsServiceIntent = new Intent(appContext, EventsService.class);
eventsServiceIntent.putExtra(EventsService.EXTRA_BROADCAST_RECEIVER_TYPE, BROADCAST_RECEIVER_TYPE);
startWakefulService(appContext, eventsServiceIntent);
}
}
//if ((!connected) && (lastState != currState))
/*if (!connected)
{
BluetoothScanAlarmBroadcastReceiver.stopScan(appContext);
}*/
}
}
}
private static final String CONNECTED_DEVICES_COUNT_PREF = "count";
private static final String CONNECTED_DEVICES_DEVICE_PREF = "device";
private static void getConnectedDevices(Context context)
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
if (connectedDevices == null)
connectedDevices = new ArrayList<>();
connectedDevices.clear();
SharedPreferences preferences = context.getSharedPreferences(PPApplication.BLUETOOTH_CONNECTED_DEVICES_PREFS_NAME, Context.MODE_PRIVATE);
int count = preferences.getInt(CONNECTED_DEVICES_COUNT_PREF, 0);
Gson gson = new Gson();
int gmtOffset = TimeZone.getDefault().getRawOffset();
for (int i = 0; i < count; i++) {
String json = preferences.getString(CONNECTED_DEVICES_DEVICE_PREF + i, "");
if (!json.isEmpty()) {
BluetoothDeviceData device = gson.fromJson(json, BluetoothDeviceData.class);
@SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices","device.name="+device.name);
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "device.timestamp="+sdf.format(device.timestamp));
long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime() - gmtOffset;
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "bootTime="+sdf.format(bootTime));
if (device.timestamp >= bootTime) {
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "added");
connectedDevices.add(device);
}
else
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "not added");
}
}
PPApplication.logE("BluetoothConnectionBroadcastReceiver.getConnectedDevices", "connectedDevices.size()=" + connectedDevices.size());
}
}
static void saveConnectedDevices(Context context)
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
if (connectedDevices == null)
connectedDevices = new ArrayList<>();
SharedPreferences preferences = context.getSharedPreferences(PPApplication.BLUETOOTH_CONNECTED_DEVICES_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putInt(CONNECTED_DEVICES_COUNT_PREF, connectedDevices.size());
Gson gson = new Gson();
for (int i = 0; i < connectedDevices.size(); i++) {
String json = gson.toJson(connectedDevices.get(i));
editor.putString(CONNECTED_DEVICES_DEVICE_PREF + i, json);
}
editor.apply();
}
}
private void addConnectedDevice(BluetoothDevice device)
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
boolean found = false;
for (BluetoothDeviceData _device : connectedDevices) {
if (_device.address.equals(device.getAddress())) {
found = true;
break;
}
}
if (!found) {
int gmtOffset = TimeZone.getDefault().getRawOffset();
Calendar now = Calendar.getInstance();
long timestamp = now.getTimeInMillis() - gmtOffset;
connectedDevices.add(new BluetoothDeviceData(device.getName(), device.getAddress(),
BluetoothScanAlarmBroadcastReceiver.getBluetoothType(device), false, timestamp));
}
}
}
private void removeConnectedDevice(BluetoothDevice device)
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
int index = 0;
boolean found = false;
for (BluetoothDeviceData _device : connectedDevices) {
if (_device.address.equals(device.getAddress())) {
found = true;
break;
}
++index;
}
if (found)
connectedDevices.remove(index);
}
}
static void clearConnectedDevices(Context context, boolean onlyOld)
{
PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices","onlyOld="+onlyOld);
if (onlyOld) {
getConnectedDevices(context);
}
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
if (connectedDevices != null) {
if (onlyOld) {
int gmtOffset = TimeZone.getDefault().getRawOffset();
for (BluetoothDeviceData device : connectedDevices) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S");
PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices","device.name="+device.name);
PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices", "device.timestamp="+sdf.format(device.timestamp));
long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime() - gmtOffset;
PPApplication.logE("BluetoothConnectionBroadcastReceiver.clearConnectedDevices", "bootTime="+sdf.format(bootTime));
if (device.timestamp < bootTime)
connectedDevices.remove(device);
}
}
else
connectedDevices.clear();
}
}
}
private void changeDeviceName(BluetoothDevice device, String deviceName)
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
for (BluetoothDeviceData _device : connectedDevices) {
if (_device.address.equals(device.getAddress()) && !deviceName.isEmpty()) {
_device.setName(deviceName);
break;
}
}
}
}
public static boolean isBluetoothConnected(Context context, String adapterName)
{
getConnectedDevices(context);
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
if (adapterName.isEmpty())
return (connectedDevices != null) && (connectedDevices.size() > 0);
else {
if (connectedDevices != null) {
for (BluetoothDeviceData _device : connectedDevices) {
String device = _device.getName().toUpperCase();
String _adapterName = adapterName.toUpperCase();
if (Wildcard.match(device, _adapterName, '_', '%', true)) {
return true;
}
}
}
return false;
}
}
}
/*
public static boolean isAdapterNameScanned(DataWrapper dataWrapper, int connectionType)
{
if (isBluetoothConnected(dataWrapper.context, ""))
{
synchronized (PPApplication.bluetoothConnectionChangeStateMutex) {
if (connectedDevices != null) {
for (BluetoothDeviceData _device : connectedDevices) {
if (dataWrapper.getDatabaseHandler().isBluetoothAdapterNameScanned(_device.getName(), connectionType))
return true;
}
}
return false;
}
}
else
return false;
}
*/
}
|
package ua.com.fielden.platform.web.security;
import static java.lang.String.format;
import static ua.com.fielden.platform.security.session.Authenticator.fromString;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Cookie;
import org.restlet.data.CookieSetting;
import org.restlet.security.ChallengeAuthenticator;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import ua.com.fielden.platform.security.session.Authenticator;
import ua.com.fielden.platform.security.session.IUserSession;
import ua.com.fielden.platform.security.session.UserSession;
import ua.com.fielden.platform.security.user.IUser;
import ua.com.fielden.platform.security.user.IUserProvider;
import ua.com.fielden.platform.security.user.User;
import ua.com.fielden.platform.utils.IUniversalConstants;
/**
* This is a guard that is based on the new TG authentication scheme, developed as part of the Web UI initiative. It it used to restrict access to sensitive web resources.
* <p>
* This type is abstract. The only part that is abstract in it, is the way for obtaining current user. Applications and unit test may need to have different ways for determining
* current users. Method {@link #getUser()} needs to be implemented to provide a currently logged in user.
*
* @author TG Team
*
*/
public abstract class AbstractWebResourceGuard extends ChallengeAuthenticator {
private final Logger logger = Logger.getLogger(getClass());
public static final String AUTHENTICATOR_COOKIE_NAME = "authenticator";
protected final Injector injector;
private final IUniversalConstants constants;
private final String domainName;
private final String path;
public AbstractWebResourceGuard(final Context context, final String domainName, final String path, final Injector injector) throws IllegalArgumentException {
super(context, ChallengeScheme.CUSTOM, "TG");
if (injector == null) {
throw new IllegalArgumentException("Injector is required.");
}
this.injector = injector;
this.constants = injector.getInstance(IUniversalConstants.class);
this.domainName = domainName;
this.path = path;
if (StringUtils.isEmpty(domainName) || StringUtils.isEmpty(path)) {
throw new IllegalStateException("Both the domain name and the applicatin binding path should be provided.");
}
setRechallenging(false);
}
@Override
public boolean authenticate(final Request request, final Response response) {
if(true) {
final IUserProvider userProvider = injector.getInstance(IUserProvider.class);
userProvider.setUsername(User.system_users.SU.name(), injector.getInstance(IUser.class));
return true;
}
try {
logger.debug(format("Starting request authentication to a resource at URI %s (%s, %s, %s)", request.getResourceRef(), request.getClientInfo().getAddress(), request.getClientInfo().getAgentName(), request.getClientInfo().getAgentVersion()));
final Optional<Authenticator> oAuth = extractAuthenticator(request);
if (!oAuth.isPresent()) {
logger.warn(format("Authenticator cookie is missing for a request to a resource at URI %s (%s, %s, %s)", request.getResourceRef(), request.getClientInfo().getAddress(), request.getClientInfo().getAgentName(), request.getClientInfo().getAgentVersion()));
forbid(response);
return false;
}
// authenticator is present
final Authenticator auth = oAuth.get();
// let's validate the authenticator
final IUserSession coUserSession = injector.getInstance(IUserSession.class);
final Optional<UserSession> session = coUserSession.currentSession(getUser(auth.username), auth.toString());
if (!session.isPresent()) {
logger.warn(format("Authenticator validation failed for a request to a resource at URI %s (%s, %s, %s)", request.getResourceRef(), request.getClientInfo().getAddress(), request.getClientInfo().getAgentName(), request.getClientInfo().getAgentVersion()));
// TODO this is an interesting approach to prevent any further processing of the request, this event prevents receiving it completely
// useful to prevent unauthorised file uploads
// However, the client side would not be able to receive a response.
//request.abort();
forbid(response);
return false;
}
// at this stage it is safe to record the fact of successful resource access for later analysis of resources being accessed and
// to count concurrent users ... it would be wise to use some key/value database for this instead of the underlying RDBMS
// TODO #236 implement logging of accessed by users resources... potentially a custom log4j appender could be created for this purpose
// the provided authenticator was valid and a new cookie should be send back to the client
assignAuthenticatingCookie(constants.now(), session.get().getAuthenticator().get(), domainName, path, request, response);
} catch (final Exception ex) {
// in case of any internal exception forbid the request
forbid(response);
logger.fatal(ex);
return false;
}
return true;
}
/**
* Extracts the latest user authenticator from the provided request.
* Returns an empty result in case no authenticating cookies was identified.
*
* @param request
* @return
*/
public static Optional<Authenticator> extractAuthenticator(final Request request) {
// first collect non-empty authenticating cookies
final List<Cookie> cookies = request.getCookies().stream()
.filter(c -> AUTHENTICATOR_COOKIE_NAME.equals(c.getName()) && !StringUtils.isEmpty(c.getValue()))
.collect(Collectors.toList());
// if there are no authenticating cookies then return an empty result
if (cookies.isEmpty()) {
return Optional.empty();
}
// convert authenticating cookies to authenticators and sort them by expiry date oldest first...
final List<Authenticator> authenticators = cookies.stream()
.map(c -> fromString(c.getValue()))
.sorted((auth1, auth2) -> auth1.getExpiryTime().compareTo(auth2.getExpiryTime()))
.collect(Collectors.toList());
// ...and get the most recent authenticator...
final Authenticator auth = Iterables.getLast(authenticators);
return Optional.of(auth);
}
/**
* A convenient method that creates an authenticating cookie based on the provided authenticator and associates it with the specified HTTP response.
*
* @param authenticator
* @param response
*/
public static void assignAuthenticatingCookie(final DateTime now, final Authenticator authenticator, final String domainName, final String path, final Request request, final Response response) {
// create a cookie that will carry an updated authenticator back to the client for further use
// it is important to note that the time that will be used by further processing of this request is not known
// and thus is not factored in for session authentication time frame
// this means that if the processing time exceeds the session expiration time then the next request after this would render invalid, requiring explicit authentication
// on the one hand this is potentially limiting for untrusted devices, but for trusted devices this should not a problem
// on the other hand, it might server as an additional security level, limiting computationally intensive requests being send from untrusted devices
// calculate maximum cookie age in seconds
final int maxAge = (int) (authenticator.expiryTime - now.getMillis()) / 1000;
if (maxAge <= 0) {
throw new IllegalStateException("What the hack is goinig on! maxAge for cookier is not > zero.");
}
final CookieSetting newCookie = new CookieSetting(
0 /*version*/,
AUTHENTICATOR_COOKIE_NAME /*name*/,
authenticator.toString() /*value*/,
path /*path*/,
domainName /*domain*/,
null /*comment*/,
maxAge /* number of seconds before cookie expires */,
true /*secure*/, // if secure is set to true then this cookie would only be included into the request if it is done over HTTPS!
true /*accessRestricted*/);
// finally associate the refreshed authenticator with the response
response.getCookieSettings().clear();
response.getCookieSettings().add(newCookie);
}
/**
* Should be implemented in accordance with requirements for obtaining the current user by name.
*
* @return
*/
protected abstract User getUser(final String username);
}
|
package com.redhat.ceylon.eclipse.code.refactor;
import static com.redhat.ceylon.eclipse.code.correct.ImportProposals.applyImports;
import static com.redhat.ceylon.eclipse.code.correct.ImportProposals.importDeclaration;
import static com.redhat.ceylon.eclipse.code.parse.CeylonSourcePositionLocator.getTokenIndexAtCharacter;
import static com.redhat.ceylon.eclipse.code.resolve.CeylonReferenceResolver.getReferencedDeclaration;
import static org.eclipse.ltk.core.refactoring.RefactoringStatus.createFatalErrorStatus;
import static org.eclipse.ltk.core.refactoring.RefactoringStatus.createWarningStatus;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.Token;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.DocumentChange;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.text.edits.DeleteEdit;
import org.eclipse.text.edits.InsertEdit;
import org.eclipse.text.edits.MultiTextEdit;
import org.eclipse.text.edits.ReplaceEdit;
import org.eclipse.ui.texteditor.ITextEditor;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration;
import com.redhat.ceylon.compiler.typechecker.parser.CeylonLexer;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.compiler.typechecker.tree.Visitor;
import com.redhat.ceylon.eclipse.core.builder.CeylonBuilder;
import com.redhat.ceylon.eclipse.util.FindDeclarationNodeVisitor;
import com.redhat.ceylon.eclipse.util.FindReferenceVisitor;
public class InlineRefactoring extends AbstractRefactoring {
private final Declaration declaration;
private boolean delete = true;
public InlineRefactoring(ITextEditor editor) {
super(editor);
declaration = getReferencedDeclaration(node);
}
@Override
boolean isEnabled() {
return declaration!=null &&
project != null &&
inSameProject(declaration) &&
declaration instanceof MethodOrValue &&
!declaration.isParameter() &&
!(declaration instanceof Setter) &&
!declaration.isDefault() &&
!declaration.isFormal() &&
(((MethodOrValue)declaration).getTypeDeclaration()!=null) &&
(!((MethodOrValue)declaration).getTypeDeclaration().isAnonymous()) &&
(declaration.isToplevel() || !declaration.isShared()); //TODO temporary restriction!
//TODO: && !declaration is a control structure variable
//TODO: && !declaration is a value with lazy init
}
public int getCount() {
return declaration==null ? 0 : countDeclarationOccurrences();
}
@Override
int countReferences(Tree.CompilationUnit cu) {
FindReferenceVisitor frv = new FindReferenceVisitor(declaration);
cu.visit(frv);
return frv.getNodes().size();
}
public String getName() {
return "Inline";
}
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
final RefactoringStatus result = new RefactoringStatus();
Tree.Declaration declarationNode=null;
Tree.CompilationUnit declarationUnit=null;
if (searchInEditor()) {
Tree.CompilationUnit cu = editor.getParseController().getRootNode();
if (cu.getUnit().equals(declaration.getUnit())) {
declarationUnit = cu;
}
}
if (declarationUnit==null) {
for (final PhasedUnit pu: CeylonBuilder.getUnits(project)) {
if (pu.getUnit().equals(declaration.getUnit())) {
declarationUnit = pu.getCompilationUnit();
break;
}
}
}
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(declaration);
declarationUnit.visit(fdv);
declarationNode = fdv.getDeclarationNode();
if (declarationNode instanceof Tree.AttributeDeclaration &&
((Tree.AttributeDeclaration) declarationNode).getSpecifierOrInitializerExpression()==null ||
declarationNode instanceof Tree.MethodDeclaration &&
((Tree.MethodDeclaration) declarationNode).getSpecifierExpression()==null) {
return createFatalErrorStatus("Cannot inline forward declaration: " +
declaration.getName());
}
if (declarationNode instanceof Tree.MethodDefinition &&
((Tree.MethodDefinition) declarationNode).getBlock().getStatements().size()!=1 ||
declarationNode instanceof Tree.AttributeGetterDefinition &&
((Tree.AttributeGetterDefinition) declarationNode).getBlock().getStatements().size()!=1) {
return createFatalErrorStatus("Cannot inline declaration with multiple statements: " +
declaration.getName());
}
if (declarationNode instanceof Tree.AnyAttribute &&
((Tree.AnyAttribute) declarationNode).getDeclarationModel().isVariable()) {
result.merge(createWarningStatus("Inlined value is variable"));
}
declarationNode.visit(new Visitor() {
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
super.visit(that);
if (that.getDeclaration()==null) {
result.merge(createWarningStatus("Definition contains unresolved reference"));
}
else if (declaration.isShared() &&
!that.getDeclaration().isShared()) {
result.merge(createWarningStatus("Definition contains reference to unshared declaration: " +
that.getDeclaration().getName()));
}
}
});
return result;
}
public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
return new RefactoringStatus();
}
public Change createChange(IProgressMonitor pm) throws CoreException,
OperationCanceledException {
Tree.Declaration declarationNode=null;
Tree.CompilationUnit declarationUnit=null;
Tree.Term term = null;
List<CommonToken> declarationTokens = null;
Tree.CompilationUnit editorRootNode = editor.getParseController().getRootNode();
List<CommonToken> editorTokens = editor.getParseController().getTokens();
if (declaration!=null) {
if (searchInEditor()) {
Tree.CompilationUnit cu = editorRootNode;
if (cu.getUnit().equals(declaration.getUnit())) {
declarationUnit = cu;
declarationTokens = editorTokens;
}
}
if (declarationUnit==null) {
for (final PhasedUnit pu: getAllUnits()) {
if (pu.getUnit().equals(declaration.getUnit())) {
declarationUnit = pu.getCompilationUnit();
declarationTokens = pu.getTokens();
break;
}
}
}
FindDeclarationNodeVisitor fdv = new FindDeclarationNodeVisitor(declaration);
declarationUnit.visit(fdv);
declarationNode = fdv.getDeclarationNode();
term = getInlinedTerm(declarationNode);
}
CompositeChange cc = new CompositeChange(getName());
if (declarationNode!=null) {
for (PhasedUnit pu: getAllUnits()) {
if (searchInFile(pu)) {
TextFileChange tfc = newTextFileChange(pu);
Tree.CompilationUnit cu = pu.getCompilationUnit();
inlineInFile(tfc, cc, declarationNode,
declarationUnit, term, declarationTokens, cu,
pu.getTokens());
}
}
}
if (searchInEditor()) {
DocumentChange dc = newDocumentChange();
inlineInFile(dc, cc, declarationNode, declarationUnit,
term, declarationTokens,
editorRootNode, editorTokens);
}
return cc;
}
private boolean addImports(final TextChange change,
final Tree.Declaration declarationNode,
final Tree.CompilationUnit cu) {
final Package decPack = declarationNode.getUnit().getPackage();
final Package filePack = cu.getUnit().getPackage();
final class AddImportsVisitor extends Visitor {
private final Set<Declaration> already;
boolean importedFromDeclarationPackage;
private AddImportsVisitor(Set<Declaration> already) {
this.already = already;
}
@Override
public void visit(Tree.BaseMemberOrTypeExpression that) {
super.visit(that);
if (that.getDeclaration()!=null) {
importDeclaration(already, that.getDeclaration(), cu);
Package refPack = that.getDeclaration().getUnit().getPackage();
importedFromDeclarationPackage = importedFromDeclarationPackage ||
//result!=0 &&
refPack.equals(decPack) &&
!decPack.equals(filePack); //unnecessary
}
}
}
final Set<Declaration> already = new HashSet<Declaration>();
AddImportsVisitor aiv = new AddImportsVisitor(already);
declarationNode.visit(aiv);
applyImports(change, already,
declarationNode.getDeclarationModel(), cu, document);
return aiv.importedFromDeclarationPackage;
}
private void inlineInFile(TextChange tfc, CompositeChange cc,
Tree.Declaration declarationNode, Tree.CompilationUnit declarationUnit,
Tree.Term term, List<CommonToken> declarationTokens,
Tree.CompilationUnit cu, List<CommonToken> tokens) {
tfc.setEdit(new MultiTextEdit());
inlineReferences(declarationNode, declarationUnit, term, declarationTokens,
cu, tokens, tfc);
boolean inlined = tfc.getEdit().hasChildren();
deleteDeclaration(declarationNode, declarationUnit, cu, tokens, tfc);
boolean importsAddedToDeclarationPackage = false;
if (inlined) {
importsAddedToDeclarationPackage = addImports(tfc, declarationNode, cu);
}
deleteImports(tfc, declarationNode, cu, tokens, importsAddedToDeclarationPackage);
if (tfc.getEdit().hasChildren()) {
cc.add(tfc);
}
}
private void deleteImports(TextChange tfc, Tree.Declaration declarationNode,
Tree.CompilationUnit cu, List<CommonToken> tokens,
boolean importsAddedToDeclarationPackage) {
Tree.ImportList il = cu.getImportList();
if (il!=null) {
for (Tree.Import i: il.getImports()) {
List<Tree.ImportMemberOrType> list = i.getImportMemberOrTypeList()
.getImportMemberOrTypes();
for (Tree.ImportMemberOrType imt: list) {
Declaration d = imt.getDeclarationModel();
if (d!=null && d.equals(declarationNode.getDeclarationModel())) {
if (list.size()==1 && !importsAddedToDeclarationPackage) {
//delete the whole import statement
tfc.addEdit(new DeleteEdit(i.getStartIndex(),
i.getStopIndex()-i.getStartIndex()+1));
}
else {
//delete just the item in the import statement...
tfc.addEdit(new DeleteEdit(imt.getStartIndex(),
imt.getStopIndex()-imt.getStartIndex()+1));
//...along with a comma before or after
int ti = getTokenIndexAtCharacter(tokens, imt.getStartIndex());
CommonToken prev = tokens.get(ti-1);
if (prev.getChannel()==CommonToken.HIDDEN_CHANNEL) {
prev = tokens.get(ti-2);
}
CommonToken next = tokens.get(ti+1);
if (next.getChannel()==CommonToken.HIDDEN_CHANNEL) {
next = tokens.get(ti+2);
}
if (prev.getType()==CeylonLexer.COMMA) {
tfc.addEdit(new DeleteEdit(prev.getStartIndex(),
imt.getStartIndex()-prev.getStartIndex()));
}
else if (next.getType()==CeylonLexer.COMMA) {
tfc.addEdit(new DeleteEdit(imt.getStopIndex()+1,
next.getStopIndex()-imt.getStopIndex()));
}
}
}
}
}
}
}
private void deleteDeclaration(Tree.Declaration declarationNode,
Tree.CompilationUnit declarationUnit, Tree.CompilationUnit cu,
List<CommonToken> tokens, TextChange tfc) {
if (delete && cu.getUnit().equals(declarationUnit.getUnit())) {
CommonToken from = (CommonToken) declarationNode.getToken();
Tree.AnnotationList anns = declarationNode.getAnnotationList();
if (!anns.getAnnotations().isEmpty()) {
from = (CommonToken) anns.getAnnotations().get(0).getToken();
}
int prevIndex = from.getTokenIndex()-1;
if (prevIndex>=0) {
CommonToken tok = tokens.get(prevIndex);
if (tok.getChannel()==Token.HIDDEN_CHANNEL) {
from=tok;
}
}
tfc.addEdit(new DeleteEdit(from.getStartIndex(),
declarationNode.getStopIndex()-from.getStartIndex()+1));
}
}
private static Tree.Term getInlinedTerm(Tree.Declaration declarationNode) {
if (declarationNode!=null) {
if (declarationNode instanceof Tree.AttributeDeclaration) {
Tree.AttributeDeclaration att = (Tree.AttributeDeclaration) declarationNode;
return att.getSpecifierOrInitializerExpression().getExpression().getTerm();
}
else if (declarationNode instanceof Tree.MethodDefinition) {
Tree.MethodDefinition meth = (Tree.MethodDefinition) declarationNode;
if (meth.getBlock().getStatements().size()!=1) {
throw new RuntimeException("method has multiple statements");
}
if (meth.getType() instanceof Tree.VoidModifier) {
//TODO: in the case of a void method, tolerate
// multiple statements
Tree.ExpressionStatement e = (Tree.ExpressionStatement) meth.getBlock()
.getStatements().get(0);
return e.getExpression().getTerm();
}
else {
Tree.Return r = (Tree.Return) meth.getBlock().getStatements().get(0);
return r.getExpression().getTerm();
}
}
else if (declarationNode instanceof Tree.MethodDeclaration) {
Tree.MethodDeclaration meth = (Tree.MethodDeclaration) declarationNode;
return meth.getSpecifierExpression().getExpression().getTerm();
}
else if (declarationNode instanceof Tree.AttributeGetterDefinition) {
Tree.AttributeGetterDefinition att = (Tree.AttributeGetterDefinition) declarationNode;
if (att.getBlock().getStatements().size()!=1) {
throw new RuntimeException("getter has multiple statements");
}
Tree.Return r = (Tree.Return) att.getBlock().getStatements().get(0);
return r.getExpression().getTerm();
}
else {
throw new RuntimeException("not a value or function");
}
}
else {
return null;
}
}
private void inlineReferences(Tree.Declaration declarationNode,
Tree.CompilationUnit declarationUnit, Tree.Term term,
List<CommonToken> declarationTokens, Tree.CompilationUnit pu,
List<CommonToken> tokens, TextChange tfc) {
String template = toString(term, declarationTokens);
int templateStart = term.getStartIndex();
if (declarationNode instanceof Tree.AnyAttribute) {
inlineAttributeReferences(pu, template, tfc);
}
else if (declarationNode instanceof Tree.AnyMethod) {
inlineFunctionReferences(pu, tokens, term, template, templateStart, tfc);
}
}
private void inlineFunctionReferences(final Tree.CompilationUnit pu, final List<CommonToken> tokens,
final Tree.Term term, final String template, final int templateStart,
final TextChange tfc) {
new Visitor() {
@Override
public void visit(final Tree.InvocationExpression that) {
super.visit(that);
if (that.getPrimary() instanceof Tree.MemberOrTypeExpression) {
Tree.MemberOrTypeExpression mte = (Tree.MemberOrTypeExpression) that.getPrimary();
if (mte.getDeclaration().equals(declaration)) {
//TODO: breaks for invocations like f(f(x, y),z)
final StringBuilder result = new StringBuilder();
class InterpolateArgumentsVisitor extends Visitor {
int start = 0;
@Override
public void visit(Tree.BaseMemberExpression it) {
super.visit(it);
if (it.getDeclaration().isParameter()) {
Parameter param = ((MethodOrValue) it.getDeclaration()).getInitializerParameter();
if ( param.getDeclaration().equals(declaration) ) {
result.append(template.substring(start,it.getStartIndex()-templateStart));
start = it.getStopIndex()-templateStart+1;
boolean sequenced = param.isSequenced();
if (that.getPositionalArgumentList()!=null) {
interpolatePositionalArguments(result, that, it, sequenced, tokens);
}
if (that.getNamedArgumentList()!=null) {
interpolateNamedArguments(result, that, it, sequenced, tokens);
}
}
}
}
void finish() {
result.append(template.substring(start, template.length()));
}
}
InterpolateArgumentsVisitor iv = new InterpolateArgumentsVisitor();
iv.visit(term);
iv.finish();
tfc.addEdit(new ReplaceEdit(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1,
result.toString()));
}
}
}
}.visit(pu);
}
private void inlineAttributeReferences(final Tree.CompilationUnit pu, final String template,
final TextChange tfc) {
new Visitor() {
@Override
public void visit(Tree.Variable that) {
if (that.getType() instanceof Tree.SyntheticVariable) {
TypedDeclaration od = that.getDeclarationModel().getOriginalDeclaration();
if (od!=null && od.equals(declaration)) {
tfc.addEdit(new InsertEdit(that.getSpecifierExpression().getStartIndex(),
that.getIdentifier().getText()+" = "));
}
}
super.visit(that);
}
@Override
public void visit(Tree.BaseMemberExpression that) {
super.visit(that);
if (that.getDeclaration().equals(declaration)) {
tfc.addEdit(new ReplaceEdit(that.getStartIndex(),
that.getStopIndex()-that.getStartIndex()+1,
template));
}
}
}.visit(pu);
}
private static void interpolatePositionalArguments(StringBuilder result,
Tree.InvocationExpression that, Tree.BaseMemberExpression it,
boolean sequenced, List<CommonToken> tokens) {
boolean first = true;
boolean found = false;
if (sequenced) {
result.append("{");
}
for (Tree.PositionalArgument arg: that.getPositionalArgumentList()
.getPositionalArguments()) {
if (it.getDeclaration().equals(arg.getParameter().getModel())) {
if (arg.getParameter().isSequenced() &&
(arg instanceof Tree.ListedArgument)) {
if (first) result.append(" ");
if (!first) result.append(", ");
first = false;
}
result.append(AbstractRefactoring.toString(arg,
tokens));
found = true;
}
}
if (sequenced) {
if (!first) result.append(" ");
result.append("}");
}
if (!found) {} //TODO: use default value!
}
private static void interpolateNamedArguments(StringBuilder result,
Tree.InvocationExpression that, Tree.BaseMemberExpression it,
boolean sequenced, List<CommonToken> tokens) {
boolean found = false;
for (Tree.NamedArgument arg: that.getNamedArgumentList().getNamedArguments()) {
if (it.getDeclaration().equals(arg.getParameter())) {
Tree.Term argTerm = ((Tree.SpecifiedArgument) arg).getSpecifierExpression()
.getExpression().getTerm();
result//.append(template.substring(start,it.getStartIndex()-templateStart))
.append(AbstractRefactoring.toString(argTerm, tokens) );
//start = it.getStopIndex()-templateStart+1;
found=true;
}
}
Tree.SequencedArgument seqArg = that.getNamedArgumentList().getSequencedArgument();
if (seqArg!=null && it.getDeclaration().equals(seqArg.getParameter())) {
result//.append(template.substring(start,it.getStartIndex()-templateStart))
.append("{");
//start = it.getStopIndex()-templateStart+1;;
boolean first=true;
for (Tree.PositionalArgument pa: seqArg.getPositionalArguments()) {
if (first) result.append(" ");
if (!first) result.append(", ");
first=false;
result.append(AbstractRefactoring.toString(pa, tokens));
}
if (!first) result.append(" ");
result.append("}");
found=true;
}
if (!found) {
if (sequenced) {
result.append("{}");
}
else {} //TODO: use default value!
}
}
public Declaration getDeclaration() {
return declaration;
}
public void setDelete() {
this.delete = !delete;
}
}
|
package org.eclipse.xtext.junit4.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.xtext.ISetup;
import org.eclipse.xtext.junit4.AbstractXtextTests;
import org.eclipse.xtext.junit4.util.ResourceLoadHelper;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.editor.XtextSourceViewerConfiguration;
import org.eclipse.xtext.ui.editor.contentassist.ConfigurableCompletionProposal;
import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext;
import org.eclipse.xtext.ui.editor.contentassist.ReplacementTextApplier;
import org.eclipse.xtext.ui.editor.model.DocumentPartitioner;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.util.StringInputStream;
import org.eclipse.xtext.util.Strings;
import org.junit.Assert;
import com.google.inject.Inject;
import com.google.inject.Injector;
/**
* Represents a builder for <code>IContentAssistProcessor</code> tests.
*
* @author Michael Clay - Initial contribution and API
* @author Sven Efftinge
* @author Sebastian Zarnekow
*/
public class ContentAssistProcessorTestBuilder implements Cloneable {
private String model;
private String suffix;
private int cursorPosition;
private Injector injector;
private final ResourceLoadHelper loadHelper;
public static class Factory {
private Injector injector;
@Inject
public Factory(Injector injector) {
this.injector = injector;
}
public ContentAssistProcessorTestBuilder create(ResourceLoadHelper resourceLoadHelper) throws Exception {
return new ContentAssistProcessorTestBuilder(this.injector,resourceLoadHelper);
}
}
public ContentAssistProcessorTestBuilder(ISetup setupClazz, AbstractXtextTests tests) throws Exception {
tests.with(setupClazz);
injector = tests.getInjector();
this.loadHelper = tests;
}
public ContentAssistProcessorTestBuilder(Injector injector, ResourceLoadHelper helper) throws Exception {
this.injector = injector;
this.loadHelper = helper;
}
public ContentAssistProcessorTestBuilder reset() throws Exception {
return clone("",0);
}
public ContentAssistProcessorTestBuilder append(String model) throws Exception {
return clone(getModel()+model, cursorPosition+model.length());
}
public ContentAssistProcessorTestBuilder appendSuffix(String suffix) throws Exception {
return cloneWithSuffix(this.suffix==null?suffix:this.suffix+suffix);
}
public ContentAssistProcessorTestBuilder appendNl(String model) throws Exception {
return append(model).append(Strings.newLine());
}
/**
* Inserts the given text at the current cursor position.
* The cursor position will be moved to the end of the inserted text.
*/
public ContentAssistProcessorTestBuilder insert(String model) throws Exception {
return insert(model, getCursorPosition());
}
public ContentAssistProcessorTestBuilder insert(String model, int cursorPosition) throws Exception {
StringBuilder builder = new StringBuilder(getModel()).insert(cursorPosition, model);
return clone(builder.toString(), cursorPosition + model.length());
}
public ContentAssistProcessorTestBuilder cursorBack(int times) throws Exception {
return clone(model, this.cursorPosition -= times);
}
public ContentAssistProcessorTestBuilder appendAndApplyProposal(String model) throws Exception {
return appendAndApplyProposal(model, cursorPosition);
}
public ContentAssistProcessorTestBuilder appendAndApplyProposal(String model, String proposal) throws Exception {
return appendAndApplyProposal(model, cursorPosition, proposal);
}
public ContentAssistProcessorTestBuilder appendAndApplyProposal(String model, int position) throws Exception {
return appendAndApplyProposal(model, position, null);
}
public ContentAssistProcessorTestBuilder appendAndApplyProposal(String model, int position, String proposalString) throws Exception {
IXtextDocument document = getDocument(getModel());
Shell shell = new Shell();
try {
XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
ISourceViewer sourceViewer = getSourceViewer(shell, document, configuration);
ICompletionProposal[] proposals = computeCompletionProposals(document, position, shell);
ICompletionProposal proposal = findProposal(proposalString, proposals);
return appendAndApplyProposal(proposal, sourceViewer, model, position);
} finally {
shell.dispose();
}
}
protected ContentAssistProcessorTestBuilder appendAndApplyProposal(ICompletionProposal proposal, ISourceViewer sourceViewer, String model, int position)
throws Exception {
IDocument document = sourceViewer.getDocument();
int offset = position;
if (model != null) {
document.set(getModel() + model);
offset += model.length();
}
if (proposal instanceof ICompletionProposalExtension2) {
ICompletionProposalExtension2 proposalExtension2 = (ICompletionProposalExtension2) proposal;
proposalExtension2.apply(sourceViewer, (char) 0, SWT.NONE, offset);
} else if (proposal instanceof ICompletionProposalExtension) {
ICompletionProposalExtension proposalExtension = (ICompletionProposalExtension) proposal;
proposalExtension.apply(document, (char) 0, offset);
} else {
proposal.apply(document);
}
return reset().append(document.get());
}
public ContentAssistProcessorTestBuilder applyProposal() throws Exception {
return applyProposal(cursorPosition);
}
public ContentAssistProcessorTestBuilder applyProposal(String proposal) throws Exception {
return applyProposal(cursorPosition, proposal);
}
public ContentAssistProcessorTestBuilder applyProposal(int position) throws Exception {
return applyProposal(position, null);
}
public ContentAssistProcessorTestBuilder applyProposal(int position, String proposalString) throws Exception {
IXtextDocument document = getDocument(getModel());
Shell shell = new Shell();
try {
ICompletionProposal[] proposals = computeCompletionProposals(document, position, shell);
ICompletionProposal proposal = findProposal(proposalString, proposals);
return applyProposal(proposal, document);
} finally {
shell.dispose();
}
}
protected ICompletionProposal findProposal(String proposalString, ICompletionProposal[] proposals) {
if (proposalString != null) {
for (ICompletionProposal candidate : proposals) {
if (proposalString.equals(getProposedText(candidate))) {
return candidate;
}
}
}
return proposals[0];
}
protected ContentAssistProcessorTestBuilder applyProposal(ICompletionProposal proposal) throws Exception {
IXtextDocument document = getDocument(model);
return applyProposal(proposal, document);
}
protected ContentAssistProcessorTestBuilder applyProposal(ICompletionProposal proposal, IXtextDocument document)
throws Exception {
proposal.apply(document);
return reset().append(document.get());
}
public ContentAssistProcessorTestBuilder expectContent(String expectation){
Assert.assertEquals(expectation, getModel());
return this;
}
public ContentAssistProcessorTestBuilder assertCount(int completionProposalCount) throws Exception {
return assertCountAtCursorPosition(completionProposalCount, this.cursorPosition);
}
public ContentAssistProcessorTestBuilder assertText(String... expectedText) throws Exception {
return assertTextAtCursorPosition(this.cursorPosition, expectedText);
}
public ProposalTester assertProposalAtCursor(String expectedText) throws Exception {
String currentModelToParse = getFullTextToBeParsed();
int idx = currentModelToParse.indexOf("<|>");
currentModelToParse = currentModelToParse.substring(0, idx) + currentModelToParse.substring(idx + 3);
ICompletionProposal[] proposals = computeCompletionProposals(currentModelToParse, idx);
if (proposals == null)
proposals = new ICompletionProposal[0];
for(ICompletionProposal proposal: proposals) {
if (expectedText.equals(toString(proposal))) {
return new ProposalTester(proposal);
}
}
Assert.fail("No such proposal: " + expectedText + " Found: " + toString(proposals));
return null;
}
public ProposalTester assertProposal(String expectedText) throws Exception {
String currentModelToParse = getFullTextToBeParsed();
ICompletionProposal[] proposals = computeCompletionProposals(currentModelToParse,
cursorPosition);
if (proposals == null)
proposals = new ICompletionProposal[0];
for(ICompletionProposal proposal: proposals) {
if (expectedText.equals(toString(proposal))) {
return new ProposalTester(proposal);
}
}
Assert.fail("No such proposal: " + expectedText + " Found: " + toString(proposals));
return null;
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(
String cursorPosition, String... expectedText) throws Exception {
return assertTextAtCursorPosition(getModel().indexOf(cursorPosition), expectedText);
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(
String cursorPosition, int offset, String... expectedText) throws Exception {
return assertTextAtCursorPosition(getModel().indexOf(cursorPosition) + offset, expectedText);
}
public ContentAssistProcessorTestBuilder assertTextAtCursorPosition(int cursorPosition, String... expectedText)
throws Exception {
String currentModelToParse = getFullTextToBeParsed();
ICompletionProposal[] computeCompletionProposals = computeCompletionProposals(currentModelToParse,
cursorPosition);
if (computeCompletionProposals == null)
computeCompletionProposals = new ICompletionProposal[0];
Arrays.sort(expectedText);
final String expectation = Strings.concat("\n", Arrays.asList(expectedText));
final String actual = Strings.concat("\n", toString(computeCompletionProposals));
Assert.assertEquals(expectation, actual);
for (int i = 0; i < computeCompletionProposals.length; i++) {
ICompletionProposal completionProposal = computeCompletionProposals[i];
String proposedText = getProposedText(completionProposal);
Assert.assertTrue("Missing proposal '" + proposedText + "'. Expect completionProposal text '" + expectation + "', but got " +
actual,
Arrays.asList(expectedText).contains(proposedText));
}
return this;
}
protected String getProposedText(ICompletionProposal completionProposal) {
String proposedText = completionProposal.getDisplayString();
if (completionProposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurableProposal = (ConfigurableCompletionProposal) completionProposal;
proposedText = configurableProposal.getReplacementString();
if (configurableProposal.getTextApplier() instanceof ReplacementTextApplier) {
proposedText = ((ReplacementTextApplier) configurableProposal.getTextApplier()).getActualReplacementString(configurableProposal);
}
}
return proposedText;
}
public ContentAssistProcessorTestBuilder assertMatchString(String matchString)
throws Exception {
String currentModelToParse = getModel();
final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(currentModelToParse));
final IXtextDocument xtextDocument = getDocument(xtextResource, currentModelToParse);
XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
Shell shell = new Shell();
try {
ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
String contentType = xtextDocument.getContentType(currentModelToParse.length());
if (contentAssistant.getContentAssistProcessor(contentType) != null) {
ContentAssistContext.Factory factory = get(ContentAssistContext.Factory.class);
ContentAssistContext[] contexts = factory.create(sourceViewer, currentModelToParse.length(), xtextResource);
for(ContentAssistContext context: contexts) {
Assert.assertTrue("matchString = '" + matchString + "', actual: '" + context.getPrefix() + "'",
"".equals(context.getPrefix()) || matchString.equals(context.getPrefix()));
}
} else {
Assert.fail("No content assistant for content type " + contentType);
}
return this;
} finally {
shell.dispose();
}
}
public ContentAssistProcessorTestBuilder assertCursorIsAfter(String text) {
Assert.assertTrue("cursor should be after '" + text + "' but it's after " + model.substring(0, getCursorPosition()),
model.substring(getCursorPosition() - text.length()).startsWith(text));
return this;
}
public ContentAssistProcessorTestBuilder assertCursorIsBefore(String text) {
Assert.assertTrue("cursor should be before '" + text + "' but it's before " + model.substring(getCursorPosition()),
model.substring(getCursorPosition()).startsWith(text));
return this;
}
protected String getModel() {
return this.model == null ? "":model;
}
protected String getFullTextToBeParsed() {
return getModel()+(this.suffix== null ? "":suffix);
}
public List<String> toString(ICompletionProposal[] proposals) {
if (proposals == null)
return Collections.emptyList();
List<String> res = new ArrayList<String>(proposals.length);
for (ICompletionProposal proposal : proposals) {
String proposedText = toString(proposal);
res.add(proposedText);
}
Collections.sort(res);
return res;
}
protected String toString(ICompletionProposal proposal) {
String proposedText = proposal.getDisplayString();
if (proposal instanceof ConfigurableCompletionProposal) {
ConfigurableCompletionProposal configurableProposal = (ConfigurableCompletionProposal) proposal;
proposedText = configurableProposal.getReplacementString();
if (configurableProposal.getTextApplier() instanceof ReplacementTextApplier)
proposedText = ((ReplacementTextApplier) configurableProposal.getTextApplier()).getActualReplacementString(configurableProposal);
}
return proposedText;
}
public ContentAssistProcessorTestBuilder assertCountAtCursorPosition(int completionProposalCount, int cursorPosition)
throws Exception {
String currentModelToParse = getFullTextToBeParsed();
ICompletionProposal[] computeCompletionProposals = computeCompletionProposals(currentModelToParse,
cursorPosition);
StringBuffer computedProposals = new StringBuffer();
for (int i = 0; i < computeCompletionProposals.length; i++) {
computedProposals.append(computeCompletionProposals[i].getDisplayString());
if (i<(computeCompletionProposals.length-1)) {
computedProposals.append(",");
}
}
Assert.assertEquals("expect only " + completionProposalCount + " CompletionProposal item for model '"
+ currentModelToParse + "' but got '"+computedProposals+"'", completionProposalCount, computeCompletionProposals.length);
return this;
}
public ICompletionProposal[] computeCompletionProposals(final String currentModelToParse, int cursorPosition)
throws Exception {
final IXtextDocument xtextDocument = getDocument(currentModelToParse);
return computeCompletionProposals(xtextDocument, cursorPosition);
}
protected ICompletionProposal[] computeCompletionProposals(final IXtextDocument xtextDocument, int cursorPosition)
throws BadLocationException {
Shell shell = new Shell();
try {
return computeCompletionProposals(xtextDocument, cursorPosition, shell);
} finally {
shell.dispose();
}
}
protected ICompletionProposal[] computeCompletionProposals(final IXtextDocument xtextDocument, int cursorPosition,
Shell shell) throws BadLocationException {
XtextSourceViewerConfiguration configuration = get(XtextSourceViewerConfiguration.class);
ISourceViewer sourceViewer = getSourceViewer(shell, xtextDocument, configuration);
return computeCompletionProposals(xtextDocument, cursorPosition, configuration, sourceViewer);
}
protected ICompletionProposal[] computeCompletionProposals(final IXtextDocument xtextDocument, int cursorPosition,
XtextSourceViewerConfiguration configuration, ISourceViewer sourceViewer) throws BadLocationException {
IContentAssistant contentAssistant = configuration.getContentAssistant(sourceViewer);
String contentType = xtextDocument.getContentType(cursorPosition);
IContentAssistProcessor processor = contentAssistant.getContentAssistProcessor(contentType);
if (processor != null) {
return processor.computeCompletionProposals(sourceViewer, cursorPosition);
}
return new ICompletionProposal[0];
}
protected IXtextDocument getDocument(final String currentModelToParse) {
final XtextResource xtextResource = loadHelper.getResourceFor(new StringInputStream(Strings.emptyIfNull(currentModelToParse)));
return getDocument(xtextResource, currentModelToParse);
}
protected ISourceViewer getSourceViewer(Shell shell, final IXtextDocument xtextDocument,
XtextSourceViewerConfiguration configuration) {
XtextSourceViewer.Factory factory = get(XtextSourceViewer.Factory.class);
ISourceViewer sourceViewer = factory.createSourceViewer(shell, null, null, false, 0);
sourceViewer.configure(configuration);
sourceViewer.setDocument(xtextDocument);
return sourceViewer;
}
public ICompletionProposal[] computeCompletionProposals(int cursorPosition) throws Exception {
return computeCompletionProposals(getFullTextToBeParsed(), cursorPosition);
}
public ICompletionProposal[] computeCompletionProposals(String cursorPosition) throws Exception {
return computeCompletionProposals(getFullTextToBeParsed(), getModel().indexOf(cursorPosition));
}
public ICompletionProposal[] computeCompletionProposals() throws Exception {
return computeCompletionProposals(getFullTextToBeParsed(), cursorPosition);
}
@Override
public String toString() {
return getModel() + "\n length: " + getModel().length() + "\n cursor at: "
+ this.cursorPosition;
}
public IXtextDocument getDocument(final XtextResource xtextResource, final String model) {
XtextDocument document = get(XtextDocument.class);
document.set(model);
document.setInput(xtextResource);
DocumentPartitioner partitioner = get(DocumentPartitioner.class);
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
return document;
}
public ITextViewer getSourceViewer(final String currentModelToParse, final IXtextDocument xtextDocument) {
ITextViewer result = new MockableTextViewer() {
@Override
public IDocument getDocument() {
return xtextDocument;
}
@Override
public ISelectionProvider getSelectionProvider() {
return new MockableSelectionProvider() {
@Override
public ISelection getSelection() {
return TextSelection.emptySelection();
}
};
}
@Override
public StyledText getTextWidget() {
return null;
}
};
return result;
}
protected ContentAssistProcessorTestBuilder clone(String model, int offset) throws Exception {
ContentAssistProcessorTestBuilder builder = (ContentAssistProcessorTestBuilder) clone();
builder.model = model;
builder.cursorPosition = offset;
builder.suffix = this.suffix;
return builder;
}
protected ContentAssistProcessorTestBuilder cloneWithSuffix(String postFix) throws Exception {
ContentAssistProcessorTestBuilder builder = (ContentAssistProcessorTestBuilder) clone();
builder.model = this.model;
builder.cursorPosition = this.cursorPosition;
builder.suffix = postFix;
return builder;
}
public <T> T get(Class<T> clazz) {
return injector.getInstance(clazz);
}
protected int getCursorPosition() {
return cursorPosition;
}
public class ProposalTester {
private ICompletionProposal proposal;
protected ProposalTester(ICompletionProposal proposal) {
this.proposal = proposal;
}
public ProposalTester withDisplayString(String displayString) {
Assert.assertEquals("displayString", displayString, proposal.getDisplayString());
return this;
}
public ContentAssistProcessorTestBuilder apply() throws Exception {
return ContentAssistProcessorTestBuilder.this.applyProposal(proposal);
}
}
}
|
package org.csstudio.scan.commandimpl;
import java.io.InputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.csstudio.scan.ScanSystemPreferences;
import org.csstudio.scan.command.IncludeCommand;
import org.csstudio.scan.command.ScanCommand;
import org.csstudio.scan.command.ScanCommandFactory;
import org.csstudio.scan.command.XMLCommandReader;
import org.csstudio.scan.server.JythonSupport;
import org.csstudio.scan.server.ScanCommandImpl;
import org.csstudio.scan.server.ScanCommandImplTool;
import org.csstudio.scan.server.ScanContext;
import org.csstudio.scan.server.SimulationContext;
import org.csstudio.scan.server.internal.PathStreamTool;
/** {@link ScanCommandImpl} that includes another scan
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class IncludeCommandImpl extends ScanCommandImpl<IncludeCommand>
{
private List<ScanCommandImpl<?>> scan_impl;
/** {@inheritDoc} */
public IncludeCommandImpl(final IncludeCommand command, final JythonSupport jython) throws Exception
{
super(command, jython);
// Parse scan
final String[] paths = ScanSystemPreferences.getScriptPaths();
final InputStream scan_stream = PathStreamTool.openStream(paths, command.getScanFile());
final XMLCommandReader reader = new XMLCommandReader(new ScanCommandFactory());
final List<ScanCommand> commands = reader.readXMLStream(scan_stream);
// Implement
final ScanCommandImplTool implementor = ScanCommandImplTool.getInstance();
scan_impl = implementor.implement(commands, jython);
}
/** {@inheritDoc} */
@Override
public long getWorkUnits()
{
long included_units = 0;
for (ScanCommandImpl<?> command : scan_impl)
included_units += command.getWorkUnits();
return included_units;
}
/** {@inheritDoc} */
@Override
public String[] getDeviceNames(final ScanContext context) throws Exception
{
context.pushMacros(command.getMacros());
try
{
final Set<String> devices = new HashSet<String>();
for (ScanCommandImpl<?> command : scan_impl)
{
for (String device_name : command.getDeviceNames(context))
devices.add(device_name);
}
return devices.toArray(new String[devices.size()]);
}
finally
{
context.popMacros();
}
}
/** {@inheritDoc} */
@Override
public void simulate(final SimulationContext context) throws Exception
{
context.pushMacros(command.getMacros());
try
{
context.logExecutionStep(context.resolveMacros(command.toString()), 0.0);
context.simulate(scan_impl);
}
finally
{
context.popMacros();
}
}
/** {@inheritDoc} */
@Override
public void execute(final ScanContext context) throws Exception
{
context.pushMacros(command.getMacros());
try
{
context.execute(scan_impl);
}
finally
{
context.popMacros();
}
}
}
|
package util;
import java.util.*;
import java.math.*;
public class EntityPlayer extends Entity {
protected double armor,speed,speedX,level;
protected int heldItemIndex;
protected Inventory inventory;
public EntityPlayer() {
super();
this.armor = 0.1;
this.speed = 0.1;
this.speedX = 1;
this.inventory = new Inventory(3);
}
public EntityPlayer(double armor, double health, double speed, double damage){
super(health, damage);
this.armor = armor;
this.speed = speed;
this.maxHealth = health;
this.inventory = new Inventory(3);
this.level = 1;
this.speedX = 1;
}
/*
* returns damage + the addedDamage combined
*/
public double getDamage(){
if(inventory.getItem(1) != null) return damage + ((Sword)inventory.getItem(1)).getDamage();
else return damage + (level * 5);
}
public double getArmor() {
if(inventory.getItem(0) != null) return armor + ((Armor)inventory.getItem(0)).getArmor();
else return armor + (level/100);
}
/*
* applies input damage from object creature to player
*
* takes into account armor
*/
public void damagePlayer(EntityCreature creature){
health = health - ( creature.getDamage() - (creature.getDamage() * (getArmor())));
}
/*
* adds health to player, then returns
*
* takes into account error in going over full health, no worries
*/
public double healPlayer(double item){
if (item + health >= health)
{
health = maxHealth;
return health;
}
else return health + item;
}
/*
* returns speed times the multiplier
*/
public double getSpeed(){
return speed * speedX;
}
public Item getCurrentHeldItem() {
return this.inventory.getItem(this.heldItemIndex);
}
public void setHeldItem(Item item) {
if(this.inventory.getSlot(item) > -1) this.heldItemIndex = this.inventory.getSlot(item);
}
/*
* adds item based on type
*
* works off of instanceof , error will occur if one of the following items aren't used "Armor, Potion, Sword, Boot"
*/
public void addItem(Item item){
for (int i = 0; i < inventory.size(); i++){
if(inventory.getItem(i) == item) {
setHeldItem(item);
removeItem(heldItemIndex);
break;
}
}
if(item instanceof Armor)
{
inventory.setSlot(0,item);
}
else if (item instanceof Potion)
{
this.health = (healPlayer(((Potion)item).getHeal()));
}
else if (item instanceof Sword)
{
inventory.setSlot(1,item);
}
else if (item instanceof Boots)
{
this.speedX = ((Boots)item).getSpeed();
inventory.setSlot(2,item);
}
}
/*
* this is used to elimate item values
* MUST BE USED AFTER THE METHOD "setHeldItem(Item)"
*/
public void removeItem(int itemIndex) {
inventory.setSlot(itemIndex,null);
}
public void leveling(EntityCreature creature){
level = level + ((level * Math.sqrt(creature.getXP()))/100);
this.health = this.health + ((getLevel() * health)/7);
this.damage = this.damage + ((getLevel() * damage)/4);
}
public double getLevel(){
return level;
}
}
|
package com.opengamma.financial.analytics.model.pnl;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.time.calendar.Clock;
import javax.time.calendar.LocalDate;
import javax.time.calendar.Period;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.schedule.HolidayDateRemovalFunction;
import com.opengamma.analytics.financial.schedule.Schedule;
import com.opengamma.analytics.financial.schedule.ScheduleCalculatorFactory;
import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunction;
import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunctionFactory;
import com.opengamma.analytics.financial.timeseries.util.TimeSeriesDifferenceOperator;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.core.position.Position;
import com.opengamma.core.security.Security;
import com.opengamma.core.value.MarketDataRequirementNames;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.DoubleLabelledMatrix2D;
import com.opengamma.financial.analytics.model.InstrumentTypeProperties;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.analytics.model.forex.ForexVisitors;
import com.opengamma.financial.analytics.model.forex.option.black.FXOptionBlackFunction;
import com.opengamma.financial.analytics.timeseries.DateConstraint;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesBundle;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils;
import com.opengamma.financial.analytics.volatility.surface.ConfigDBVolatilitySurfaceDefinitionSource;
import com.opengamma.financial.analytics.volatility.surface.ConfigDBVolatilitySurfaceSpecificationSource;
import com.opengamma.financial.analytics.volatility.surface.SurfaceInstrumentProvider;
import com.opengamma.financial.analytics.volatility.surface.VolatilitySurfaceDefinition;
import com.opengamma.financial.analytics.volatility.surface.VolatilitySurfaceSpecification;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.calendar.MondayToFridayCalendar;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.financial.security.fx.FXUtils;
import com.opengamma.financial.security.option.FXOptionSecurity;
import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.UnorderedCurrencyPair;
import com.opengamma.util.timeseries.DoubleTimeSeries;
public class FXOptionBlackVegaPnLFunction extends AbstractFunction.NonCompiledInvoker {
private static final HolidayDateRemovalFunction HOLIDAY_REMOVER = HolidayDateRemovalFunction.getInstance();
private static final Calendar WEEKEND_CALENDAR = new MondayToFridayCalendar("Weekend");
private static final TimeSeriesDifferenceOperator DIFFERENCE = new TimeSeriesDifferenceOperator();
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) throws AsynchronousExecution {
final Object vegaMatrixObject = inputs.getValue(ValueRequirementNames.VEGA_QUOTE_MATRIX);
if (vegaMatrixObject == null) {
throw new OpenGammaRuntimeException("Could not get vega matrix");
}
final Object volatilityHTSObject = inputs.getValue(ValueRequirementNames.VOLATILITY_SURFACE_HISTORICAL_TIME_SERIES);
if (volatilityHTSObject == null) {
throw new OpenGammaRuntimeException("Could not get historical time series for volatilities");
}
final DoubleLabelledMatrix2D vegaMatrix = (DoubleLabelledMatrix2D) vegaMatrixObject;
final HistoricalTimeSeriesBundle timeSeriesBundle = (HistoricalTimeSeriesBundle) volatilityHTSObject;
final Clock snapshotClock = executionContext.getValuationClock();
final LocalDate now = snapshotClock.zonedDateTime().toLocalDate();
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE);
final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext);
final ConfigDBVolatilitySurfaceDefinitionSource definitionSource = new ConfigDBVolatilitySurfaceDefinitionSource(configSource);
final ConfigDBVolatilitySurfaceSpecificationSource specificationSource = new ConfigDBVolatilitySurfaceSpecificationSource(configSource);
final Position position = target.getPosition();
final FinancialSecurity security = (FinancialSecurity) position.getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(putCurrency, callCurrency);
final VolatilitySurfaceDefinition<Object, Object> definition = getSurfaceDefinition(currencyPair, surfaceName, definitionSource);
final VolatilitySurfaceSpecification specification = getSurfaceSpecification(currencyPair, surfaceName, specificationSource);
final Period samplingPeriod = getSamplingPeriod(desiredValue.getConstraint(ValuePropertyNames.SAMPLING_PERIOD));
final LocalDate startDate = now.minus(samplingPeriod);
final String scheduleCalculatorName = desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR);
final Schedule scheduleCalculator = getScheduleCalculator(scheduleCalculatorName);
final String samplingFunctionName = desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION);
final TimeSeriesSamplingFunction samplingFunction = getSamplingFunction(samplingFunctionName);
final LocalDate[] schedule = HOLIDAY_REMOVER.getStrippedSchedule(scheduleCalculator.getSchedule(startDate, now, true, false), WEEKEND_CALENDAR);
DoubleTimeSeries<?> vegaPnL = getPnLSeries(definition, specification, timeSeriesBundle, vegaMatrix, now, schedule, samplingFunction);
vegaPnL = vegaPnL.multiply(position.getQuantity().doubleValue());
final String currencyBase = getResultCurrency(target);
final ValueProperties properties = getResultProperties(desiredValue, currencyBase);
final ValueSpecification spec = new ValueSpecification(ValueRequirementNames.PNL_SERIES, target.toSpecification(), properties);
return Collections.singleton(new ComputedValue(spec, vegaPnL));
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.POSITION;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
final Security security = target.getPosition().getSecurity();
return security instanceof FXOptionSecurity || security instanceof NonDeliverableFXOptionSecurity;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final FinancialSecurity security = (FinancialSecurity) target.getPosition().getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final Currency currencyBase = FXUtils.baseCurrency(putCurrency, callCurrency); // The base currency
final ValueProperties properties = createValueProperties()
.with(ValuePropertyNames.CALCULATION_METHOD, FXOptionBlackFunction.BLACK_METHOD)
.withAny(FXOptionBlackFunction.PUT_CURVE)
.withAny(FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG)
.withAny(FXOptionBlackFunction.CALL_CURVE)
.withAny(FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG)
.withAny(ValuePropertyNames.SURFACE)
.withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
.withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME)
.withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME)
.with(ValuePropertyNames.CURRENCY, currencyBase.getCode())
.withAny(ValuePropertyNames.SAMPLING_PERIOD)
.withAny(ValuePropertyNames.SCHEDULE_CALCULATOR)
.withAny(ValuePropertyNames.SAMPLING_FUNCTION)
.with(YieldCurveNodePnLFunction.PROPERTY_PNL_CONTRIBUTIONS, ValueRequirementNames.VEGA_QUOTE_MATRIX)
.get();
return Sets.newHashSet(new ValueSpecification(ValueRequirementNames.PNL_SERIES, target.toSpecification(), properties));
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> putCurveNames = constraints.getValues(FXOptionBlackFunction.PUT_CURVE);
if (putCurveNames == null || putCurveNames.size() != 1) {
return null;
}
final Set<String> putCurveCalculationConfigs = constraints.getValues(FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG);
if (putCurveCalculationConfigs == null || putCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> callCurveNames = constraints.getValues(FXOptionBlackFunction.CALL_CURVE);
if (callCurveNames == null || callCurveNames.size() != 1) {
return null;
}
final Set<String> callCurveCalculationConfigs = constraints.getValues(FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG);
if (callCurveCalculationConfigs == null || callCurveCalculationConfigs.size() != 1) {
return null;
}
final Set<String> surfaceNames = constraints.getValues(ValuePropertyNames.SURFACE);
if (surfaceNames == null || surfaceNames.size() != 1) {
return null;
}
final Set<String> interpolatorNames = constraints.getValues(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
if (interpolatorNames == null || interpolatorNames.size() != 1) {
return null;
}
final Set<String> leftExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
if (leftExtrapolatorNames == null || leftExtrapolatorNames.size() != 1) {
return null;
}
final Set<String> rightExtrapolatorNames = constraints.getValues(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
if (rightExtrapolatorNames == null || rightExtrapolatorNames.size() != 1) {
return null;
}
final Set<String> samplingPeriods = constraints.getValues(ValuePropertyNames.SAMPLING_PERIOD);
if (samplingPeriods == null || samplingPeriods.size() != 1) {
return null;
}
final FinancialSecurity security = (FinancialSecurity) target.getPosition().getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
final UnorderedCurrencyPair currencies = UnorderedCurrencyPair.of(putCurrency, callCurrency);
final String surfaceName = Iterables.getOnlyElement(surfaceNames);
final String samplingPeriod = Iterables.getOnlyElement(samplingPeriods);
final ValueRequirement vegaMatrixRequirement = new ValueRequirement(ValueRequirementNames.VEGA_QUOTE_MATRIX, security,
ValueProperties.builder()
.with(ValuePropertyNames.CALCULATION_METHOD, FXOptionBlackFunction.BLACK_METHOD)
.with(FXOptionBlackFunction.PUT_CURVE, Iterables.getOnlyElement(putCurveNames))
.with(FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG, Iterables.getOnlyElement(putCurveCalculationConfigs))
.with(FXOptionBlackFunction.CALL_CURVE, Iterables.getOnlyElement(callCurveNames))
.with(FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG, Iterables.getOnlyElement(callCurveCalculationConfigs))
.with(ValuePropertyNames.SURFACE, surfaceName)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, Iterables.getOnlyElement(interpolatorNames))
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, Iterables.getOnlyElement(leftExtrapolatorNames))
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, Iterables.getOnlyElement(rightExtrapolatorNames))
.with(ValuePropertyNames.CURRENCY, getResultCurrency(target)).get());
final ValueRequirement surfaceHTSRequirement = getVolatilitySurfaceHTSRequirement(currencies, surfaceName, samplingPeriod);
final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>();
requirements.add(vegaMatrixRequirement);
requirements.add(surfaceHTSRequirement);
return requirements;
}
private ValueRequirement getVolatilitySurfaceHTSRequirement(final UnorderedCurrencyPair currencies, final String surfaceName, final String samplingPeriod) {
return HistoricalTimeSeriesFunctionUtils.createVolatilitySurfaceHTSRequirement(currencies, surfaceName, InstrumentTypeProperties.FOREX,
MarketDataRequirementNames.MARKET_VALUE, null, DateConstraint.VALUATION_TIME.minus(samplingPeriod), true, DateConstraint.VALUATION_TIME, true);
}
private VolatilitySurfaceDefinition<Object, Object> getSurfaceDefinition(final UnorderedCurrencyPair currencyPair, final String definitionName,
final ConfigDBVolatilitySurfaceDefinitionSource definitionSource) {
final String fullDefinitionName = definitionName + "_" + currencyPair.getUniqueId().getValue();
final VolatilitySurfaceDefinition<Object, Object> definition = (VolatilitySurfaceDefinition<Object, Object>) definitionSource.getDefinition(fullDefinitionName,
InstrumentTypeProperties.FOREX);
if (definition == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface definition named " + fullDefinitionName + " for instrument type " + InstrumentTypeProperties.FOREX);
}
return definition;
}
private VolatilitySurfaceSpecification getSurfaceSpecification(final UnorderedCurrencyPair currencyPair, final String specificationName,
final ConfigDBVolatilitySurfaceSpecificationSource specificationSource) {
final String fullSpecificationName = specificationName + "_" + currencyPair.getUniqueId().getValue();
final VolatilitySurfaceSpecification specification = specificationSource.getSpecification(fullSpecificationName, InstrumentTypeProperties.FOREX);
if (specification == null) {
throw new OpenGammaRuntimeException("Could not get volatility surface specification named " + fullSpecificationName);
}
return specification;
}
private Period getSamplingPeriod(final String samplingPeriodName) {
return Period.parse(samplingPeriodName);
}
private Schedule getScheduleCalculator(final String scheduleCalculatorName) {
return ScheduleCalculatorFactory.getScheduleCalculator(scheduleCalculatorName);
}
private TimeSeriesSamplingFunction getSamplingFunction(final String samplingFunctionName) {
return TimeSeriesSamplingFunctionFactory.getFunction(samplingFunctionName);
}
private DoubleTimeSeries<?> getPnLSeries(final VolatilitySurfaceDefinition<Object, Object> definition, final VolatilitySurfaceSpecification specification,
final HistoricalTimeSeriesBundle timeSeriesBundle, final DoubleLabelledMatrix2D vegaMatrix, final LocalDate endDate, final LocalDate[] schedule,
final TimeSeriesSamplingFunction samplingFunction) {
final SurfaceInstrumentProvider<Object, Object> provider = (SurfaceInstrumentProvider<Object, Object>) specification.getSurfaceInstrumentProvider();
final double[][] vegas = vegaMatrix.getValues();
if (vegas.length != definition.getYs().length || vegas[0].length != definition.getXs().length) {
throw new OpenGammaRuntimeException("Vega matrix not the same shape as that in definition");
}
DoubleTimeSeries<?> vegaPnL = null;
int i = 0;
for (final Object x : definition.getXs()) {
int j = 0;
for (final Object y : definition.getYs()) {
ExternalId id = provider.getInstrument(x, y, endDate);
if (id.getScheme().equals(ExternalSchemes.BLOOMBERG_TICKER_WEAK)) {
id = ExternalSchemes.bloombergTickerSecurityId(id.getValue());
}
final ExternalIdBundle identifier = ExternalIdBundle.of(id);
final HistoricalTimeSeries tsForTicker = timeSeriesBundle.get(MarketDataRequirementNames.MARKET_VALUE, identifier);
if (tsForTicker == null) {
throw new OpenGammaRuntimeException("Could not get identifier / vol series for " + id);
}
final DoubleTimeSeries<?> volHistory = DIFFERENCE.evaluate(samplingFunction.getSampledTimeSeries(tsForTicker.getTimeSeries(), schedule));
final double vega = vegas[j][i] * 100;
if (vegaPnL == null) {
vegaPnL = volHistory.multiply(vega);
} else {
vegaPnL = vegaPnL.add(volHistory.multiply(vega));
}
j++;
}
i++;
}
return vegaPnL;
}
private ValueProperties getResultProperties(final ValueRequirement desiredValue, final String currencyBase) {
final String putCurveName = desiredValue.getConstraint(FXOptionBlackFunction.PUT_CURVE);
final String callCurveName = desiredValue.getConstraint(FXOptionBlackFunction.CALL_CURVE);
final String surfaceName = desiredValue.getConstraint(ValuePropertyNames.SURFACE);
final String putCurveConfig = desiredValue.getConstraint(FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG);
final String callCurveConfig = desiredValue.getConstraint(FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG);
final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
final String leftExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
final String rightExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
final String samplingPeriod = desiredValue.getConstraint(ValuePropertyNames.SAMPLING_PERIOD);
final String scheduleCalculator = desiredValue.getConstraint(ValuePropertyNames.SCHEDULE_CALCULATOR);
final String samplingFunction = desiredValue.getConstraint(ValuePropertyNames.SAMPLING_FUNCTION);
return createValueProperties()
.with(ValuePropertyNames.CALCULATION_METHOD, FXOptionBlackFunction.BLACK_METHOD)
.with(FXOptionBlackFunction.PUT_CURVE, putCurveName)
.with(FXOptionBlackFunction.PUT_CURVE_CALC_CONFIG, putCurveConfig)
.with(FXOptionBlackFunction.CALL_CURVE, callCurveName)
.with(FXOptionBlackFunction.CALL_CURVE_CALC_CONFIG, callCurveConfig)
.with(ValuePropertyNames.SURFACE, surfaceName)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName)
.with(ValuePropertyNames.CURRENCY, currencyBase)
.with(ValuePropertyNames.SAMPLING_PERIOD, samplingPeriod)
.with(ValuePropertyNames.SCHEDULE_CALCULATOR, scheduleCalculator)
.with(ValuePropertyNames.SAMPLING_FUNCTION, samplingFunction)
.with(YieldCurveNodePnLFunction.PROPERTY_PNL_CONTRIBUTIONS, ValueRequirementNames.VEGA_QUOTE_MATRIX)
.get();
}
private String getResultCurrency(final ComputationTarget target) {
final FinancialSecurity security = (FinancialSecurity) target.getPosition().getSecurity();
final Currency putCurrency = security.accept(ForexVisitors.getPutCurrencyVisitor());
final Currency callCurrency = security.accept(ForexVisitors.getCallCurrencyVisitor());
Currency ccy;
if (FXUtils.isInBaseQuoteOrder(putCurrency, callCurrency)) {
ccy = callCurrency;
} else {
ccy = putCurrency;
}
return ccy.getCode();
}
}
|
package pl.consdata.ico.sqcompanion.sync;
import javax.annotation.PostConstruct;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/**
* @author gregorry
*/
@Slf4j
@Service
@Profile("default")
public class SyncAfterAppInitialization {
private final SynchronizationService synchronizationService;
public SyncAfterAppInitialization(final SynchronizationService synchronizationService) {
this.synchronizationService = synchronizationService;
}
@PostConstruct
public void tickSynchronizationAfterAppInit() {
synchronizationService.runSynchronization();
}
}
|
package org.aksw.sparqlify.qa.metrics.interpretability;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.aksw.sparqlify.core.algorithms.ViewQuad;
import org.aksw.sparqlify.core.domain.input.ViewDefinition;
import org.aksw.sparqlify.qa.dataset.SparqlifyDataset;
import org.aksw.sparqlify.qa.exceptions.NotImplementedException;
import org.aksw.sparqlify.qa.metrics.DatasetMetric;
import org.aksw.sparqlify.qa.metrics.PinpointMetric;
import org.aksw.sparqlify.qa.sinks.TriplePosition;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;
/**
* This metric checks if a given resource has a certain ontological context,
* meaning that its role in an ontology is well defined.
* Such an ontoogical context is assigned via ontology properties like
* rdf:type, rdfs:subClassOf, owl:equivalentProperty, ... (see ontProperties
* list)
*
* This metric considers only local resources.
*
* @author Patrick Westphal <patrick.westphal@informatik.uni-leipzig.de>
*
*/
public class ResourceInterpretability extends PinpointMetric implements
DatasetMetric {
List<Resource> seenResources;
List<Property> ontProperties = new ArrayList<Property>(Arrays.asList(
// rdf(s)
RDF.type, RDFS.subClassOf, RDFS.subPropertyOf, RDFS.domain,
RDFS.range,
// owl
OWL.complementOf, OWL.disjointWith, OWL.equivalentClass,
OWL.equivalentProperty, OWL.intersectionOf, OWL.inverseOf,
OWL.oneOf, OWL.unionOf
));
public ResourceInterpretability() {
super();
seenResources = new ArrayList<Resource>();
}
@Override
public void assessDataset(SparqlifyDataset dataset)
throws NotImplementedException {
StmtIterator statementsIt = dataset.listStatements();
while (statementsIt.hasNext()) {
Statement statement = statementsIt.next();
Resource subject = statement.getSubject();
Resource predicate = statement.getPredicate().asResource();
RDFNode object = statement.getObject();
/* subject */
if (!seenResources.contains(subject) && subject.isURIResource()
&& subject.getURI().startsWith(dataset.getPrefix())) {
checkResourceInterpretability(subject,
TriplePosition.SUBJECT, statement, dataset);
seenResources.add(subject);
}
/* predicate */
if (!seenResources.contains(predicate)
&& predicate.getURI().startsWith(dataset.getPrefix())) {
checkResourceInterpretability(predicate,
TriplePosition.PREDICATE, statement, dataset);
seenResources.add(predicate);
}
/* object */
if (object.isURIResource() && !seenResources.contains(object.asResource())
&& object.asResource().getURI().startsWith(dataset.getPrefix())) {
checkResourceInterpretability(object.asResource(),
TriplePosition.OBJECT, statement, dataset);
seenResources.add(object.asResource());
}
}
}
private void checkResourceInterpretability(Resource resource,
TriplePosition pos, Statement statement, SparqlifyDataset dataset)
throws NotImplementedException {
boolean ontPropStatementFound = false;
// check if resource is further described using one of the proposed
// properties
for (Property ontProp : ontProperties) {
if (dataset.listStatements(resource, ontProp, (RDFNode) null).hasNext()) {
ontPropStatementFound = true;
break;
}
}
if (!ontPropStatementFound) {
Set<ViewQuad<ViewDefinition>> viewQuads = pinpointer
.getViewCandidates(statement.asTriple());
writeNodeTripleMeasureToSink(0, pos, statement.asTriple(), viewQuads);
}
}
}
|
package org.axonframework.boot.autoconfig;
import com.codahale.metrics.MetricRegistry;
import org.axonframework.metrics.GlobalMetricRegistry;
import org.axonframework.metrics.MetricsModuleConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Auto configuration to set up Metrics for the infrastructure components.
*
* @author Steven van Beelen
* @since 3.2
*/
@Configuration
@AutoConfigureBefore(AxonAutoConfiguration.class)
@ConditionalOnClass(name = {
"com.codahale.metrics.MetricRegistry",
"org.axonframework.metrics.GlobalMetricRegistry"
})
public class MetricsAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public MetricRegistry metricRegistry() {
return new MetricRegistry();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(MetricRegistry.class)
public GlobalMetricRegistry globalMetricRegistry(MetricRegistry metricRegistry) {
return new GlobalMetricRegistry(metricRegistry);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnBean(GlobalMetricRegistry.class)
public MetricsModuleConfigurer metricsModuleConfigurer(GlobalMetricRegistry globalMetricRegistry) {
return new MetricsModuleConfigurer(globalMetricRegistry);
}
}
|
package dk.statsbiblioteket.newspaper.metadatachecker.jpylyzer;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.AttributeParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.DataFileNodeBeginsParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.DataFileNodeEndsParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeBeginsParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.common.NodeEndParsingEvent;
import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler;
import dk.statsbiblioteket.util.Strings;
import dk.statsbiblioteket.util.console.ProcessRunner;
import dk.statsbiblioteket.util.xml.DOM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class JpylyzerValidatorEventHandler
implements TreeEventHandler {
public static final String CONTENTS = "/contents";
private final String scratchFolder;
/** Logger */
private final Logger log = LoggerFactory.getLogger(JpylyzerValidatorEventHandler.class);
/** The result collector results are collected in. */
private final ResultCollector resultCollector;
private Validator validator;
private boolean isInDataFile;
private String datafile;
private boolean atNinestars = false;
private String jpylyzerPath;
public JpylyzerValidatorEventHandler(String scratchFolder,
ResultCollector resultCollector,
String controlPoliciesPath,
String jpylyzerPath)
throws
FileNotFoundException {
this.scratchFolder = scratchFolder;
this.resultCollector = resultCollector;
this.jpylyzerPath = jpylyzerPath;
Document controlPoliciesDocument;
if (controlPoliciesPath != null) {
controlPoliciesDocument = DOM.streamToDOM(new FileInputStream(controlPoliciesPath));
} else {
controlPoliciesDocument = DOM.streamToDOM(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("defaultControlPolicies.xml"));
}
if (this.jpylyzerPath == null) {
this.jpylyzerPath = "src/main/extras/jpylyzer-1.10.1/jpylyzer.py";
}
validator = new ValidatorFactory(controlPoliciesDocument).createValidator();
}
public JpylyzerValidatorEventHandler(String scratchFolder,
ResultCollector resultCollector,
String controlPoliciesPath,
String jpylyzerPath,
boolean atNinestars)
throws
FileNotFoundException {
this(scratchFolder, resultCollector, controlPoliciesPath, jpylyzerPath);
this.atNinestars = atNinestars;
}
@Override
public void handleNodeBegin(NodeBeginsParsingEvent event) {
if (event instanceof DataFileNodeBeginsParsingEvent) {
isInDataFile = true;
datafile = event.getName();
}
}
@Override
public void handleNodeEnd(NodeEndParsingEvent event) {
if (event instanceof DataFileNodeEndsParsingEvent) {
isInDataFile = false;
datafile = null;
}
}
@Override
public void handleAttribute(AttributeParsingEvent event) {
try {
if (isInDataFile) {
if (event.getName().endsWith(CONTENTS)) {
log.debug("Encountered event {}",event.getName());
if (atNinestars) {
File filePath = new File(scratchFolder, datafile);
InputStream jpylizerOutput = jpylize(filePath);
validator.validate(datafile, Strings.flush(jpylizerOutput), resultCollector);
}
} else {
if (event.getName().endsWith("jpylizer.xml")) {
validator.validate(datafile, Strings.flush(event.getData()), resultCollector);
}
}
}
} catch (IOException e) {
//TODO map exception to resultCollector
}
}
@Override
public void handleFinish() {
//Anything to do here?
}
private InputStream jpylize(File dataPath) {
log.info("Running jpylyzer on file {}", dataPath);
ProcessRunner runner = new ProcessRunner(jpylyzerPath, dataPath.getAbsolutePath());
runner.setOutputCollectionByteSize(Integer.MAX_VALUE);
runner.run();
if (runner.getReturnCode() == 0) {
return runner.getProcessOutput();
} else {
throw new RuntimeException(
"failed to run jpylyzer, returncode:" + runner.getReturnCode() + ", stdOut:" + runner
.getProcessOutputAsString() + " stdErr:" + runner.getProcessErrorAsString());
}
}
}
|
package org.mtransit.parser.ca_moncton_codiac_transpo_bus;
import static org.mtransit.commons.RegexUtils.DIGITS;
import static org.mtransit.commons.StringUtils.EMPTY;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mtransit.commons.CharUtils;
import org.mtransit.commons.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.MTLog;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRouteSNToIDConverter;
import org.mtransit.parser.mt.data.MTrip;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MonctonCodiacTranspoBusAgencyTools extends DefaultAgencyTools {
public static void main(@NotNull String[] args) {
new MonctonCodiacTranspoBusAgencyTools().start(args);
}
@Nullable
@Override
public List<Locale> getSupportedLanguages() {
return LANG_EN_FR;
}
@Override
public boolean defaultExcludeEnabled() {
return true;
}
@NotNull
@Override
public String getAgencyName() {
return "Codiac Transpo";
}
@NotNull
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
@Override
public boolean defaultRouteIdEnabled() {
return true;
}
@Override
public boolean useRouteShortNameForRouteId() {
return true;
}
private static final long RID_ENDS_WITH_C1 = MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.other(0L));
private static final long RID_ENDS_WITH_C2 = MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.other(1L));
private static final long RID_ENDS_WITH_LT = MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.other(2L));
private static final long RID_ENDS_WITH_LTS = MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.other(3L));
private static final String C1 = "c1";
private static final String C2 = "c2";
private static final String LT = "lt";
private static final String LTS = "lts";
private static final long RID_MM = 99_000L;
private static final long RID_METS = 99_001L;
private static final String MM_RID = "MM";
private static final String METS_RID = "METS";
@Nullable
@Override
public Long convertRouteIdFromShortNameNotSupported(@NotNull String routeShortName) {
switch (routeShortName) {
case MM_RID:
return RID_MM;
case METS_RID:
return RID_METS;
}
return super.convertRouteIdFromShortNameNotSupported(routeShortName);
}
@Nullable
@Override
public Long convertRouteIdNextChars(@NotNull String nextChars) {
switch (nextChars) {
case LTS:
return RID_ENDS_WITH_LTS;
case LT:
return RID_ENDS_WITH_LT;
case C1:
return RID_ENDS_WITH_C1;
case C2:
return RID_ENDS_WITH_C2;
}
return super.convertRouteIdNextChars(nextChars);
}
@Override
public boolean defaultAgencyColorEnabled() {
return true;
}
private static final String AGENCY_COLOR_GREEN = "005238"; // GREEN (from PDF)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@NotNull
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public boolean defaultRouteLongNameEnabled() {
return true;
}
@Nullable
@Override
public String provideMissingRouteColor(@NotNull GRoute gRoute) {
final long routeId = getRouteId(gRoute);
switch ((int) routeId) {
// @formatter:off
case 50: return "ED1D24";
case 51: return "00A651";
case 52: return "0072BC";
case 60: return "E977AF";
case 61: return "684287";
case 62: return "DC62A4";
case 63: return "F7941E";
case 64: return "A6664C";
case 65: return "FBAF34";
case 66: return "65A6BB";
case 67: return "2E3092";
case 68: return "00AEEF";
case 70: return "3EC7F4";
case 71: return "8DC63F";
case 72: return "8DC63F";
case 73: return "6A3B0C";
case 75: return "732600";
case 80: return "CF8B2D";
case 81: return "942976";
case 82: return "FDCC08";
case 83: return "B63030";
case 93: return "8FB73E";
case 94: return "41827C";
case 95: return "F58473";
case 939495: return null; // agency color
// @formatter:on
}
if (RID_MM == routeId) {
return null; // agency color
} else if (RID_METS == routeId) { // METS
return null; // agency color
} else if (60L + RID_ENDS_WITH_LT == routeId) {
return "E977AF"; // same as 60
} else if (60L + RID_ENDS_WITH_LTS == routeId) {
return "E977AF"; // same as 60
} else if (60_67L + MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.C) == routeId) { // 6067C
return null; // agency color
} else if (61L + MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.B) == routeId) { // 61B
return "B0A0C5";
} else if (6851L + MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.D) == routeId) { // 6851D
return null;
} else if (80_81L + RID_ENDS_WITH_C1 == routeId) { // 8081C1
return null; // agency color
} else if (80_81L + RID_ENDS_WITH_C2 == routeId) { // 8081C2
return null; // agency color
} else if (81L + MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.S) == routeId) { // 81S
return "942976"; // same as 81
} else if (93L + MRouteSNToIDConverter.endsWith(MRouteSNToIDConverter.A) == routeId) { // 93A
return "A94D3F"; // same as 93
}
throw new MTLog.Fatal("Unexpected route color for %s!", gRoute.toStringPlus());
}
@Override
public boolean directionFinderEnabled() {
return true;
}
@NotNull
@Override
public List<Integer> getDirectionTypes() {
return Arrays.asList(
MTrip.HEADSIGN_TYPE_DIRECTION,
MTrip.HEADSIGN_TYPE_STRING
);
}
@NotNull
@Override
public String cleanDirectionHeadsign(boolean fromStopName, @NotNull String directionHeadSign) {
directionHeadSign = super.cleanDirectionHeadsign(fromStopName, directionHeadSign);
directionHeadSign = CleanUtils.cleanBounds(directionHeadSign); // only kept EN for now
return directionHeadSign;
}
private static final Pattern AVENIR_CENTER_ = CleanUtils.cleanWords("Avenir Centre Avenir");
private static final String AVENIR_CENTER_REPLACEMENT = CleanUtils.cleanWordsReplacement("Avenir Ctr");
private static final Pattern CF_CHAMPLAIN_ = CleanUtils.cleanWords("cf champlaim");
private static final String CF_CHAMPLAIN_REPLACEMENT = CleanUtils.cleanWordsReplacement("CF Champlain");
private static final Pattern NORTH_PLAZA_ = CleanUtils.cleanWords("north plaza nord", "north plz nord");
private static final String NORTH_PLAZA_REPLACEMENT = CleanUtils.cleanWordsReplacement("North Plz");
private static final Pattern SOUTH_PLAZA_ = CleanUtils.cleanWords("south plaza sud", "south plz sud");
private static final String SOUTH_PLAZA_REPLACEMENT = CleanUtils.cleanWordsReplacement("South Plz");
private static final Pattern WEST_MONCTON_ = CleanUtils.cleanWord("west Moncton ouest");
private static final String WEST_MONCTON_REPLACEMENT = CleanUtils.cleanWordsReplacement("West Moncton");
private static final Pattern EAST_MONCTON_ = CleanUtils.cleanWord("east Moncton est");
private static final String EAST_MONCTON_REPLACEMENT = CleanUtils.cleanWordsReplacement("East Moncton");
private static final Pattern COLISEUM_ = Pattern.compile("(coliseum - colisée)", Pattern.CASE_INSENSITIVE);
private static final String COLISEUM_REPLACEMENT = "Coliseum"; // FIXME support for head-sign string i18n
private static final Pattern HOSP_ = Pattern.compile("(hospitals - hôpitaux)", Pattern.CASE_INSENSITIVE);
private static final String HOSP_REPLACEMENT = "Hospitals"; // FIXME support for head-sign string i18n
private static final Pattern STARTS_W_SHUTTLE_FOR_ = Pattern.compile("(^shuttle for )", Pattern.CASE_INSENSITIVE);
@NotNull
@Override
public String cleanTripHeadsign(@NotNull String tripHeadsign) {
tripHeadsign = AVENIR_CENTER_.matcher(tripHeadsign).replaceAll(AVENIR_CENTER_REPLACEMENT);
tripHeadsign = CF_CHAMPLAIN_.matcher(tripHeadsign).replaceAll(CF_CHAMPLAIN_REPLACEMENT);
tripHeadsign = WEST_MONCTON_.matcher(tripHeadsign).replaceAll(WEST_MONCTON_REPLACEMENT);
tripHeadsign = EAST_MONCTON_.matcher(tripHeadsign).replaceAll(EAST_MONCTON_REPLACEMENT);
tripHeadsign = NORTH_PLAZA_.matcher(tripHeadsign).replaceAll(NORTH_PLAZA_REPLACEMENT);
tripHeadsign = SOUTH_PLAZA_.matcher(tripHeadsign).replaceAll(SOUTH_PLAZA_REPLACEMENT);
tripHeadsign = COLISEUM_.matcher(tripHeadsign).replaceAll(COLISEUM_REPLACEMENT);
tripHeadsign = HOSP_.matcher(tripHeadsign).replaceAll(HOSP_REPLACEMENT);
tripHeadsign = STARTS_W_SHUTTLE_FOR_.matcher(tripHeadsign).replaceAll(EMPTY);
tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
private static final Pattern UNIVERSITY_ENCODING = Pattern.compile("((^|\\W)(universit)(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_ENCODING_REPLACEMENT = "$2" + "University" + "$4";
private static final Pattern ADELARD_ENCODING = Pattern.compile("((^|\\W)(adlard)(\\W|$))", Pattern.CASE_INSENSITIVE);
private static final String ADELARD_ENCODING_REPLACEMENT = "$2" + "Adelard" + "$4";
@NotNull
@Override
public String cleanStopName(@NotNull String gStopName) {
gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT);
gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT);
gStopName = UNIVERSITY_ENCODING.matcher(gStopName).replaceAll(UNIVERSITY_ENCODING_REPLACEMENT);
gStopName = ADELARD_ENCODING.matcher(gStopName).replaceAll(ADELARD_ENCODING_REPLACEMENT);
gStopName = CleanUtils.cleanSlashes(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public int getStopId(@NotNull GStop gStop) {
final String stopCode = gStop.getStopCode();
if (stopCode.length() > 0 && CharUtils.isDigitsOnly(stopCode)) {
return Integer.parseInt(stopCode);
}
final Matcher matcher = DIGITS.matcher(stopCode);
if (matcher.find()) {
final int digits = Integer.parseInt(matcher.group());
//noinspection ConstantConditions
if (true) { // LIKE BEFORE
return 6_810_000 + digits;
}
if (stopCode.startsWith("D")) {
return 40_000 + digits;
} else if (stopCode.startsWith("M")) {
return 130_000 + digits;
} else if (stopCode.startsWith("R")) {
return 180_000 + digits;
}
}
throw new MTLog.Fatal("Unexpected stop ID for %s!", gStop);
}
}
|
package com.twelvemonkeys.imageio.stream;
import com.twelvemonkeys.lang.Validate;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageInputStreamImpl;
import java.io.IOException;
// TODO: Create a provider for this (wrapping the FileIIS and FileCacheIIS classes), and disable the Sun built-in spis?
// TODO: Test on other platforms, might be just an OS X issue
public final class BufferedImageInputStream extends ImageInputStreamImpl implements ImageInputStream {
static final int DEFAULT_BUFFER_SIZE = 8192;
private ImageInputStream mStream;
private byte[] mBuffer;
private long mBufferStart = 0;
private int mBufferPos = 0;
private int mBufferLength = 0;
public BufferedImageInputStream(final ImageInputStream pStream) throws IOException {
this(pStream, DEFAULT_BUFFER_SIZE);
}
private BufferedImageInputStream(final ImageInputStream pStream, final int pBufferSize) throws IOException {
Validate.notNull(pStream, "stream");
mStream = pStream;
streamPos = pStream.getStreamPosition();
mBuffer = new byte[pBufferSize];
}
private void fillBuffer() throws IOException {
mBufferStart = streamPos;
mBufferLength = mStream.read(mBuffer, 0, mBuffer.length);
mBufferPos = 0;
}
private boolean isBufferValid() throws IOException {
return mBufferPos < mBufferLength && mBufferStart == mStream.getStreamPosition() - mBufferLength;
}
@Override
public int read() throws IOException {
if (!isBufferValid()) {
fillBuffer();
}
if (mBufferLength <= 0) {
return -1;
}
bitOffset = 0;
streamPos++;
return mBuffer[mBufferPos++] & 0xff;
}
@Override
public int read(final byte[] pBuffer, final int pOffset, final int pLength) throws IOException {
bitOffset = 0;
if (!isBufferValid()) {
// Bypass cache if cache is empty for reads longer than buffer
if (pLength >= mBuffer.length) {
return readDirect(pBuffer, pOffset, pLength);
}
else {
fillBuffer();
}
}
return readBuffered(pBuffer, pOffset, pLength);
}
private int readDirect(final byte[] pBuffer, final int pOffset, final int pLength) throws IOException {
// TODO: Figure out why reading more than the buffer length causes alignment issues...
int read = mStream.read(pBuffer, pOffset, Math.min(mBuffer.length, pLength));
if (read > 0) {
streamPos += read;
}
mBufferStart = mStream.getStreamPosition();
mBufferLength = 0;
return read;
}
private int readBuffered(final byte[] pBuffer, final int pOffset, final int pLength) {
if (mBufferLength <= 0) {
return -1;
}
// Read as much as possible from buffer
int length = Math.min(mBufferLength - mBufferPos, pLength);
if (length > 0) {
System.arraycopy(mBuffer, mBufferPos, pBuffer, pOffset, length);
mBufferPos += length;
}
streamPos += length;
return length;
}
@Override
public void seek(long pPosition) throws IOException {
// TODO: Could probably be optimized to not invalidate buffer if new position is within current buffer
mStream.seek(pPosition);
mBufferLength = 0; // Will invalidate buffer
streamPos = mStream.getStreamPosition();
}
@Override
public void flushBefore(long pos) throws IOException {
mStream.flushBefore(pos);
}
@Override
public long getFlushedPosition() {
return mStream.getFlushedPosition();
}
@Override
public boolean isCached() {
return mStream.isCached();
}
@Override
public boolean isCachedMemory() {
return mStream.isCachedMemory();
}
@Override
public boolean isCachedFile() {
return mStream.isCachedFile();
}
@Override
public void close() throws IOException {
if (mStream != null) {
mStream.close();
mStream = null;
mBuffer = null;
}
super.close();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
@Override
public long length() {
// WTF?! This method is allowed to throw IOException in the interface...
try {
return mStream.length();
}
catch (IOException e) {
throw unchecked(e, RuntimeException.class);
}
}
@SuppressWarnings({"unchecked", "UnusedDeclaration"})
private <T extends Throwable> T unchecked(IOException pExcption, Class<T> pClass) {
// Ugly hack to fool the compiler..
return (T) pExcption;
}
}
|
package com.sdl.dxa.modules.ish.controller;
import com.google.common.base.Strings;
import com.sdl.dxa.modules.ish.exception.IshExceptionHandler;
import com.sdl.dxa.modules.ish.exception.IshServiceException;
import com.sdl.dxa.modules.ish.model.ErrorMessage;
import com.sdl.dxa.modules.ish.model.Publication;
import com.sdl.dxa.modules.ish.providers.PublicationService;
import com.sdl.dxa.modules.ish.providers.TocService;
import com.sdl.dxa.modules.ish.localization.IshLocalization;
import com.sdl.dxa.modules.ish.providers.ConditionService;
import com.sdl.dxa.modules.ish.providers.TridionDocsContentService;
import com.sdl.webapp.common.api.WebRequestContext;
import com.sdl.webapp.common.api.content.ContentProviderException;
import com.sdl.webapp.common.api.content.StaticContentItem;
import com.sdl.webapp.common.api.formats.DataFormatter;
import com.sdl.webapp.common.api.model.PageModel;
import com.sdl.webapp.common.api.model.entity.SitemapItem;
import com.sdl.webapp.common.controller.exception.NotFoundException;
import com.tridion.ambientdata.web.WebContext;
import com.tridion.meta.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
/**
* Controller for Ish Module.
*/
@Slf4j
@Controller
public class IshController {
private static final URI USER_CONDITIONS_URI = URI.create("taf:ish:userconditions");
@Autowired
private WebRequestContext webRequestContext;
@Autowired
private DataFormatter dataFormatters;
@Autowired
private PublicationService publicationService;
@Autowired
private IshExceptionHandler exceptionHandler;
@Autowired
private TocService tocService;
@Autowired
private TridionDocsContentService tridionDocsContentService;
@Autowired
private ConditionService conditionService;
/**
* Get page model using the json format.
*
* @param publicationId Publication id
* @param pageId Page id
* @param request Http request
* @return Page model using the json format.
* @throws ContentProviderException
*/
/**
* Get binary data.
*
* @param publicationId Publication id
* @param binaryId Binary id
* @return Binary data using a stream.
* @throws ContentProviderException
* @throws IOException
*/
/**
* Get list of publications using the json format.
*
* @return Publications list using the json format.
* @throws IshServiceException
*/
@RequestMapping(method = GET, value = "/api/publications", produces = {APPLICATION_JSON_VALUE})
@ResponseBody
public List<Publication> getPublicationList() throws IshServiceException {
return publicationService.getPublicationList();
}
@RequestMapping(method = {GET, POST}, value = "/api/toc/{publicationId}", produces = {APPLICATION_JSON_VALUE})
@ResponseBody
public Collection<SitemapItem> getRootToc(@PathVariable("publicationId") Integer publicationId,
@RequestParam(value = "conditions", defaultValue = "") String conditions,
HttpServletRequest request) {
publicationService.checkPublicationOnline(publicationId);
if (!conditions.isEmpty()) {
WebContext.getCurrentClaimStore().put(USER_CONDITIONS_URI, conditions);
}
return tocService.getToc(publicationId, null, false, 1, request, webRequestContext);
}
@RequestMapping(method = {GET, POST}, value = "/api/toc/{publicationId}/{sitemapItemId}",
produces = {APPLICATION_JSON_VALUE})
@ResponseBody
public Collection<SitemapItem> getToc(@PathVariable("publicationId") Integer publicationId,
@PathVariable("sitemapItemId") String sitemapItemId,
@RequestParam(value = "includeAncestors", required = false,
defaultValue = "false") boolean includeAncestors,
@RequestParam(value = "conditions", defaultValue = "") String conditions,
HttpServletRequest request) {
publicationService.checkPublicationOnline(publicationId);
if (!conditions.isEmpty()) {
WebContext.getCurrentClaimStore().put(USER_CONDITIONS_URI, conditions);
}
return tocService.getToc(publicationId, sitemapItemId, includeAncestors, 1, request,
webRequestContext);
}
@RequestMapping(method = GET, value = "/api/conditions/{publicationId:[\\d]+}", produces = {APPLICATION_JSON_VALUE})
@ResponseBody
public String getPublicationConditions(@PathVariable("publicationId") Integer publicationId) {
return conditionService.getConditions(publicationId).toString();
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
ResponseEntity<ErrorMessage> handleException(Exception ex) {
ErrorMessage message = exceptionHandler.handleException(ex);
return new ResponseEntity(message, message.getHttpStatus());
}
/**
* Get page model using the json format by given criteria.
* As a criteria you may use any metadata field with given value.
* It looks for page in given publication which meets criteria
*
* @param publicationId target Publication id where we have to fetch Page Id (aka topic id)
* @param ishFieldValue Value of meta field 'ishlogicalref.object.id'
* which is reference number of topic. This reference is common for a topic,
* which is used in different publications
* @return Integer pageId of a topic in target publication
* @throws ContentProviderException
*/
@RequestMapping(method = {GET, POST}, value = "/api/pageIdByReference/{publicationId}/{ishFieldValue}",
produces = {APPLICATION_JSON_VALUE})
@ResponseBody
public Item getTopicIdInTargetPublication(@PathVariable("publicationId") Integer publicationId,
@PathVariable("ishFieldValue") String ishFieldValue)
throws ContentProviderException {
publicationService.checkPublicationOnline(publicationId);
if (Strings.isNullOrEmpty(ishFieldValue)) {
throw new NotFoundException("Unable to use empty 'ishlogicalref.object.id' value as a search criteria");
}
return tridionDocsContentService.getPageIdByIshLogicalReference(publicationId, ishFieldValue);
}
}
|
package info.bitrich.xchangestream.coinmate.v2;
import info.bitrich.xchangestream.core.StreamingExchange;
import info.bitrich.xchangestream.core.StreamingExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.currency.CurrencyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoinmateManualExample {
private static final Logger LOG = LoggerFactory.getLogger(CoinmateStreamingExchange.class);
public static void main(String[] args) {
ExchangeSpecification exSpec = new CoinmateStreamingExchange().getDefaultExchangeSpecification();
StreamingExchange exchange =
StreamingExchangeFactory.INSTANCE.createExchange(exSpec);
exchange.connect().blockingAwait();
exchange
.getStreamingMarketDataService()
.getOrderBook(CurrencyPair.BTC_EUR)
.subscribe(orderBook -> {
LOG.info("Ask: {}", orderBook.getAsks().get(0));
LOG.info("Bid: {}", orderBook.getBids().get(0));
});
exchange
.getStreamingMarketDataService()
.getTrades(CurrencyPair.BTC_USD).subscribe(trade -> {
LOG.info("Trade {}", trade);
});
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package be.ibridge.kettle.core.database;
import java.io.StringReader;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import org.eclipse.core.runtime.IProgressMonitor;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.Counter;
import be.ibridge.kettle.core.DBCache;
import be.ibridge.kettle.core.DBCacheEntry;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.Result;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleDatabaseBatchException;
import be.ibridge.kettle.core.exception.KettleDatabaseException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta;
/**
* Database handles the process of connecting to, reading from, writing to and updating databases.
* The database specific parameters are defined in DatabaseInfo.
*
* @author Matt
* @since 05-04-2003
*
*/
public class Database
{
private DatabaseMeta databaseMeta;
private int rowlimit;
private int commitsize;
private Connection connection;
private Statement sel_stmt;
private PreparedStatement pstmt;
private PreparedStatement prepStatementLookup;
private PreparedStatement prepStatementUpdate;
private PreparedStatement prepStatementInsert;
private PreparedStatement pstmt_pun;
private PreparedStatement pstmt_dup;
private PreparedStatement pstmt_seq;
private CallableStatement cstmt;
private ResultSetMetaData rsmd;
private DatabaseMetaData dbmd;
private Row rowinfo;
private int written;
private LogWriter log;
/**
* Counts the number of rows written to a batch.
*/
private int batchCounter;
/**
* Construnct a new Database Connection
* @param inf The Database Connection Info to construct the connection with.
*/
public Database(DatabaseMeta inf)
{
log=LogWriter.getInstance();
databaseMeta = inf;
pstmt = null;
rsmd = null;
rowinfo = null;
dbmd = null;
rowlimit=0;
written=0;
log.logDetailed(toString(), "New database connection defined");
}
/**
* @return Returns the connection.
*/
public Connection getConnection()
{
return connection;
}
/**
* Set the maximum number of records to retrieve from a query.
* @param rows
*/
public void setQueryLimit(int rows)
{
rowlimit = rows;
}
/**
* @return Returns the prepStatementInsert.
*/
public PreparedStatement getPrepStatementInsert()
{
return prepStatementInsert;
}
/**
* @return Returns the prepStatementLookup.
*/
public PreparedStatement getPrepStatementLookup()
{
return prepStatementLookup;
}
/**
* @return Returns the prepStatementUpdate.
*/
public PreparedStatement getPrepStatementUpdate()
{
return prepStatementUpdate;
}
/**
* Open the database connection.
* @throws KettleDatabaseException if something went wrong.
*/
public void connect()
throws KettleDatabaseException
{
try
{
if (databaseMeta!=null)
{
connect(databaseMeta.getDriverClass());
log.logDetailed(toString(), "Connected to database.");
}
else
{
throw new KettleDatabaseException("No valid database connection defined!");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Error occured while trying to connect to the database", e);
}
}
/**
* Connect using the correct classname
* @param classname for example "org.gjt.mm.mysql.Driver"
* @return true if the connect was succesfull, false if something went wrong.
*/
private void connect(String classname)
throws KettleDatabaseException
{
// Install and load the jdbc Driver
try
{
Class.forName(classname);
}
catch(NoClassDefFoundError e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(ClassNotFoundException e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
catch(Exception e)
{
throw new KettleDatabaseException("Exception while loading class", e);
}
try
{
connection = DriverManager.getConnection(databaseMeta.getURL(), databaseMeta.getUsername(), databaseMeta.getPassword());
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
catch(Throwable e)
{
throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e);
}
}
/**
* Disconnect from the database and close all open prepared statements.
*/
public void disconnect()
{
try
{
if (connection==null) return ; // Nothing to do...
if (connection.isClosed()) return ; // Nothing to do...
if (!isAutoCommit()) commit();
if (pstmt !=null) { pstmt.close(); pstmt=null; }
if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; }
if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; }
if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; }
if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; }
if (connection !=null) { connection.close(); connection=null; }
log.logDetailed(toString(), "Connection to database closed!");
}
catch(SQLException ex)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage());
}
catch(KettleDatabaseException dbe)
{
log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage());
}
}
public void cancelQuery() throws KettleDatabaseException
{
try
{
if (pstmt !=null)
{
pstmt.cancel();
}
if (sel_stmt !=null)
{
sel_stmt.cancel();
}
log.logDetailed(toString(), "Open query canceled!");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error cancelling query", ex);
}
}
/**
* Specify after how many rows a commit needs to occur when inserting or updating values.
* @param commsize The number of rows to wait before doing a commit on the connection.
*/
public void setCommit(int commsize)
{
commitsize=commsize;
String onOff = (commitsize<=0?"on":"off");
try
{
connection.setAutoCommit(commitsize<=0);
log.logDetailed(toString(), "Auto commit "+onOff);
}
catch(Exception e)
{
log.logError(toString(), "Can't turn auto commit "+onOff);
}
}
/**
* Perform a commit the connection if this is supported by the database
*/
public void commit()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.commit();
}
else
{
log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]");
}
}
catch(Exception e)
{
if (databaseMeta.supportsEmptyTransactions()) // TODO: find a way to examine the exact error thrown, in case it's -255: ignore, everything else: report
throw new KettleDatabaseException("Error comitting connection", e);
}
}
public void rollback()
throws KettleDatabaseException
{
try
{
if (getDatabaseMetaData().supportsTransactions())
{
connection.rollback();
}
else
{
log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]");
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error performing rollback on connection", e);
}
}
/**
* Prepare inserting values into a table, using the fields & values in a Row
* @param r The row to determine which values need to be inserted
* @param table The name of the table in which we want to insert rows
* @throws KettleDatabaseException if something went wrong.
*/
public void prepareInsert(Row r, String table)
throws KettleDatabaseException
{
if (r.size()==0)
{
throw new KettleDatabaseException("No fields in row, can't insert!");
}
String ins = getInsertStatement(table, r);
log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins);
prepStatementInsert=prepareSQL(ins);
}
/**
* Prepare a statement to be executed on the database.
* @param sql The SQL to be prepared
* @return The PreparedStatement object.
* @throws KettleDatabaseException
*/
public PreparedStatement prepareSQL(String sql)
throws KettleDatabaseException
{
try
{
return connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex);
}
}
public void closeLookup() throws KettleDatabaseException
{
closePreparedStatement(pstmt);
}
public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException
{
if (ps!=null)
{
try
{
ps.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing prepared statement", e);
}
}
}
public void closeInsert() throws KettleDatabaseException
{
if (prepStatementInsert!=null)
{
try
{
prepStatementInsert.close();
prepStatementInsert = null;
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing insert prepared statement.", e);
}
}
}
public void closeUpdate() throws KettleDatabaseException
{
if (prepStatementUpdate!=null)
{
try
{
prepStatementUpdate.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing update prepared statement.", e);
}
}
}
public void setValues(Row r)
throws KettleDatabaseException
{
setValues(r, pstmt);
}
public void setValuesInsert(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementInsert);
}
public void setValuesUpdate(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementUpdate);
}
public void setValuesLookup(Row r)
throws KettleDatabaseException
{
setValues(r, prepStatementLookup);
}
public void setProcValues(Row r, int argnrs[], String argdir[], boolean result)
throws KettleDatabaseException
{
int i;
int pos;
if (result) pos=2; else pos=1;
for (i=0;i<argnrs.length;i++)
{
if (argdir[i].equalsIgnoreCase("IN"))
{
Value v=r.getValue(argnrs[i]);
setValue(cstmt, v, pos);
pos++;
}
}
}
public void setValue(PreparedStatement ps, Value v, int pos)
throws KettleDatabaseException
{
String debug = "";
try
{
switch(v.getType())
{
case Value.VALUE_TYPE_BIGNUMBER:
debug="BigNumber";
if (!v.isNull())
{
ps.setBigDecimal(pos, v.getBigNumber());
}
else
{
ps.setNull(pos, java.sql.Types.DECIMAL);
}
break;
case Value.VALUE_TYPE_NUMBER :
debug="Number";
if (!v.isNull())
{
double num = v.getNumber();
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
num = Const.round(num, v.getPrecision());
}
ps.setDouble(pos, num);
}
else
{
ps.setNull(pos, java.sql.Types.DOUBLE);
}
break;
case Value.VALUE_TYPE_INTEGER:
debug="Integer";
if (!v.isNull())
{
if (databaseMeta.supportsSetLong())
{
ps.setLong(pos, Math.round( v.getNumber() ) );
}
else
{
if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0)
{
ps.setDouble(pos, v.getNumber() );
}
else
{
ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) );
}
}
}
else
{
ps.setNull(pos, java.sql.Types.BIGINT);
}
break;
case Value.VALUE_TYPE_STRING :
debug="String";
if (v.getLength()<DatabaseMeta.CLOB_LENGTH)
{
if (!v.isNull() && v.getString()!=null)
{
ps.setString(pos, v.getString());
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
else
{
if (!v.isNull())
{
int maxlen = databaseMeta.getMaxTextFieldLength();
int len = v.getStringLength();
// Take the last maxlen characters of the string...
int begin = len - maxlen;
if (begin<0) begin=0;
// Get the substring!
String logging = v.getString().substring(begin);
if (databaseMeta.supportsSetCharacterStream())
{
StringReader sr = new StringReader(logging);
ps.setCharacterStream(pos, sr, logging.length());
}
else
{
ps.setString(pos, logging);
}
}
else
{
ps.setNull(pos, java.sql.Types.VARCHAR);
}
}
break;
case Value.VALUE_TYPE_DATE :
debug="Date";
if (!v.isNull() && v.getDate()!=null)
{
long dat = v.getDate().getTime();
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
// Convert to DATE!
java.sql.Date ddate = new java.sql.Date(dat);
ps.setDate(pos, ddate);
}
else
{
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
ps.setTimestamp(pos, sdate);
}
}
else
{
if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion())
{
ps.setNull(pos, java.sql.Types.DATE);
}
else
{
ps.setNull(pos, java.sql.Types.TIME);
}
}
break;
case Value.VALUE_TYPE_BOOLEAN:
debug="Boolean";
if (databaseMeta.supportsBooleanDataType())
{
if (!v.isNull())
{
ps.setBoolean(pos, v.getBoolean());
}
else
{
ps.setNull(pos, java.sql.Types.BOOLEAN);
}
}
else
{
if (!v.isNull())
{
ps.setString(pos, v.getBoolean()?"Y":"N");
}
else
{
ps.setNull(pos, java.sql.Types.CHAR);
}
}
break;
default:
debug="default";
break;
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e);
}
}
// Sets the values of the preparedStatement pstmt.
public void setValues(Row r, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
//System.out.println("Setting value ["+v+"] on preparedStatement, position="+i);
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("offending row : "+r, e);
}
}
}
public void setDimValues(Row r, Value dateval)
throws KettleDatabaseException
{
setDimValues(r, dateval, prepStatementLookup);
}
// Sets the values of the preparedStatement pstmt.
public void setDimValues(Row r, Value dateval, PreparedStatement ps)
throws KettleDatabaseException
{
int i;
Value v;
long dat;
// now set the values in the row!
for (i=0;i<r.size();i++)
{
v=r.getValue(i);
try
{
setValue(ps, v, i+1);
}
catch(KettleDatabaseException e)
{
throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e);
}
}
if (dateval!=null && dateval.getDate()!=null && !dateval.isNull())
{
dat = dateval.getDate().getTime();
}
else
{
Calendar cal=Calendar.getInstance(); // use system date!
dat = cal.getTime().getTime();
}
java.sql.Timestamp sdate = new java.sql.Timestamp(dat);
try
{
ps.setTimestamp(r.size()+1, sdate); // ? > date_from
ps.setTimestamp(r.size()+2, sdate); // ? <= date_to
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex);
}
}
public void dimUpdate(Row row,
String table,
String fieldlookup[],
int fieldnrs[],
String returnkey,
Value dimkey
)
throws KettleDatabaseException
{
int i;
if (pstmt_dup==null) // first time: construct prepared statement
{
// Construct the SQL statement...
/*
* UPDATE d_customer
* SET fieldlookup[] = row.getValue(fieldnrs)
* WHERE returnkey = dimkey
* ;
*/
String sql="UPDATE "+table+Const.CR+"SET ";
for (i=0;i<fieldlookup.length;i++)
{
if (i>0) sql+=", "; else sql+=" ";
sql+=fieldlookup[i]+" = ?"+Const.CR;
}
sql+="WHERE "+returnkey+" = ?";
try
{
log.logDebug(toString(), "Preparing statement: ["+sql+"]");
pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Coudln't prepare statement :"+Const.CR+sql, ex);
}
}
// Assemble information
// New
Row rupd=new Row();
for (i=0;i<fieldnrs.length;i++)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
rupd.addValue( dimkey );
setValues(rupd, pstmt_dup);
insertRow(pstmt_dup);
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
public void dimInsert(Row row,
String table,
boolean newentry,
String keyfield,
boolean autoinc,
Value technicalKey,
String versionfield,
Value val_version,
String datefrom,
Value val_datfrom,
String dateto,
Value val_datto,
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[])
* VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
if (!autoinc) sql+=keyfield+", "; // NO AUTOINCREMENT
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix!
sql+=versionfield+", "+datefrom+", "+dateto;
for (i=0;i<keylookup.length;i++)
{
sql+=", "+keylookup[i];
}
for (i=0;i<fieldlookup.length;i++)
{
sql+=", "+fieldlookup[i];
}
sql+=") VALUES(";
if (!autoinc) sql+="?, ";
sql+="?, ?, ?";
for (i=0;i<keynrs.length;i++)
{
sql+=", ?";
}
for (i=0;i<fieldnrs.length;i++)
{
sql+=", ?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL=["+sql+"]");
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
//pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } );
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex);
}
/*
* UPDATE d_customer
* SET dateto = val_datnow
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
String sql_upd="UPDATE "+table+Const.CR+"SET "+dateto+" = ?"+Const.CR;
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
sql_upd+="AND "+versionfield+" = ? ";
try
{
log.logDetailed(toString(), "Preparing update: "+Const.CR+sql+Const.CR);
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(technicalKey);
if (!newentry)
{
Value val_new_version = new Value(val_version);
val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version
rins.addValue(val_new_version);
}
else
{
rins.addValue(val_version);
}
rins.addValue(val_datfrom);
rins.addValue(val_datto);
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
for (i=0;i<fieldnrs.length;i++)
{
Value val = row.getValue(fieldnrs[i]);
rins.addValue( val );
}
log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
log.logDebug(toString(), "Row inserted!");
if (keyfield==null)
{
try
{
ResultSet keys=prepStatementInsert.getGeneratedKeys(); // 1 key
if (keys.next()) technicalKey.setValue(keys.getLong(1));
else
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield+", no fields in resultset.");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve technical key value from auto-increment field : "+keyfield, ex);
}
}
if (!newentry) // we have to update the previous version in the dimension!
{
/*
* UPDATE d_customer
* SET dateto = val_datfrom
* WHERE keylookup[] = keynrs[]
* AND versionfield = val_version - 1
* ;
*/
Row rupd = new Row();
rupd.addValue(val_datfrom);
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
rupd.addValue(val_version);
log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString());
// UPDATE VALUES
setValues(rupd, prepStatementUpdate); // set values for update
log.logDebug(toString(), "Values set for update ("+rupd.size()+")");
insertRow(prepStatementUpdate); // do the actual update
log.logDebug(toString(), "Row updated!");
}
}
// This updates all versions of a dimension entry.
public void dimPunchThrough(Row row,
String table,
int fieldupdate[],
String fieldlookup[],
int fieldnrs[],
String key[],
String keylookup[],
int keynrs[]
)
throws KettleDatabaseException
{
int i;
boolean first;
if (pstmt_pun==null) // first time: construct prepared statement
{
/*
* UPDATE table
* SET punchv1 = fieldx, ...
* WHERE keylookup[] = keynrs[]
* ;
*/
String sql_upd="UPDATE "+table+Const.CR;
sql_upd+="SET ";
first=true;
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
if (!first) sql_upd+=", "; else sql_upd+=" ";
first=false;
sql_upd+=fieldlookup[i]+" = ?"+Const.CR;
}
}
sql_upd+="WHERE ";
for (i=0;i<keylookup.length;i++)
{
if (i>0) sql_upd+="AND ";
sql_upd+=keylookup[i]+" = ?"+Const.CR;
}
try
{
pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd));
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex);
}
}
Row rupd=new Row();
for (i=0;i<fieldlookup.length;i++)
{
if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH)
{
rupd.addValue( row.getValue(fieldnrs[i]));
}
}
for (i=0;i<keynrs.length;i++)
{
rupd.addValue( row.getValue(keynrs[i]));
}
// UPDATE VALUES
setValues(rupd, pstmt_pun); // set values for update
insertRow(pstmt_pun); // do the actual update
}
// This inserts new record into dimension
// Optionally, if the entry already exists, update date range from previous version
// of the entry.
public void combiInsert(Row row,
String table,
String keyfield,
boolean autoinc,
Value val_key,
String keylookup[],
int keynrs[],
boolean crc,
String crcfield,
Value val_crc
)
throws KettleDatabaseException
{
int i;
boolean comma;
if (prepStatementInsert==null) // first time: construct prepared statement
{
/* Construct the SQL statement...
*
* INSERT INTO
* d_test(keyfield, [crcfield,] keylookup[])
* VALUES(val_key, [val_crc], row values with keynrs[])
* ;
*/
String sql="INSERT INTO "+table+"( ";
comma=false;
if (!autoinc) // NO AUTOINCREMENT
{
sql+=keyfield;
comma=true;
}
else
if (databaseMeta.needsPlaceHolder())
{
sql+="0"; // placeholder on informix! Will be replaced in table by real autoinc value.
comma=true;
}
if (crc)
{
if (comma) sql+=", ";
sql+=crcfield;
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=", ";
sql+=keylookup[i];
comma=true;
}
sql+=") VALUES (";
comma=false;
if (keyfield!=null)
{
sql+="?";
comma=true;
}
if (crc)
{
if (comma) sql+=",";
sql+="?";
comma=true;
}
for (i=0;i<keylookup.length;i++)
{
if (comma) sql+=","; else comma=true;
sql+="?";
}
sql+=" )";
try
{
if (keyfield==null)
{
log.logDetailed(toString(), "SQL with return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS);
}
else
{
log.logDetailed(toString(), "SQL without return keys: "+sql);
prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql));
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
catch(Exception ex)
{
throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sql, ex);
}
}
Row rins=new Row();
if (!autoinc) rins.addValue(val_key);
if (crc)
{
rins.addValue(val_crc);
}
for (i=0;i<keynrs.length;i++)
{
rins.addValue( row.getValue(keynrs[i]));
}
//log.logRowlevel("rins="+rins.toString());
// INSERT NEW VALUE!
setValues(rins, prepStatementInsert);
insertRow(prepStatementInsert);
if (keyfield==null)
{
try
{
ResultSet keys=pstmt.getGeneratedKeys(); // 1 key
if (keys.next()) val_key.setValue(keys.getDouble(1));
else
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset");
}
keys.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex);
}
}
}
public Value getNextSequenceValue(String seq, String keyfield)
throws KettleDatabaseException
{
Value retval=null;
try
{
if (pstmt_seq==null)
{
pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq)));
}
ResultSet rs=pstmt_seq.executeQuery();
if (rs.next())
{
long next = rs.getLong(1);
retval=new Value(keyfield, next);
retval.setLength(9,0);
}
rs.close();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex);
}
return retval;
}
public void insertRow(String tableName, Row fields)
throws KettleDatabaseException
{
prepareInsert(fields, tableName);
setValuesInsert(fields);
insertRow();
closeInsert();
}
public String getInsertStatement(String tableName, Row fields)
{
String ins="";
ins+="INSERT INTO "+tableName+"(";
// now add the names in the row:
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
String name = fields.getValue(i).getName();
ins+=databaseMeta.quoteField(name);
}
ins+=") VALUES (";
// Add placeholders...
for (int i=0;i<fields.size();i++)
{
if (i>0) ins+=", ";
ins+=" ?";
}
ins+=")";
return ins;
}
public void insertRow()
throws KettleDatabaseException
{
insertRow(prepStatementInsert);
}
public void insertRow(boolean batch) throws KettleDatabaseException
{
insertRow(prepStatementInsert, batch);
}
public void updateRow()
throws KettleDatabaseException
{
insertRow(prepStatementUpdate);
}
public void insertRow(PreparedStatement ps)
throws KettleDatabaseException
{
insertRow(ps, false);
}
/**
* @param batchCounter The batchCounter to set.
*/
public void setBatchCounter(int batchCounter)
{
this.batchCounter = batchCounter;
}
/**
* @return Returns the batchCounter.
*/
public int getBatchCounter()
{
return batchCounter;
}
private long testCounter = 0;
/**
* Insert a row into the database using a prepared statement that has all values set.
* @param ps The prepared statement
* @param batch True if you want to use batch inserts (size = commitsize)
* @throws KettleDatabaseException
*/
public void insertRow(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
String debug="insertRow start";
try
{
boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates();
// Add support for batch inserts...
if (!isAutoCommit())
{
if (useBatchInsert)
{
debug="insertRow add batch";
batchCounter++;
ps.addBatch(); // Add the batch, but don't forget to run the batch
testCounter++;
// System.out.println("testCounter is at "+testCounter);
}
else
{
debug="insertRow exec update";
ps.executeUpdate();
}
}
else
{
ps.executeUpdate();
}
written++;
if (!isAutoCommit() && (written%commitsize)==0)
{
if (useBatchInsert)
{
debug="insertRow executeBatch commit";
ps.executeBatch();
commit();
ps.clearBatch();
// System.out.println("EXECUTE BATCH, testcounter is at "+testCounter);
batchCounter=0;
}
else
{
debug="insertRow normal commit";
commit();
}
}
}
catch(BatchUpdateException ex)
{
//System.out.println("Batch update exception "+ex.getMessage());
KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex);
kdbe.setUpdateCounts(ex.getUpdateCounts());
throw kdbe;
}
catch(SQLException ex)
{
// System.out.println("SQLException: "+ex.getMessage());
throw new KettleDatabaseException("Error inserting row", ex);
}
catch(Exception e)
{
// System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage());
throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e);
}
}
/**
* Clears batch of insert prepared statement
* @deprecated
* @throws KettleDatabaseException
*/
public void clearInsertBatch() throws KettleDatabaseException
{
clearBatch(prepStatementInsert);
}
public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException
{
try
{
preparedStatement.clearBatch();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to clear batch for prepared statement", e);
}
}
public void insertFinished(boolean batch) throws KettleDatabaseException
{
insertFinished(prepStatementInsert, batch);
prepStatementInsert = null;
}
public void insertFinished(PreparedStatement ps, boolean batch)
throws KettleDatabaseException
{
try
{
if (ps!=null)
{
if (!isAutoCommit())
{
if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0)
{
//System.out.println("Executing batch with "+batchCounter+" elements...");
ps.executeBatch();
commit();
}
else
{
commit();
}
}
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex);
}
}
/**
* Execute an SQL statement on the database connection (has to be open)
* @param sql The SQL to execute
* @return a Result object indicating the number of lines read, deleted, inserted, updated, ...
* @throws KettleDatabaseException in case anything goes wrong.
*/
public Result execStatement(String sql)
throws KettleDatabaseException
{
return execStatement(sql, null);
}
public Result execStatement(String sql, Row params)
throws KettleDatabaseException
{
Result result = new Result();
try
{
boolean resultSet;
int count;
if (params!=null)
{
PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql));
setValues(params, prep_stmt); // set the parameters!
resultSet = prep_stmt.execute();
count = prep_stmt.getUpdateCount();
prep_stmt.close();
}
else
{
Statement stmt = connection.createStatement();
resultSet = stmt.execute(databaseMeta.stripCR(sql));
count = stmt.getUpdateCount();
stmt.close();
}
if (resultSet)
{
// the result is a resultset, but we don't do anything with it!
// You should have called something else!
// System.out.println("What to do with ResultSet??? (count="+count+")");
}
else
{
if (count > 0)
{
if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count);
if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count);
if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count);
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e);
}
return result;
}
/**
* Execute a series of SQL statements, separated by ;
*
* We are already connected...
* Multiple statements have to be split into parts
* We use the ";" to separate statements...
*
* We keep the results in Result object from Jobs
*
* @param script The SQL script to be execute
* @throws KettleDatabaseException In case an error occurs
* @return A result with counts of the number or records updates, inserted, deleted or read.
*/
public Result execStatements(String script)
throws KettleDatabaseException
{
Result result = new Result();
String all = script;
int from=0;
int to=0;
int length = all.length();
int nrstats = 0;
while (to<length)
{
char c = all.charAt(to);
if (c=='"')
{
to++;
c=' ';
while (to<length && c!='"') { c=all.charAt(to); to++; }
}
else
if (c=='\'') // skip until next '
{
to++;
c=' ';
while (to<length && c!='\'') { c=all.charAt(to); to++; }
}
else
if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line...
{
to++;
while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; }
}
if (c==';' || to>=length-1) // end of statement
{
if (to>=length-1) to++; // grab last char also!
String stat = all.substring(from, to);
if (!Const.onlySpaces(stat))
{
String sql=Const.trim(stat);
if (sql.toUpperCase().startsWith("SELECT"))
{
// A Query
log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql);
nrstats++;
ResultSet rs = openQuery(sql);
if (rs!=null)
{
Row r = getRow(rs);
while (r!=null)
{
result.setNrLinesRead(result.getNrLinesRead()+1);
log.logDetailed(toString(), r.toString());
r=getRow(rs);
}
}
else
{
log.logDebug(toString(), "Error executing query: "+Const.CR+sql);
}
}
else // any kind of statement
{
log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql);
// A DDL statement
nrstats++;
Result res = execStatement(sql);
result.add(res);
}
}
to++;
from=to;
}
else
{
to++;
}
}
log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed");
return result;
}
public ResultSet openQuery(String sql)
throws KettleDatabaseException
{
return openQuery(sql, null);
}
public ResultSet openQuery(String sql, Row params)
throws KettleDatabaseException
{
return openQuery(sql, params, ResultSet.FETCH_FORWARD);
}
public ResultSet openQuery(String sql, Row params, int fetch_mode)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
if (params!=null)
{
debug = "P create prepared statement (con==null? "+(connection==null)+")";
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug = "P Set values";
setValues(params); // set the dates etc!
if (databaseMeta.isFetchSizeSupported() && pstmt.getMaxRows()>0)
{
debug = "P Set fetchsize";
int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE;
// System.out.println("Setting pstmt fetchsize to : "+fs);
pstmt.setFetchSize(fs);
debug = "P Set fetch direction";
pstmt.setFetchDirection(fetch_mode);
}
debug = "P Set max rows";
if (rowlimit>0) pstmt.setMaxRows(rowlimit);
debug = "exec query";
res = pstmt.executeQuery();
}
else
{
debug = "create statement";
sel_stmt = connection.createStatement();
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>0)
{
debug = "Set fetchsize";
int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE;
sel_stmt.setFetchSize(fs);
debug = "Set fetch direction";
sel_stmt.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "Set max rows";
if (rowlimit>0) sel_stmt.setMaxRows(rowlimit);
debug = "exec query";
res=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
}
debug = "get metadata";
rsmd = res.getMetaData();
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
log.logError(toString(), "ERROR executing ["+sql+"]");
log.logError(toString(), "ERROR in part: ["+debug+"]");
printSQLException(ex);
throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex);
}
catch(Exception e)
{
log.logError(toString(), "ERROR executing query: "+e.toString());
log.logError(toString(), "ERROR in part: "+debug);
throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e);
}
return res;
}
public ResultSet openQuery(PreparedStatement ps, Row params)
throws KettleDatabaseException
{
ResultSet res;
String debug = "Start";
// Create a Statement
try
{
debug = "OQ Set values";
setValues(params, ps); // set the parameters!
if (databaseMeta.isFetchSizeSupported() && ps.getMaxRows()>0)
{
debug = "OQ Set fetchsize";
int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE;
ps.setFetchSize(fs);
debug = "OQ Set fetch direction";
ps.setFetchDirection(ResultSet.FETCH_FORWARD);
}
debug = "OQ Set max rows";
if (rowlimit>0) ps.setMaxRows(rowlimit);
debug = "OQ exec query";
res = ps.executeQuery();
debug = "OQ get metadata";
rsmd = res.getMetaData();
debug = "OQ getRowInfo()";
rowinfo = getRowInfo();
}
catch(SQLException ex)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e);
}
return res;
}
public Row getTableFields(String tablename)
throws KettleDatabaseException
{
return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false);
}
public Row getQueryFields(String sql, boolean param)
throws KettleDatabaseException
{
return getQueryFields(sql, param, null);
}
/**
* See if the table specified exists by looking at the data dictionary!
* @param tablename The name of the table to check.
* @return true if the table exists, false if it doesn't.
*/
public boolean checkTableExists(String tablename)
throws KettleDatabaseException
{
try
{
log.logDebug(toString(), "Checking if table ["+tablename+"] exists!");
if (getDatabaseMetaData()!=null)
{
ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } );
boolean found = false;
if (alltables!=null)
{
while (alltables.next() && !found)
{
String schemaName = alltables.getString("TABLE_SCHEM");
String name = alltables.getString("TABLE_NAME");
if ( tablename.equalsIgnoreCase(name) ||
( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) )
)
{
log.logDebug(toString(), "table ["+tablename+"] was found!");
found=true;
}
}
alltables.close();
return found;
}
else
{
throw new KettleDatabaseException("Unable to read table-names from the database meta-data.");
}
}
else
{
throw new KettleDatabaseException("Unable to get database meta-data from the database.");
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e);
}
}
/**
* Check whether the sequence exists, Oracle only!
* @param sequenceName The name of the sequence
* @return true if the sequence exists.
*/
public boolean checkSequenceExists(String sequenceName)
throws KettleDatabaseException
{
boolean retval=false;
if (!databaseMeta.supportsSequences()) return retval;
try
{
// Get the info from the data dictionary...
String sql = databaseMeta.getSQLSequenceExists(sequenceName);
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
if (row!=null)
{
retval=true;
}
closeQuery(res);
}
}
catch(Exception e)
{
throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e);
}
return retval;
}
/**
* Check if an index on certain fields in a table exists.
* @param tablename The table on which the index is checked
* @param idx_fields The fields on which the indexe is checked
* @return True if the index exists
*/
public boolean checkIndexExists(String tablename, String idx_fields[])
throws KettleDatabaseException
{
if (!checkTableExists(tablename)) return false;
log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc());
boolean exists[] = new boolean[idx_fields.length];
for (int i=0;i<exists.length;i++) exists[i]=false;
try
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_MSSQL:
{
// Get the info from the data dictionary...
String sql = "select i.name table_name, c.name column_name ";
sql += "from sysindexes i, sysindexkeys k, syscolumns c ";
sql += "where i.name = '"+tablename+"' ";
sql += "AND i.id = k.id ";
sql += "AND i.id = c.id ";
sql += "AND k.colid = c.colid ";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("column_name", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0) exists[idx]=true;
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ORACLE:
{
// Get the info from the data dictionary...
String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'";
ResultSet res = openQuery(sql);
if (res!=null)
{
Row row = getRow(res);
while (row!=null)
{
String column = row.getString("COLUMN_NAME", "");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
row = getRow(res);
}
closeQuery(res);
}
else
{
return false;
}
}
break;
case DatabaseMeta.TYPE_DATABASE_ACCESS:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close(); }
break;
default:
{
// Get a list of all the indexes for this table
ResultSet indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true);
while (indexList.next())
{
// String tablen = indexList.getString("TABLE_NAME");
// String indexn = indexList.getString("INDEX_NAME");
String column = indexList.getString("COLUMN_NAME");
// int pos = indexList.getShort("ORDINAL_POSITION");
// int type = indexList.getShort("TYPE");
int idx = Const.indexOfString(column, idx_fields);
if (idx>=0)
{
exists[idx]=true;
}
}
indexList.close();
}
break;
}
// See if all the fields are indexed...
boolean all=true;
for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false;
return all;
}
catch(Exception e)
{
e.printStackTrace();
throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e);
}
}
public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon)
{
String cr_index="";
cr_index += "CREATE ";
if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE))
cr_index += "UNIQUE ";
if (bitmap && databaseMeta.supportsBitmapIndex())
cr_index += "BITMAP ";
cr_index += "INDEX "+indexname+Const.CR+" ";
cr_index += "ON "+tablename+Const.CR;
cr_index += "( "+Const.CR;
for (int i=0;i<idx_fields.length;i++)
{
if (i>0) cr_index+=", "; else cr_index+=" ";
cr_index += idx_fields[i]+Const.CR;
}
cr_index+=")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
cr_index+="TABLESPACE "+databaseMeta.getIndexTablespace();
}
if (semi_colon)
{
cr_index+=";"+Const.CR;
}
return cr_index;
}
public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon)
{
String cr_seq="";
if (sequence==null || sequence.length()==0) return cr_seq;
if (databaseMeta.supportsSequences())
{
cr_seq += "CREATE SEQUENCE "+sequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-)
cr_seq += "START WITH "+start_at+" "+Const.CR;
cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR;
if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR;
if (semi_colon) cr_seq+=";"+Const.CR;
}
return cr_seq;
}
public Row getQueryFields(String sql, boolean param, Row inform)
throws KettleDatabaseException
{
Row fields;
DBCache dbcache = DBCache.getInstance();
DBCacheEntry entry=null;
// Check the cache first!
if (dbcache!=null)
{
entry = new DBCacheEntry(databaseMeta.getName(), sql);
fields = dbcache.get(entry);
if (fields!=null)
{
return fields;
}
}
if (connection==null) return null; // Cache test without connect.
// No cache entry found
String debug="";
try
{
if (inform==null)
{
debug="inform==null";
sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
debug="isFetchSizeSupported()";
if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1)
{
debug = "Set fetchsize";
sel_stmt.setFetchSize(1); // Only one row needed!
}
debug = "Set max rows to 1";
sel_stmt.setMaxRows(1);
debug = "exec query";
ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql));
debug = "get metadata";
rsmd = r.getMetaData();
fields = getRowInfo();
debug="close resultset";
r.close();
debug="close statement";
sel_stmt.close();
sel_stmt=null;
}
else
{
debug="prepareStatement";
PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql));
if (param)
{
Row par = inform;
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(ps);
debug="getParameterMetaData()";
if (par==null) par = getParameterMetaData(sql, inform);
setValues(par, ps);
}
debug="executeQuery()";
ResultSet r = ps.executeQuery();
debug="getMetaData";
rsmd = ps.getMetaData();
debug="getRowInfo";
fields=getRowInfo(rsmd);
debug="close resultset";
r.close();
debug="close preparedStatement";
ps.close();
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex);
}
catch(Exception e)
{
throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e);
}
// Store in cache!!
if (dbcache!=null && entry!=null)
{
if (fields!=null)
{
dbcache.put(entry, fields);
}
}
return fields;
}
public void closeQuery(ResultSet res)
throws KettleDatabaseException
{
// close everything involved in the query!
try
{
if (res!=null) res.close();
if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; }
if (pstmt!=null) { pstmt.close(); pstmt=null;}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex);
}
}
// Build the row using ResultSetMetaData rsmd
private Row getRowInfo(ResultSetMetaData rm)
throws KettleDatabaseException
{
int nrcols;
int i;
Value v;
String name;
int type, valtype;
int precision;
int length;
if (rm==null) return null;
rowinfo = new Row();
try
{
nrcols=rm.getColumnCount();
for (i=1;i<=nrcols;i++)
{
name=new String(rm.getColumnName(i));
type=rm.getColumnType(i);
valtype=Value.VALUE_TYPE_NONE;
length=rm.getPrecision(i);
precision=rm.getScale(i);
switch(type)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR: // Character Large Object
valtype=Value.VALUE_TYPE_STRING;
length=rm.getColumnDisplaySize(i);
// System.out.println("Display of "+name+" = "+precision);
// System.out.println("Precision of "+name+" = "+rm.getPrecision(i));
// System.out.println("Scale of "+name+" = "+rm.getScale(i));
break;
case java.sql.Types.CLOB:
valtype=Value.VALUE_TYPE_STRING;
length=DatabaseMeta.CLOB_LENGTH;
break;
case java.sql.Types.BIGINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 9.223.372.036.854.775.807
length=15;
break;
case java.sql.Types.INTEGER:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 2.147.483.647
length=9;
break;
case java.sql.Types.SMALLINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 32.767
length=4;
break;
case java.sql.Types.TINYINT:
valtype=Value.VALUE_TYPE_INTEGER;
precision=0; // Max 127
length=2;
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
case java.sql.Types.NUMERIC:
valtype=Value.VALUE_TYPE_NUMBER;
if (length >=126) length=-1;
if (precision >=126) precision=-1;
if (precision==0 && length<18 && length>0) valtype=Value.VALUE_TYPE_INTEGER;
if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
if (precision<=0 && length<=0) // undefined size: BIGNUMBER
{
valtype=Value.VALUE_TYPE_BIGNUMBER;
length=-1;
precision=-1;
}
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
valtype=Value.VALUE_TYPE_DATE;
break;
case java.sql.Types.BOOLEAN:
valtype=Value.VALUE_TYPE_BOOLEAN;
break;
default:
valtype=Value.VALUE_TYPE_STRING;
break;
}
// comment=rm.getColumnLabel(i);
// TODO: change this hack!
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ACCESS)
{
if (valtype==Value.VALUE_TYPE_INTEGER)
{
valtype=Value.VALUE_TYPE_NUMBER;
length = -1;
precision = -1;
}
}
v=new Value(name, valtype);
v.setLength(length, precision);
rowinfo.addValue(v);
}
return rowinfo;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error getting row information from database: ", ex);
}
}
// Build the row using ResultSetMetaData rsmd
private Row getRowInfo()
throws KettleDatabaseException
{
return getRowInfo(rsmd);
}
public boolean absolute(ResultSet rs, int position)
throws KettleDatabaseException
{
try
{
return rs.absolute(position);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to position "+position, e);
}
}
public boolean relative(ResultSet rs, int rows)
throws KettleDatabaseException
{
try
{
return rs.relative(rows);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e);
}
}
public void afterLast(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.afterLast();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to after the last position", e);
}
}
public void first(ResultSet rs)
throws KettleDatabaseException
{
try
{
rs.first();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to move resultset to the first position", e);
}
}
/**
* Get a row from the resultset.
* @param rs The resultset to get the row from
* @return one row or null if no row was found on the resultset or if an error occurred.
*/
public Row getRow(ResultSet rs)
throws KettleDatabaseException
{
Row row;
int nrcols, i;
Value val;
try
{
nrcols=rsmd.getColumnCount();
if (rs.next())
{
row=new Row();
for (i=0;i<nrcols;i++)
{
val=new Value(rowinfo.getValue(i)); // copy info from meta-data.
switch(val.getType())
{
case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break;
case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break;
case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break;
case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break;
case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break;
case Value.VALUE_TYPE_DATE :
if (databaseMeta.supportsTimeStampToDateConversion())
{
val.setValue( rs.getTimestamp(i+1) ); break;
}
else
{
val.setValue( rs.getDate(i+1) ); break;
}
default: break;
}
if (rs.wasNull()) val.setNull(); // null value!
row.addValue(val);
}
}
else
{
row=null;
}
return row;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Couldn't get row from result set", ex);
}
}
public void printSQLException(SQLException ex)
{
log.logError(toString(), "==> SQLException: ");
while (ex != null)
{
log.logError(toString(), "Message: " + ex.getMessage ());
log.logError(toString(), "SQLState: " + ex.getSQLState ());
log.logError(toString(), "ErrorCode: " + ex.getErrorCode ());
ex = ex.getNextException();
log.logError(toString(), "");
}
}
// Lookup certain fields in a table
public void setLookup(String table, String codes[], String condition[],
String gets[], String rename[], String orderby)
throws KettleDatabaseException
{
String sql;
int i;
sql = "SELECT ";
for (i=0;i<gets.length;i++)
{
if (i!=0) sql += ", ";
sql += gets[i];
if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i]))
{
sql+=" AS "+rename[i];
}
}
sql += " FROM "+table+" WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += " AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
if (orderby!=null && orderby.length()!=0)
{
sql += " ORDER BY "+orderby;
}
try
{
log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex);
}
}
// Lookup certain fields in a table
public boolean prepareUpdate(String table, String codes[], String condition[], String sets[])
{
String sql;
int i;
sql = "UPDATE "+table+Const.CR+"SET ";
for (i=0;i<sets.length;i++)
{
if (i!=0) sql += ", ";
sql += databaseMeta.quoteField(sets[i]);
sql+=" = ?"+Const.CR;
}
sql += "WHERE ";
for (i=0;i<codes.length;i++)
{
if (i!=0) sql += "AND ";
sql += codes[i];
if ("BETWEEN".equalsIgnoreCase(condition[i]))
{
sql+=" BETWEEN ? AND ? ";
}
else
if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i]))
{
sql+=" "+condition[i]+" ";
}
else
{
sql+=" "+condition[i]+" ? ";
}
}
try
{
log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]");
prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql));
}
catch(SQLException ex)
{
printSQLException(ex);
return false;
}
return true;
}
public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype)
throws KettleDatabaseException
{
String sql;
int pos=0;
int i;
sql = "{ ";
if (returnvalue!=null && returnvalue.length()!=0)
{
sql+="? = ";
}
sql+="call "+proc+" ";
if (arg.length>0) sql+="(";
for (i=0;i<arg.length;i++)
{
if (i!=0) sql += ", ";
sql += " ?";
}
if (arg.length>0) sql+=")";
sql+="}";
try
{
log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]");
cstmt=connection.prepareCall(sql);
pos=1;
if (returnvalue!=null)
{
switch(returntype)
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break;
default: break;
}
pos++;
}
for (i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
switch(argtype[i])
{
case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break;
case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break;
case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break;
case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break;
case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break;
case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break;
default: break;
}
}
}
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare database procedure call", ex);
}
}
/*
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
* datefield: do we have a datefield?
* datefrom, dateto: date-range, if any.
*/
public boolean setDimLookup(String table,
String keys[],
String tk,
String version,
String extra[],
String extraRename[],
String datefrom,
String dateto
)
throws KettleDatabaseException
{
String sql;
int i;
/*
* SELECT <tk>, <version>, ...
* FROM <table>
* WHERE key1=keys[1]
* AND key2=keys[2] ...
* AND <datefield> BETWEEN <datefrom> AND <dateto>
* ;
*
*/
sql = "SELECT "+tk+", "+version;
if (extra!=null)
{
for (i=0;i<extra.length;i++)
{
if (extra[i]!=null && extra[i].length()!=0)
{
sql+=", "+extra[i];
if (extraRename[i]!=null &&
extraRename[i].length()>0 &&
!extra[i].equals(extraRename[i]))
{
sql+=" AS "+extraRename[i];
}
}
}
}
sql+= " FROM "+table+" WHERE ";
for (i=0;i<keys.length;i++)
{
if (i!=0) sql += " AND ";
sql += keys[i]+" = ? ";
}
sql += " AND ? >= "+datefrom+" AND ? < "+dateto;
try
{
log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]");
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
log.logDetailed(toString(), "Finished preparing dimension lookup statement.");
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare dimension lookup", ex);
}
return true;
}
/* CombinationLookup
* table: dimension table
* keys[]: which dim-fields do we use to look up key?
* retval: name of the key to return
*/
public void setCombiLookup(String table,
String keys[],
String retval,
boolean crc,
String crcfield
)
throws KettleDatabaseException
{
String sql;
int i;
boolean comma;
/*
* SELECT <retval>
* FROM <table>
* WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
* OR
*
* SELECT <retval>
* FROM <table>
* WHERE <crcfield> = ?
* AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) )
* ...
* ;
*
*/
sql = "SELECT "+retval+Const.CR+"FROM "+table+Const.CR+"WHERE ";
comma=false;
if (crc)
{
sql+=crcfield+" = ? "+Const.CR;
comma=true;
}
else
{
sql+="( ( ";
}
for (i=0;i<keys.length;i++)
{
if (comma)
{
sql += " AND ( ( ";
}
else
{
comma=true;
}
sql += keys[i]+" = ? ) OR ( "+keys[i]+" IS NULL AND ? IS NULL ) )"+Const.CR;
}
try
{
log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sql);
prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql));
prepStatementLookup.setMaxRows(1); // alywas get only 1 line back!
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex);
}
}
public Row callProcedure(String arg[], String argdir[], int argtype[],
String resultname, int resulttype)
throws KettleDatabaseException
{
Row ret;
try
{
cstmt.execute();
ret=new Row();
int pos=1;
if (resultname!=null && resultname.length()!=0)
{
Value v=new Value(resultname, Value.VALUE_TYPE_NONE);
switch(resulttype)
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break;
}
ret.addValue(v);
pos++;
}
for (int i=0;i<arg.length;i++)
{
if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT"))
{
Value v=new Value(arg[i], Value.VALUE_TYPE_NONE);
switch(argtype[i])
{
case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break;
case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break;
case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break;
case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break;
case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break;
case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break;
}
ret.addValue(v);
}
}
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to call procedure", ex);
}
}
public Row getLookup()
throws KettleDatabaseException
{
return getLookup(prepStatementLookup);
}
public Row getLookup(PreparedStatement ps)
throws KettleDatabaseException
{
String debug = "start";
Row ret;
try
{
debug = "pstmt.executeQuery()";
ResultSet res = ps.executeQuery();
debug = "res.getMetaData";
rsmd = res.getMetaData();
debug = "getRowInfo()";
rowinfo = getRowInfo();
debug = "getRow(res)";
ret=getRow(res);
debug = "res.close()";
res.close(); // close resultset!
return ret;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex);
}
}
public DatabaseMetaData getDatabaseMetaData()
throws KettleDatabaseException
{
try
{
if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once!
}
catch(Exception e)
{
throw new KettleDatabaseException("Unable to get database metadata from this database connection", e);
}
return dbmd;
}
public String getDDL(String tablename, Row fields)
throws KettleDatabaseException
{
return getDDL(tablename, fields, null, false, null, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk)
throws KettleDatabaseException
{
return getDDL(tablename, fields, tk, use_autoinc, pk, true);
}
public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval;
// First, check for reserved SQL in the input row r...
databaseMeta.replaceReservedWords(fields);
if (checkTableExists(tablename))
{
retval=getAlterTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
else
{
retval=getCreateTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon);
}
return retval;
}
public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
{
String retval;
retval = "CREATE TABLE "+tablename+Const.CR;
retval+= "("+Const.CR;
for (int i=0;i<fields.size();i++)
{
if (i>0) retval+=", "; else retval+=" ";
Value v=fields.getValue(i);
retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc);
}
// At the end, before the closing of the statement, we might need to add some constraints...
// Technical keys
if (tk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE)
{
retval+=", PRIMARY KEY ("+tk+")"+Const.CR;
}
}
// Primary keys
if (pk!=null)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE)
{
retval+=", PRIMARY KEY ("+pk+")"+Const.CR;
}
}
retval+= ")"+Const.CR;
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE &&
databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0)
{
retval+="TABLESPACE "+databaseMeta.getDataTablespace();
}
if (semicolon) retval+=";";
retval+=Const.CR;
return retval;
}
public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon)
throws KettleDatabaseException
{
String retval="";
// Get the fields that are in the table now:
Row tabFields = getTableFields(tablename);
// Find the missing fields
Row missing = new Row();
for (int i=0;i<fields.size();i++)
{
Value v = fields.getValue(i);
// Not found?
if (tabFields.searchValue( v.getName() )==null )
{
missing.addValue(v); // nope --> Missing!
}
}
if (missing.size()!=0)
{
for (int i=0;i<missing.size();i++)
{
Value v=missing.getValue(i);
retval+=databaseMeta.getAddColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
// Find the surplus fields
Row surplus = new Row();
for (int i=0;i<tabFields.size();i++)
{
Value v = tabFields.getValue(i);
// Found in table, not in input ?
if (fields.searchValue( v.getName() )==null )
{
surplus.addValue(v); // yes --> surplus!
}
}
if (surplus.size()!=0)
{
for (int i=0;i<surplus.size();i++)
{
Value v=surplus.getValue(i);
retval+=databaseMeta.getDropColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
// OK, see if there are fields for wich we need to modify the type... (length, precision)
Row modify = new Row();
for (int i=0;i<fields.size();i++)
{
Value desiredField = fields.getValue(i);
Value currentField = tabFields.searchValue( desiredField.getName());
if (currentField!=null)
{
boolean mod = false;
mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0;
mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0;
// Numeric values...
mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() );
if (mod)
{
// System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]");
modify.addValue(desiredField);
}
}
}
if (modify.size()>0)
{
for (int i=0;i<modify.size();i++)
{
Value v=modify.getValue(i);
retval+=databaseMeta.getModifyColumnStatement(tablename, v, tk, use_autoinc, pk, true);
}
}
return retval;
}
public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc)
throws KettleDatabaseException
{
int start_tk = databaseMeta.getNotFoundTK(use_autoinc);
String sql = "SELECT count(*) FROM "+tablename+" WHERE "+tk+" = "+start_tk;
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
Value count = r.getValue(0);
if (count.getNumber() == 0)
{
try
{
Statement st = connection.createStatement();
String isql;
if (!databaseMeta.supportsAutoinc() || !use_autoinc)
{
isql = isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)";
}
else
{
switch(databaseMeta.getDatabaseType())
{
case DatabaseMeta.TYPE_DATABASE_CACHE :
case DatabaseMeta.TYPE_DATABASE_GUPTA :
case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_INFORMIX :
case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+tablename+"("+tk+", "+version+") values (1, 1)"; break;
case DatabaseMeta.TYPE_DATABASE_MSSQL :
case DatabaseMeta.TYPE_DATABASE_DB2 :
case DatabaseMeta.TYPE_DATABASE_DBASE :
case DatabaseMeta.TYPE_DATABASE_GENERIC :
case DatabaseMeta.TYPE_DATABASE_SYBASE :
case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+tablename+"("+version+") values (1)"; break;
default: isql = "insert into "+tablename+"("+tk+", "+version+") values (0, 1)"; break;
}
}
st.executeUpdate(databaseMeta.stripCR(isql));
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e);
}
}
}
public Value checkSequence(String seqname)
throws KettleDatabaseException
{
String sql=null;
if (databaseMeta.supportsSequences())
{
sql = databaseMeta.getSQLCurrentSequenceValue(seqname);
ResultSet rs = openQuery(sql, null);
Row r = getRow(rs); // One value: a number;
if (r!=null)
{
Value last = r.getValue(0);
// errorstr="Sequence is at number: "+last.toString();
return last;
}
else
{
return null;
}
}
else
{
throw new KettleDatabaseException("Sequences are only available for Oracle databases.");
}
}
public void truncateTable(String tablename) throws KettleDatabaseException
{
execStatement(databaseMeta.getTruncateTableStatement(tablename));
}
/**
* Execute a query and return at most one row from the resultset
* @param sql The SQL for the query
* @return one Row with data or null if nothing was found.
*/
public Row getOneRow(String sql) throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, null);
if (rs!=null)
{
Row r = getRow(rs); // One row only;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
throw new KettleDatabaseException("error opening resultset for query: "+sql);
}
}
public Row getOneRow(String sql, Row param)
throws KettleDatabaseException
{
ResultSet rs = openQuery(sql, param);
if (rs!=null)
{
Row r = getRow(rs); // One value: a number;
try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); }
if (pstmt!=null)
{
try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); }
pstmt=null;
}
if (sel_stmt!=null)
{
try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); }
sel_stmt=null;
}
return r;
}
else
{
return null;
}
}
public Row getParameterMetaData(PreparedStatement ps)
{
Row par = new Row();
try
{
ParameterMetaData pmd = ps.getParameterMetaData();
for (int i=1;i<pmd.getParameterCount();i++)
{
String name = "par"+i;
int sqltype = pmd.getParameterType(i);
int length = pmd.getPrecision(i);
int precision = pmd.getScale(i);
Value val;
switch(sqltype)
{
case java.sql.Types.CHAR:
case java.sql.Types.VARCHAR:
val=new Value(name, Value.VALUE_TYPE_STRING);
break;
case java.sql.Types.BIGINT:
case java.sql.Types.INTEGER:
case java.sql.Types.NUMERIC:
case java.sql.Types.SMALLINT:
case java.sql.Types.TINYINT:
val=new Value(name, Value.VALUE_TYPE_INTEGER);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.DOUBLE:
case java.sql.Types.FLOAT:
case java.sql.Types.REAL:
val=new Value(name, Value.VALUE_TYPE_NUMBER);
break;
case java.sql.Types.DATE:
case java.sql.Types.TIME:
case java.sql.Types.TIMESTAMP:
val=new Value(name, Value.VALUE_TYPE_DATE);
break;
case java.sql.Types.BOOLEAN:
val=new Value(name, Value.VALUE_TYPE_BOOLEAN);
break;
default:
val=new Value(name, Value.VALUE_TYPE_NONE);
break;
}
if (val.isNumeric() && ( length>18 || precision>18) )
{
val = new Value(name, Value.VALUE_TYPE_BIGNUMBER);
}
val.setNull();
par.addValue(val);
}
}
// Oops: probably the database or JDBC doesn't support it.
catch(AbstractMethodError e) { return null; }
catch(SQLException e) { return null; }
catch(Exception e) { return null; }
return par;
}
public int countParameters(String sql)
{
int q=0;
boolean quote_opened=false;
boolean dquote_opened=false;
for (int x=0;x<sql.length();x++)
{
char c = sql.charAt(x);
switch(c)
{
case '\'': quote_opened= !quote_opened; break;
case '"' : dquote_opened=!dquote_opened; break;
case '?' : if (!quote_opened && !dquote_opened) q++; break;
}
}
return q;
}
// Get the fields back from an SQL query
public Row getParameterMetaData(String sql, Row inform)
{
// The database coudln't handle it: try manually!
int q=countParameters(sql);
Row par=new Row();
if (inform!=null && q==inform.size())
{
for (int i=0;i<q;i++)
{
Value inf=inform.getValue(i);
Value v = new Value(inf);
par.addValue(v);
}
}
else
{
for (int i=0;i<q;i++)
{
Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER);
v.setValue( 0.0 );
par.addValue(v);
}
}
return par;
}
public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_batchid)
{
v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v);
}
v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield)
{
Row r = new Row();
Value v;
if (use_jobid)
{
v=new Value("ID_JOB", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
}
v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v);
v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v);
v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v);
v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v);
if (use_logfield)
{
v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING);
v.setLength(DatabaseMeta.CLOB_LENGTH,0);
r.addValue(v);
}
return r;
}
public void writeLogRecord( String logtable,
boolean use_id,
long id,
boolean job,
String name,
String status,
long read, long written, long updated,
long input, long output, long errors,
java.util.Date startdate, java.util.Date enddate,
java.util.Date logdate, java.util.Date depdate,
String log_string
)
throws KettleDatabaseException
{
int parms;
String sql = "INSERT INTO "+logtable+" ( ";
if (job)
{
if (use_id)
{
sql+="ID_JOB, JOBNAME";
parms=13;
}
else
{
sql+="JOBNAME";
parms=12;
}
}
else
{
if (use_id)
{
sql+="ID_BATCH, TRANSNAME";
parms=13;
}
else
{
sql+="TRANSNAME";
parms=12;
}
}
sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE";
if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB!
sql+=") VALUES(";
for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?";
if (log_string!=null && log_string.length()>0) sql+=", ?";
sql+=")";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
if (job)
{
if (use_id)
{
r.addValue( new Value("ID_BATCH", id ));
}
r.addValue( new Value("TRANSNAME", name ));
}
else
{
if (use_id)
{
r.addValue( new Value("ID_JOB", id ));
}
r.addValue( new Value("JOBNAME", name ));
}
r.addValue( new Value("STATUS", status ));
r.addValue( new Value("LINES_READ", (long)read ));
r.addValue( new Value("LINES_WRITTEN", (long)written));
r.addValue( new Value("LINES_UPDATED", (long)updated));
r.addValue( new Value("LINES_INPUT", (long)input ));
r.addValue( new Value("LINES_OUTPUT", (long)output ));
r.addValue( new Value("ERRORS", (long)errors ));
r.addValue( new Value("STARTDATE", startdate ));
r.addValue( new Value("ENDDATE", enddate ));
r.addValue( new Value("LOGDATE", logdate ));
r.addValue( new Value("DEPDATE", depdate ));
if (log_string!=null && log_string.length()>0)
{
Value large = new Value("LOG_FIELD", log_string );
large.setLength(DatabaseMeta.CLOB_LENGTH);
r.addValue( large );
}
setValues(r);
pstmt.executeUpdate();
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex);
}
}
public Row getLastLogDate( String logtable,
String name,
boolean job,
String status
)
throws KettleDatabaseException
{
Row row=null;
String jobtrans = job?"JOBNAME":"TRANSNAME";
String sql = "";
sql+=" SELECT ENDDATE, DEPDATE, STARTDATE";
sql+=" FROM "+logtable;
sql+=" WHERE ERRORS = 0";
sql+=" AND STATUS = 'end'";
sql+=" AND "+jobtrans+" = ?";
sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC";
try
{
pstmt = connection.prepareStatement(databaseMeta.stripCR(sql));
Row r = new Row();
r.addValue( new Value("TRANSNAME", name ));
setValues(r);
ResultSet res = pstmt.executeQuery();
if (res!=null)
{
rsmd = res.getMetaData();
rowinfo = getRowInfo();
row = getRow(res);
res.close();
}
pstmt.close(); pstmt=null;
}
catch(SQLException ex)
{
throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex);
}
return row;
}
public synchronized void getNextValue(TransMeta transMeta, String table, Value val_key)
throws KettleDatabaseException
{
String lookup = table+"."+val_key.getName();
// Try to find the previous sequence value...
Counter counter = (Counter)transMeta.getCounters().get(lookup);
if (counter==null)
{
Row r = getOneRow("SELECT MAX("+val_key.getName()+") FROM "+table);
if (r!=null)
{
counter = new Counter(r.getValue(0).getInteger()+1, 1);
val_key.setValue(counter.next());
transMeta.getCounters().put(lookup, counter);
}
else
{
throw new KettleDatabaseException("Couldn't find maximum key value from table "+table);
}
}
else
{
val_key.setValue(counter.next());
}
}
public String toString()
{
if (databaseMeta!=null) return databaseMeta.getName();
else return "-";
}
public boolean isSystemTable(String table_name)
{
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL)
{
if ( table_name.startsWith("sys")) return true;
if ( table_name.equals("dtproperties")) return true;
}
else
if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA)
{
if ( table_name.startsWith("SYS")) return true;
}
return false;
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit) throws KettleDatabaseException
{
return getRows(sql, limit, null);
}
/** Reads the result of an SQL query into an ArrayList
*
* @param sql The SQL to launch
* @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read.
* @param monitor The progress monitor to update while getting the rows.
* @return An ArrayList of rows.
* @throws KettleDatabaseException if something goes wrong.
*/
public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException
{
int i=0;
boolean stop=false;
ArrayList result = new ArrayList();
if (monitor!=null) monitor.setTaskName("Opening query...");
ResultSet rset = openQuery(sql);
if (rset!=null)
{
if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit);
while ((limit<=0 || i<limit) && !stop)
{
Row row = getRow(rset);
if (row!=null)
{
result.add(row);
i++;
}
else
{
stop=true;
}
if (monitor!=null && limit>0) monitor.worked(1);
}
closeQuery(rset);
if (monitor!=null) monitor.done();
}
return result;
}
public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException
{
return getFirstRows(table_name, limit, null);
}
public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor)
throws KettleDatabaseException
{
String sql = "SELECT * FROM "+table_name;
if (limit>0)
{
sql+=databaseMeta.getLimitClause(limit);
}
return getRows(sql, limit, monitor);
}
public Row getReturnRow()
{
return rowinfo;
}
public String[] getTableTypes()
throws KettleDatabaseException
{
try
{
ArrayList types = new ArrayList();
ResultSet rstt = getDatabaseMetaData().getTableTypes();
while(rstt.next())
{
String ttype = rstt.getString("TABLE_TYPE");
types.add(ttype);
}
return (String[])types.toArray(new String[types.size()]);
}
catch(SQLException e)
{
throw new KettleDatabaseException("Unable to get table types from database!", e);
}
}
public String[] getTablenames()
throws KettleDatabaseException
{
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got table from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]");
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getViews()
throws KettleDatabaseException
{
if (!databaseMeta.supportsViews()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getSynonyms()
throws KettleDatabaseException
{
if (!databaseMeta.supportsSynonyms()) return new String[] {};
String schemaname = null;
if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase();
ArrayList names = new ArrayList();
ResultSet alltables=null;
try
{
alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() );
while (alltables.next())
{
String table = alltables.getString("TABLE_NAME");
log.logRowlevel(toString(), "got view from meta-data: "+table);
names.add(table);
}
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e);
}
finally
{
try
{
if (alltables!=null) alltables.close();
}
catch(SQLException e)
{
throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e);
}
}
log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data.");
return (String[])names.toArray(new String[names.size()]);
}
public String[] getProcedures() throws KettleDatabaseException
{
String sql = databaseMeta.getSQLListOfProcedures();
if (sql!=null)
{
//System.out.println("SQL= "+sql);
ArrayList procs = getRows(sql, 1000);
//System.out.println("Found "+procs.size()+" rows");
String[] str = new String[procs.size()];
for (int i=0;i<procs.size();i++)
{
str[i] = ((Row)procs.get(i)).getValue(0).getString();
}
return str;
}
return null;
}
public boolean isAutoCommit()
{
return commitsize<=0;
}
/**
* @return Returns the databaseMeta.
*/
public DatabaseMeta getDatabaseMeta()
{
return databaseMeta;
}
/**
* Lock a tables in the database for write operations
* @param tableNames The tables to lock
* @throws KettleDatabaseException
*/
public void lockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLLockTables(tableNames);
if (sql!=null)
{
execStatements(sql);
}
}
/**
* Unlock certain tables in the database for write operations
* @param tableNames The tables to unlock
* @throws KettleDatabaseException
*/
public void unlockTables(String tableNames[]) throws KettleDatabaseException
{
String sql = databaseMeta.getSQLUnlockTables(tableNames);
if (sql!=null)
{
execStatement(sql);
}
}
}
|
package beast.app.beauti;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import beast.app.draw.ExtensionFileFilter;
import beast.core.Description;
import beast.core.Input;
import beast.core.BEASTObject;
import beast.core.Input.Validate;
import beast.evolution.alignment.Alignment;
import beast.evolution.alignment.FilteredAlignment;
import beast.evolution.alignment.Sequence;
import beast.evolution.datatype.DataType;
import beast.util.NexusParser;
import beast.util.XMLParser;
@Description("Class for creating new alignments to be edited by AlignmentListInputEditor")
public class BeautiAlignmentProvider extends BEASTObject {
public Input<BeautiSubTemplate> template = new Input<BeautiSubTemplate>("template", "template to be used after creating a new alignment. ", Validate.REQUIRED);
@Override
public void initAndValidate() throws Exception {}
/**
* return amount to which the provided matches an alignment
* The provider with the highest match will be used to edit the alignment
* */
int matches(Alignment alignment) {
return 1;
}
/**
* return new alignment, return null if not successfull
* **/
List<BEASTObject> getAlignments(BeautiDoc doc) {
JFileChooser fileChooser = new JFileChooser(Beauti.g_sDir);
fileChooser.addChoosableFileFilter(new ExtensionFileFilter(".xml", "Beast xml file (*.xml)"));
String[] extsf = { ".fas", ".fasta" };
fileChooser.addChoosableFileFilter(new ExtensionFileFilter(extsf, "Fasta file (*.fas)"));
String[] exts = { ".nex", ".nxs", ".nexus" };
fileChooser.addChoosableFileFilter(new ExtensionFileFilter(exts, "Nexus file (*.nex)"));
fileChooser.setDialogTitle("Load Sequence");
fileChooser.setMultiSelectionEnabled(true);
int rval = fileChooser.showOpenDialog(null);
if (rval == JFileChooser.APPROVE_OPTION) {
File[] files = fileChooser.getSelectedFiles();
return getAlignments(doc, files);
}
return null;
}
/**
* return new alignment given files
* @param doc
* @param files
* @return
*/
public List<BEASTObject> getAlignments(BeautiDoc doc, File[] files) {
List<BEASTObject> selectedPlugins = new ArrayList<BEASTObject>();
for (File file : files) {
String fileName = file.getName();
// if (sFileName.lastIndexOf('/') > 0) {
// Beauti.g_sDir = sFileName.substring(0,
// sFileName.lastIndexOf('/'));
if (fileName.toLowerCase().endsWith(".nex") || fileName.toLowerCase().endsWith(".nxs")
|| fileName.toLowerCase().endsWith(".nexus")) {
NexusParser parser = new NexusParser();
try {
parser.parseFile(file);
if (parser.filteredAlignments.size() > 0) {
/**
* sanity check: make sure the filters do not
* overlap
**/
int[] used = new int[parser.m_alignment.getSiteCount()];
Set<Integer> overlap = new HashSet<Integer>();
int partitionNr = 1;
for (Alignment data : parser.filteredAlignments) {
int[] indices = ((FilteredAlignment) data).indices();
for (int i : indices) {
if (used[i] > 0) {
overlap.add(used[i] * 10000 + partitionNr);
} else {
used[i] = partitionNr;
}
}
partitionNr++;
}
if (overlap.size() > 0) {
String overlaps = "<html>Warning: The following partitions overlap:<br/>";
for (int i : overlap) {
overlaps += parser.filteredAlignments.get(i / 10000 - 1).getID()
+ " overlaps with "
+ parser.filteredAlignments.get(i % 10000 - 1).getID() + "<br/>";
}
overlaps += "The first thing you might want to do is delete some of these partitions.</html>";
JOptionPane.showMessageDialog(null, overlaps);
}
/** add alignments **/
for (Alignment data : parser.filteredAlignments) {
selectedPlugins.add(data);
}
} else {
selectedPlugins.add(parser.m_alignment);
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Loading of " + fileName + " failed: " + ex.getMessage());
return null;
}
}
if (file.getName().toLowerCase().endsWith(".xml")) {
BEASTObject alignment = getXMLData(file);
selectedPlugins.add(alignment);
}
if (file.getName().toLowerCase().endsWith(".fas") || file.getName().toLowerCase().endsWith(".fasta")) {
BEASTObject alignment = getFASTAData(file);
selectedPlugins.add(alignment);
}
}
for (BEASTObject plugin : selectedPlugins) {
doc.addAlignmentWithSubnet((Alignment) plugin, getStartTemplate());
}
return selectedPlugins;
}
/** provide GUI for manipulating the alignment **/
void editAlignment(Alignment alignment, BeautiDoc doc) {
try {
AlignmentViewer viewer = new AlignmentViewer(alignment);
viewer.showInDialog();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Something went wrong viewing the alignment: " + e.getMessage());
e.printStackTrace();
}
}
/** check validity of the alignment,
* return null if there are no problens,
* return message string if something is fishy **/
String validateAlignment() {
return null;
}
/** return template to apply to this new alignment.
* By default, the partition template of the current beauti template is returned **/
BeautiSubTemplate getStartTemplate() {
return template.get();
}
static public BEASTObject getXMLData(File file) {
String sXML = "";
try {
// parse as BEAST 2 xml fragment
XMLParser parser = new XMLParser();
BufferedReader fin = new BufferedReader(new FileReader(file));
while (fin.ready()) {
sXML += fin.readLine() + "\n";
}
fin.close();
BEASTObject runnable = parser.parseBareFragment(sXML, false);
BEASTObject alignment = getAlignment(runnable);
alignment.initAndValidate();
return alignment;
} catch (Exception ex) {
// attempt to parse as BEAST 1 xml
try {
String ID = file.getName();
ID = ID.substring(0, ID.lastIndexOf('.')).replaceAll("\\..*", "");
BEASTObject alignment = parseBeast1XML(ID, sXML);
if (alignment != null) {
alignment.setID(file.getName().substring(0, file.getName().length() - 4).replaceAll("\\..*", ""));
}
return alignment;
} catch (Exception ex2) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Loading of " + file.getName() + " failed: " + ex.getMessage()
+ "\n" + ex2.getMessage());
}
return null;
}
}
private BEASTObject getFASTAData(File file) {
try {
// grab alignment data
Map<String, StringBuilder> seqMap = new HashMap<String, StringBuilder>();
List<String> sTaxa = new ArrayList<String>();
String currentTaxon = null;
BufferedReader fin = new BufferedReader(new FileReader(file));
String sMissing = "?";
String sGap = "-";
int nTotalCount = 4;
String datatype = "nucleotide";
while (fin.ready()) {
String line = fin.readLine();
if (line.startsWith(";")) {
// it is a comment, ignore
} else if (line.startsWith(">")) {
// it is a taxon
currentTaxon = line.substring(1).trim();
// only up to first space
currentTaxon = currentTaxon.replaceAll("\\s.*$", "");
} else {
// it is a data line
if (currentTaxon == null) {
throw new RuntimeException("Expected taxon defined on first line");
}
if (seqMap.containsKey(currentTaxon)) {
StringBuilder sb = seqMap.get(currentTaxon);
sb.append(line);
} else {
StringBuilder sb = new StringBuilder();
seqMap.put(currentTaxon, sb);
sb.append(line);
sTaxa.add(currentTaxon);
}
}
}
fin.close();
int nChar = -1;
Alignment alignment = new Alignment();
for (final String sTaxon : sTaxa) {
final StringBuilder bsData = seqMap.get(sTaxon);
String sData = bsData.toString();
sData = sData.replaceAll("\\s", "");
seqMap.put(sTaxon, new StringBuilder(sData));
if (nChar < 0) {nChar = sData.length();}
if (sData.length() != nChar) {
throw new Exception("Expected sequence of length " + nChar + " instead of " + sData.length() + " for taxon " + sTaxon);
}
// map to standard missing and gap chars
sData = sData.replace(sMissing.charAt(0), DataType.MISSING_CHAR);
sData = sData.replace(sGap.charAt(0), DataType.GAP_CHAR);
if (datatype.equals("nucleotide") && !sData.matches("[ACGTXacgtx?_]+")) {
datatype = "aminoacid";
nTotalCount = 20;
}
final Sequence sequence = new Sequence();
sData = sData.replaceAll("[Xx]", "?");
sequence.init(nTotalCount, sTaxon, sData);
sequence.setID(NexusParser.generateSequenceID(sTaxon));
alignment.sequenceInput.setValue(sequence, alignment);
}
String ID = file.getName();
ID = ID.substring(0, ID.lastIndexOf('.')).replaceAll("\\..*", "");
alignment.setID(ID);
alignment.dataTypeInput.setValue(datatype, alignment);
alignment.initAndValidate();
return alignment;
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Loading of " + file.getName() + " failed: " + e.getMessage());
}
return null;
}
private static BEASTObject parseBeast1XML(String ID, String sXML) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(sXML)));
doc.normalize();
NodeList alignments = doc.getElementsByTagName("alignment");
Alignment alignment = new Alignment();
alignment.dataTypeInput.setValue("nucleotide", alignment);
// parse first alignment
org.w3c.dom.Node node = alignments.item(0);
String sDataType = node.getAttributes().getNamedItem("dataType").getNodeValue();
int nTotalCount = 4;
if (sDataType == null) {
alignment.dataTypeInput.setValue("integer", alignment);
} else if (sDataType.toLowerCase().equals("dna") || sDataType.toLowerCase().equals("nucleotide")) {
alignment.dataTypeInput.setValue("nucleotide", alignment);
nTotalCount = 4;
} else if (sDataType.toLowerCase().equals("aminoacid") || sDataType.toLowerCase().equals("protein")) {
alignment.dataTypeInput.setValue("aminoacid", alignment);
nTotalCount = 20;
} else {
alignment.dataTypeInput.setValue("integer", alignment);
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
org.w3c.dom.Node child = children.item(i);
if (child.getNodeName().equals("sequence")) {
Sequence sequence = new Sequence();
// find the taxon
String taxon = "";
NodeList sequenceChildren = child.getChildNodes();
for (int j = 0; j < sequenceChildren.getLength(); j++) {
org.w3c.dom.Node child2 = sequenceChildren.item(j);
if (child2.getNodeName().equals("taxon")) {
taxon = child2.getAttributes().getNamedItem("idref").getNodeValue();
}
}
String data = child.getTextContent();
sequence.initByName("totalcount", nTotalCount, "taxon", taxon, "value", data);
sequence.setID("seq_" + taxon);
alignment.sequenceInput.setValue(sequence, alignment);
}
}
alignment.setID(ID);
alignment.initAndValidate();
return alignment;
} // parseBeast1XML
static BEASTObject getAlignment(BEASTObject plugin) throws IllegalArgumentException, IllegalAccessException {
if (plugin instanceof Alignment) {
return plugin;
}
for (BEASTObject plugin2 : plugin.listActivePlugins()) {
plugin2 = getAlignment(plugin2);
if (plugin2 != null) {
return plugin2;
}
}
return null;
}
}
|
package org.splevo.jamopp.diffing.similarity;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.ComposedSwitch;
import org.emftext.commons.layout.util.LayoutSwitch;
import org.emftext.language.java.annotations.AnnotationAttributeSetting;
import org.emftext.language.java.annotations.AnnotationInstance;
import org.emftext.language.java.annotations.util.AnnotationsSwitch;
import org.emftext.language.java.arrays.util.ArraysSwitch;
import org.emftext.language.java.classifiers.AnonymousClass;
import org.emftext.language.java.classifiers.Classifier;
import org.emftext.language.java.classifiers.ConcreteClassifier;
import org.emftext.language.java.classifiers.util.ClassifiersSwitch;
import org.emftext.language.java.commons.NamedElement;
import org.emftext.language.java.commons.util.CommonsSwitch;
import org.emftext.language.java.containers.CompilationUnit;
import org.emftext.language.java.containers.Package;
import org.emftext.language.java.containers.util.ContainersSwitch;
import org.emftext.language.java.expressions.AndExpression;
import org.emftext.language.java.expressions.AndExpressionChild;
import org.emftext.language.java.expressions.AssignmentExpression;
import org.emftext.language.java.expressions.AssignmentExpressionChild;
import org.emftext.language.java.expressions.ConditionalAndExpression;
import org.emftext.language.java.expressions.ConditionalAndExpressionChild;
import org.emftext.language.java.expressions.ConditionalOrExpression;
import org.emftext.language.java.expressions.ConditionalOrExpressionChild;
import org.emftext.language.java.expressions.EqualityExpression;
import org.emftext.language.java.expressions.EqualityExpressionChild;
import org.emftext.language.java.expressions.Expression;
import org.emftext.language.java.expressions.RelationExpression;
import org.emftext.language.java.expressions.RelationExpressionChild;
import org.emftext.language.java.expressions.UnaryExpression;
import org.emftext.language.java.expressions.UnaryExpressionChild;
import org.emftext.language.java.expressions.util.ExpressionsSwitch;
import org.emftext.language.java.generics.util.GenericsSwitch;
import org.emftext.language.java.imports.ClassifierImport;
import org.emftext.language.java.imports.StaticMemberImport;
import org.emftext.language.java.imports.util.ImportsSwitch;
import org.emftext.language.java.instantiations.ExplicitConstructorCall;
import org.emftext.language.java.instantiations.NewConstructorCall;
import org.emftext.language.java.instantiations.util.InstantiationsSwitch;
import org.emftext.language.java.literals.BooleanLiteral;
import org.emftext.language.java.literals.CharacterLiteral;
import org.emftext.language.java.literals.DecimalDoubleLiteral;
import org.emftext.language.java.literals.DecimalFloatLiteral;
import org.emftext.language.java.literals.DecimalIntegerLiteral;
import org.emftext.language.java.literals.DecimalLongLiteral;
import org.emftext.language.java.literals.HexDoubleLiteral;
import org.emftext.language.java.literals.HexFloatLiteral;
import org.emftext.language.java.literals.HexIntegerLiteral;
import org.emftext.language.java.literals.HexLongLiteral;
import org.emftext.language.java.literals.OctalIntegerLiteral;
import org.emftext.language.java.literals.OctalLongLiteral;
import org.emftext.language.java.literals.util.LiteralsSwitch;
import org.emftext.language.java.members.EnumConstant;
import org.emftext.language.java.members.Member;
import org.emftext.language.java.members.Method;
import org.emftext.language.java.members.util.MembersSwitch;
import org.emftext.language.java.modifiers.util.ModifiersSwitch;
import org.emftext.language.java.operators.AssignmentOperator;
import org.emftext.language.java.operators.EqualityOperator;
import org.emftext.language.java.operators.RelationOperator;
import org.emftext.language.java.operators.UnaryOperator;
import org.emftext.language.java.operators.util.OperatorsSwitch;
import org.emftext.language.java.parameters.OrdinaryParameter;
import org.emftext.language.java.parameters.Parameter;
import org.emftext.language.java.parameters.util.ParametersSwitch;
import org.emftext.language.java.references.ElementReference;
import org.emftext.language.java.references.IdentifierReference;
import org.emftext.language.java.references.MethodCall;
import org.emftext.language.java.references.Reference;
import org.emftext.language.java.references.ReferenceableElement;
import org.emftext.language.java.references.StringReference;
import org.emftext.language.java.references.util.ReferencesSwitch;
import org.emftext.language.java.statements.CatchBlock;
import org.emftext.language.java.statements.Conditional;
import org.emftext.language.java.statements.ExpressionStatement;
import org.emftext.language.java.statements.Jump;
import org.emftext.language.java.statements.JumpLabel;
import org.emftext.language.java.statements.LocalVariableStatement;
import org.emftext.language.java.statements.Return;
import org.emftext.language.java.statements.Statement;
import org.emftext.language.java.statements.StatementListContainer;
import org.emftext.language.java.statements.SynchronizedBlock;
import org.emftext.language.java.statements.Throw;
import org.emftext.language.java.statements.util.StatementsSwitch;
import org.emftext.language.java.types.ClassifierReference;
import org.emftext.language.java.types.NamespaceClassifierReference;
import org.emftext.language.java.types.Type;
import org.emftext.language.java.types.util.TypesSwitch;
import org.emftext.language.java.variables.AdditionalLocalVariable;
import org.emftext.language.java.variables.Variable;
import org.emftext.language.java.variables.util.VariablesSwitch;
import org.splevo.diffing.match.HierarchicalMatchEngine;
import org.splevo.diffing.util.NormalizationUtil;
import org.splevo.jamopp.diffing.util.JaMoPPModelUtil;
import org.splevo.jamopp.util.JaMoPPElementUtil;
import com.google.common.base.Strings;
/**
* Internal switch class to prove element similarity.
*
* <p>
* The similarity case methods do not need to check for null values. It is assumed that the calling
* class does a null value check for the elements to compare in advanced, such as done by the
* SimilarityChecker class.
* </p>
*
* <p>
* Check strategy:<br>
* First all "not-similar"-criteria are checked. If none hits, true will be returned.
* </p>
*/
public class SimilaritySwitch extends ComposedSwitch<Boolean> {
/** The logger for this class. */
private Logger logger = Logger.getLogger(SimilaritySwitch.class);
/** The object to compare the switched element with. */
private EObject compareElement = null;
/** Internal similarity checker to compare container elements etc. */
private SimilarityChecker similarityChecker = null;
/**
* Constructor requiring the element to compare with.
*
* @param compareElement
* The right-side / original element to check the similarity against.
* @param checkStatementPosition
* Flag if the similarity check should consider the position of a statement or not.
* @param classifierNormalizations
* A list of patterns replace any match in a classifier name with the defined
* replacement string.
* @param compilationUnitNormalizations
* A list of patterns replace any match in a compilation unit name with the defined
* replacement string.
* @param packageNormalizations
* A list of package normalization patterns.
*/
public SimilaritySwitch(EObject compareElement, boolean checkStatementPosition,
Map<Pattern, String> classifierNormalizations, Map<Pattern, String> compilationUnitNormalizations,
Map<Pattern, String> packageNormalizations) {
this.similarityChecker = new SimilarityChecker(classifierNormalizations, compilationUnitNormalizations,
packageNormalizations);
this.compareElement = compareElement;
addSwitch(new AnnotationsSimilaritySwitch());
addSwitch(new ArraysSimilaritySwitch());
addSwitch(new ClassifiersSimilaritySwitch(classifierNormalizations));
addSwitch(new CommonsSimilaritySwitch());
addSwitch(new ContainersSimilaritySwitch(compilationUnitNormalizations, packageNormalizations));
addSwitch(new ExpressionsSimilaritySwitch());
addSwitch(new GenericsSimilaritySwitch());
addSwitch(new ImportsSimilaritySwitch());
addSwitch(new InstantiationsSimilaritySwitch());
addSwitch(new LiteralsSimilaritySwitch());
addSwitch(new MembersSimilaritySwitch());
addSwitch(new ModifiersSimilaritySwitch());
addSwitch(new OperatorsSimilaritySwitch());
addSwitch(new ParametersSimilaritySwitch());
addSwitch(new ReferencesSimilaritySwitch());
addSwitch(new StatementsSimilaritySwitch(checkStatementPosition));
addSwitch(new TypesSimilaritySwitch());
addSwitch(new VariablesSimilaritySwitch());
addSwitch(new LayoutSimilaritySwitch());
}
/**
* Similarity decisions for annotation elements.
*/
private class AnnotationsSimilaritySwitch extends AnnotationsSwitch<Boolean> {
@Override
public Boolean caseAnnotationInstance(AnnotationInstance instance1) {
AnnotationInstance instance2 = (AnnotationInstance) compareElement;
Classifier class1 = instance1.getAnnotation();
Classifier class2 = instance2.getAnnotation();
Boolean classifierSimilarity = similarityChecker.isSimilar(class1, class2);
if (classifierSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
String namespace1 = instance1.getNamespacesAsString();
String namespace2 = instance2.getNamespacesAsString();
if (namespace1 == null) {
return (namespace2 == null);
} else {
return (namespace1.equals(namespace2));
}
}
@Override
public Boolean caseAnnotationAttributeSetting(AnnotationAttributeSetting setting1) {
AnnotationAttributeSetting setting2 = (AnnotationAttributeSetting) compareElement;
Boolean similarity = similarityChecker.isSimilar(setting1.getAttribute(), setting2.getAttribute());
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decision for array elements.
* <p>
* All array elements are strongly typed. They have no identifying attributes. Their location is
* implicitly checked by the {@link HierarchicalMatchEngine} and the runtime type is checked by
* the outer {@link SimilarityChecker}. So nothing to check here.
*/
private class ArraysSimilaritySwitch extends ArraysSwitch<Boolean> {
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for classifier elements.
*/
private class ClassifiersSimilaritySwitch extends ClassifiersSwitch<Boolean> {
/**
* A list of patterns replace any match in a classifier name with the defined replacement
* string.
*/
private Map<Pattern, String> classifierNormalizationPatterns = null;
/**
* Constructor to set the required configurations.
*
* @param classifierNormalizationPatterns
* A list of patterns replace any match in a classifier name with the defined
* replacement string.
*/
public ClassifiersSimilaritySwitch(Map<Pattern, String> classifierNormalizationPatterns) {
this.classifierNormalizationPatterns = classifierNormalizationPatterns;
}
/**
* Concrete classifiers such as classes and interface are identified by their location and
* name. The location is considered implicitly.
*
* @param classifier1
* the classifier to compare with the compareelement
* @return True or false whether they are similar or not.
*/
@Override
public Boolean caseConcreteClassifier(ConcreteClassifier classifier1) {
ConcreteClassifier classifier2 = (ConcreteClassifier) compareElement;
String name1 = NormalizationUtil.normalize(classifier1.getName(), classifierNormalizationPatterns);
String name2 = Strings.nullToEmpty(classifier2.getName());
return (name1.equals(name2));
}
}
/**
* Similarity decisions for commons elements.
*/
private class CommonsSimilaritySwitch extends CommonsSwitch<Boolean> {
/**
* Check named element
*
* Similarity is defined by the names of the elements.
*
* @param element1
* The method call to compare with the compare element.
* @return True As null always means null.
*/
@Override
public Boolean caseNamedElement(NamedElement element1) {
NamedElement element2 = (NamedElement) compareElement;
if (element1.getName() == null) {
return (element2.getName() == null);
}
return (element1.getName().equals(element2.getName()));
}
}
/**
* Similarity decisions for container elements.
*/
private class ContainersSimilaritySwitch extends ContainersSwitch<Boolean> {
private Map<Pattern, String> compilationUnitNormalizations = null;
private Map<Pattern, String> packageNormalizations = null;
/**
* Constructor to set the required configurations.
*
* @param compilationUnitNormalizations
* A list of patterns replace any match in a classifier name with the defined
* replacement string.
* @param packageNormalizations
* A list of package normalization patterns.
*/
public ContainersSimilaritySwitch(Map<Pattern, String> compilationUnitNormalizations,
Map<Pattern, String> packageNormalizations) {
this.compilationUnitNormalizations = compilationUnitNormalizations;
this.packageNormalizations = packageNormalizations;
}
/**
* Check the similarity of two CompilationUnits.<br>
* Similarity is checked by
* <ul>
* <li>Comparing their names (including renamings)</li>
* <li>Comparing their namespaces' values (including renamings)</li>
* </ul>
* Note: CompilationUnit names are full qualified. So it is important to apply classifier as
* well as package renaming normalizations to them.
*
* @param unit1
* The compilation unit to compare with the compareElement.
* @return True/False whether they are similar or not.
*/
@Override
public Boolean caseCompilationUnit(CompilationUnit unit1) {
CompilationUnit unit2 = (CompilationUnit) compareElement;
String name1 = NormalizationUtil.normalize(unit1.getName(), compilationUnitNormalizations);
name1 = NormalizationUtil.normalize(name1, packageNormalizations);
String name2 = unit2.getName();
if (!name1.equals(name2)) {
return Boolean.FALSE;
}
String namespaceString1 = NormalizationUtil.normalizeNamespace(unit1.getNamespacesAsString(),
packageNormalizations);
String namespaceString2 = Strings.nullToEmpty(unit2.getNamespacesAsString());
if (!namespaceString1.equals(namespaceString2)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* Check package similarity.<br>
* Similarity is checked by
* <ul>
* <li>full qualified package path</li>
* </ul>
*
* @param package1
* The package to compare with the compare element.
* @return True/False if the packages are similar or not.
*/
@Override
public Boolean casePackage(Package package1) {
Package package2 = (Package) compareElement;
String packagePath1 = JaMoPPModelUtil.buildNamespacePath(package1);
packagePath1 = NormalizationUtil.normalizeNamespace(packagePath1, packageNormalizations);
String packagePath2 = JaMoPPModelUtil.buildNamespacePath(package2);
if (!packagePath1.equals(packagePath2)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}
/**
* Similarity decisions for expression elements.
* <p>
* All expression elements are strong typed with no identifying attributes or non-containment
* references. While their location is checked by the used {@link HierarchicalMatchEngine} and
* the runtime types are checked by the wrapping {@link SimilarityChecker} all elements that
* arrive here can be assumed to similar.
* </p>
*/
private class ExpressionsSimilaritySwitch extends ExpressionsSwitch<Boolean> {
@Override
public Boolean caseAssignmentExpression(AssignmentExpression exp1) {
AssignmentExpression exp2 = (AssignmentExpression) compareElement;
AssignmentExpressionChild child1 = exp1.getChild();
AssignmentExpressionChild child2 = exp2.getChild();
Boolean childSimilarity = similarityChecker.isSimilar(child1, child2);
if (childSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
AssignmentOperator op1 = exp1.getAssignmentOperator();
AssignmentOperator op2 = exp2.getAssignmentOperator();
Boolean operatorSimilarity = similarityChecker.isSimilar(op1, op2);
if (operatorSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
Expression value1 = exp1.getValue();
Expression value2 = exp2.getValue();
Boolean valueSimilarity = similarityChecker.isSimilar(value1, value2);
if (valueSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseEqualityExpression(EqualityExpression exp1) {
EqualityExpression exp2 = (EqualityExpression) compareElement;
// check operator equality
EList<EqualityOperator> operators1 = exp1.getEqualityOperators();
EList<EqualityOperator> operators2 = exp2.getEqualityOperators();
Boolean operatorSimilarity = similarityChecker.areSimilar(operators1, operators2);
if (operatorSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
// check expression equality
EList<EqualityExpressionChild> children1 = exp1.getChildren();
EList<EqualityExpressionChild> children2 = exp2.getChildren();
Boolean childSimilarity = similarityChecker.areSimilar(children1, children2);
if (childSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseRelationExpression(RelationExpression exp1) {
RelationExpression exp2 = (RelationExpression) compareElement;
// check operator equality
EList<RelationOperator> operators1 = exp1.getRelationOperators();
EList<RelationOperator> operators2 = exp2.getRelationOperators();
Boolean operatorSimilarity = similarityChecker.areSimilar(operators1, operators2);
if (operatorSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
// check expression equality
EList<RelationExpressionChild> children1 = exp1.getChildren();
EList<RelationExpressionChild> children2 = exp2.getChildren();
Boolean childSimilarity = similarityChecker.areSimilar(children1, children2);
if (childSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseAndExpression(AndExpression exp1) {
AndExpression exp2 = (AndExpression) compareElement;
// check expression equality
EList<AndExpressionChild> children1 = exp1.getChildren();
EList<AndExpressionChild> children2 = exp2.getChildren();
Boolean childSimilarity = similarityChecker.areSimilar(children1, children2);
if (childSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseUnaryExpression(UnaryExpression exp1) {
UnaryExpression exp2 = (UnaryExpression) compareElement;
// check operator equality
EList<UnaryOperator> operators1 = exp1.getOperators();
EList<UnaryOperator> operators2 = exp2.getOperators();
Boolean operatorSimilarity = similarityChecker.areSimilar(operators1, operators2);
if (operatorSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
// check expression equality
UnaryExpressionChild child1 = exp1.getChild();
UnaryExpressionChild child2 = exp2.getChild();
return similarityChecker.isSimilar(child1, child2);
}
@Override
public Boolean caseConditionalOrExpression(ConditionalOrExpression exp1) {
ConditionalOrExpression exp2 = (ConditionalOrExpression) compareElement;
// check expression equality
EList<ConditionalOrExpressionChild> children1 = exp1.getChildren();
EList<ConditionalOrExpressionChild> children2 = exp2.getChildren();
return similarityChecker.areSimilar(children1, children2);
}
@Override
public Boolean caseConditionalAndExpression(ConditionalAndExpression exp1) {
ConditionalAndExpression exp2 = (ConditionalAndExpression) compareElement;
// check expression equality
EList<ConditionalAndExpressionChild> children1 = exp1.getChildren();
EList<ConditionalAndExpressionChild> children2 = exp2.getChildren();
return similarityChecker.areSimilar(children1, children2);
}
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for the generic elements.
*/
private class GenericsSimilaritySwitch extends GenericsSwitch<Boolean> {
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for the import elements.
*/
private class ImportsSimilaritySwitch extends ImportsSwitch<Boolean> {
@Override
public Boolean caseClassifierImport(ClassifierImport import1) {
ClassifierImport import2 = (ClassifierImport) compareElement;
Boolean similarity = similarityChecker.isSimilar(import1.getClassifier(), import2.getClassifier());
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
String namespace1 = Strings.nullToEmpty(import1.getNamespacesAsString());
String namespace2 = Strings.nullToEmpty(import2.getNamespacesAsString());
return (namespace1.equals(namespace2));
}
@Override
public Boolean caseStaticMemberImport(StaticMemberImport import1) {
StaticMemberImport import2 = (StaticMemberImport) compareElement;
if (import1.getStaticMembers().size() != import2.getStaticMembers().size()) {
return Boolean.FALSE;
}
for (int i = 0; i < import1.getStaticMembers().size(); i++) {
ReferenceableElement member1 = import1.getStaticMembers().get(i);
ReferenceableElement member2 = import2.getStaticMembers().get(i);
Boolean similarity = similarityChecker.isSimilar(member1, member2);
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
String namespace1 = Strings.nullToEmpty(import1.getNamespacesAsString());
String namespace2 = Strings.nullToEmpty(import2.getNamespacesAsString());
return (namespace1.equals(namespace2));
}
}
/**
* Similarity decisions for object instantiation elements.
*/
private class InstantiationsSimilaritySwitch extends InstantiationsSwitch<Boolean> {
/**
* Check class instance creation similarity.<br>
* Similarity is checked by
* <ul>
* <li>instance type similarity</li>
* <li>number of constructor arguments</li>
* <li>types of constructor arguments</li>
* </ul>
*
* @param call1
* The class instance creation to compare with the compare element.
* @return True/False if the class instance creations are similar or not.
*/
@Override
public Boolean caseExplicitConstructorCall(ExplicitConstructorCall call1) {
ExplicitConstructorCall call2 = (ExplicitConstructorCall) compareElement;
// check the class instance types
Boolean typeSimilarity = similarityChecker.isSimilar(call1.getType(), call2.getType());
if (typeSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
// check number of type arguments
EList<Expression> cic1Args = call1.getArguments();
EList<Expression> cic2Args = call2.getArguments();
if (cic1Args.size() != cic2Args.size()) {
return Boolean.FALSE;
}
// check the argument similarity
for (int i = 0; i < cic1Args.size(); i++) {
Boolean argumentSimilarity = similarityChecker.isSimilar(cic1Args.get(i), cic2Args.get(i));
if (argumentSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
@Override
public Boolean caseNewConstructorCall(NewConstructorCall call1) {
NewConstructorCall call2 = (NewConstructorCall) compareElement;
Type type1 = call1.getTypeReference().getTarget();
Type type2 = call2.getTypeReference().getTarget();
Boolean typeSimilarity = similarityChecker.isSimilar(type1, type2);
if (typeSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
EList<Type> types1 = call1.getArgumentTypes();
EList<Type> types2 = call2.getArgumentTypes();
if (types1.size() != types2.size()) {
return Boolean.FALSE;
}
for (int i = 0; i < types1.size(); i++) {
Type argType1 = types1.get(i);
Type argType2 = types2.get(i);
Boolean similarity = similarityChecker.isSimilar(argType1, argType2);
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for literal elements.
*/
private class LiteralsSimilaritySwitch extends LiteralsSwitch<Boolean> {
@Override
public Boolean caseBooleanLiteral(BooleanLiteral boolean1) {
BooleanLiteral boolean2 = (BooleanLiteral) compareElement;
return (boolean1.isValue() == boolean2.isValue());
}
@Override
public Boolean caseCharacterLiteral(CharacterLiteral char1) {
CharacterLiteral char2 = (CharacterLiteral) compareElement;
return (char1.getValue() == char2.getValue());
}
@Override
public Boolean caseDecimalFloatLiteral(DecimalFloatLiteral float1) {
DecimalFloatLiteral float2 = (DecimalFloatLiteral) compareElement;
return (float1.getDecimalValue() == float2.getDecimalValue());
}
@Override
public Boolean caseHexFloatLiteral(HexFloatLiteral float1) {
HexFloatLiteral float2 = (HexFloatLiteral) compareElement;
return (float1.getHexValue() == float2.getHexValue());
}
@Override
public Boolean caseDecimalDoubleLiteral(DecimalDoubleLiteral double1) {
DecimalDoubleLiteral double2 = (DecimalDoubleLiteral) compareElement;
return (double1.getDecimalValue() == double2.getDecimalValue());
}
@Override
public Boolean caseHexDoubleLiteral(HexDoubleLiteral double1) {
HexDoubleLiteral double2 = (HexDoubleLiteral) compareElement;
return (double1.getHexValue() == double2.getHexValue());
}
@Override
public Boolean caseDecimalIntegerLiteral(DecimalIntegerLiteral int1) {
DecimalIntegerLiteral int2 = (DecimalIntegerLiteral) compareElement;
return (int1.getDecimalValue().equals(int2.getDecimalValue()));
}
@Override
public Boolean caseHexIntegerLiteral(HexIntegerLiteral int1) {
HexIntegerLiteral int2 = (HexIntegerLiteral) compareElement;
return (int1.getHexValue().equals(int2.getHexValue()));
}
@Override
public Boolean caseOctalIntegerLiteral(OctalIntegerLiteral int1) {
OctalIntegerLiteral int2 = (OctalIntegerLiteral) compareElement;
return (int1.getOctalValue().equals(int2.getOctalValue()));
}
@Override
public Boolean caseDecimalLongLiteral(DecimalLongLiteral long1) {
DecimalLongLiteral long2 = (DecimalLongLiteral) compareElement;
return (long1.getDecimalValue().equals(long2.getDecimalValue()));
}
@Override
public Boolean caseHexLongLiteral(HexLongLiteral long1) {
HexLongLiteral long2 = (HexLongLiteral) compareElement;
return (long1.getHexValue().equals(long2.getHexValue()));
}
@Override
public Boolean caseOctalLongLiteral(OctalLongLiteral long1) {
OctalLongLiteral long2 = (OctalLongLiteral) compareElement;
return (long1.getOctalValue().equals(long2.getOctalValue()));
}
/**
* Check null literal similarity.<br>
*
* Null literals are always assumed to be similar.
*
* @param object
* The literal to compare with the compare element.
* @return True As null always means null.
*/
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for the member elements.
*/
private class MembersSimilaritySwitch extends MembersSwitch<Boolean> {
/**
* Check abstract method declaration similarity. Similarity is checked by
* <ul>
* <li>name</li>
* <li>parameter list size</li>
* <li>parameter types</li>
* <li>name</li>
* <li>container for
* <ul>
* <li>AbstractTypeDeclaration</li>
* <li>AnonymousClassDeclaration</li>
* <li>Model</li>
* </ul>
* </li>
* </ul>
*
* The container must be checked to check similarity for referenced methods.
*
*
* @param method1
* The abstract method declaration to compare with the compare element.
* @return True/False if the abstract method declarations are similar or not.
*/
@Override
public Boolean caseMethod(Method method1) {
Method method2 = (Method) compareElement;
// if methods have different names they are not similar.
if (!method1.getName().equals(method2.getName())) {
return Boolean.FALSE;
}
if (method1.getParameters().size() != method2.getParameters().size()) {
return Boolean.FALSE;
}
for (int i = 0; i < method1.getParameters().size(); i++) {
Parameter param1 = method1.getParameters().get(i);
Parameter param2 = method2.getParameters().get(i);
Type type1 = param1.getTypeReference().getTarget();
Type type2 = param2.getTypeReference().getTarget();
Boolean typeSimilarity = similarityChecker.isSimilar(type1, type2);
if (typeSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
if (method1.getContainingConcreteClassifier() != null) {
ConcreteClassifier type1 = method1.getContainingConcreteClassifier();
ConcreteClassifier type2 = method2.getContainingConcreteClassifier();
return similarityChecker.isSimilar(type1, type2);
}
if (method1.getContainingAnonymousClass() != null) {
AnonymousClass type1 = method1.getContainingAnonymousClass();
AnonymousClass type2 = method2.getContainingAnonymousClass();
Boolean typeSimilarity = similarityChecker.isSimilar(type1, type2);
if (typeSimilarity != null) {
return typeSimilarity;
}
}
logger.warn("MethodDeclaration in unknown container: " + method1.getName() + " : "
+ method1.eContainer().getClass().getSimpleName());
return super.caseMethod(method1);
}
@Override
public Boolean caseEnumConstant(EnumConstant const1) {
EnumConstant const2 = (EnumConstant) compareElement;
String name1 = Strings.nullToEmpty(const1.getName());
String name2 = Strings.nullToEmpty(const2.getName());
return (name1.equals(name2));
}
@Override
public Boolean caseMember(Member member1) {
Member member2 = (Member) compareElement;
String name1 = Strings.nullToEmpty(member1.getName());
String name2 = Strings.nullToEmpty(member2.getName());
return (name1.equals(name2));
}
}
/**
* Similarity decisions for modifier elements.
* <p>
* All modifier elements are strong typed with no identifying attributes or non-containment
* references. While their location is checked by the used {@link HierarchicalMatchEngine} and
* the runtime types are checked by the wrapping {@link SimilarityChecker} all elements that
* arrive here can be assumed to similar.
* </p>
*/
private class ModifiersSimilaritySwitch extends ModifiersSwitch<Boolean> {
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for operator elements.
* <p>
* All operator elements are strong typed with no identifying attributes or non-containment
* references. While their location is checked by the used {@link HierarchicalMatchEngine} and
* the runtime types are checked by the wrapping {@link SimilarityChecker} all elements that
* arrive here can be assumed to similar.
* </p>
*/
private class OperatorsSimilaritySwitch extends OperatorsSwitch<Boolean> {
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for parameter elements.
* <p>
* Parameters are variables and for this named elements. So their names must be checked but no
* more identifying attributes or references exist.
* </p>
*/
private class ParametersSimilaritySwitch extends ParametersSwitch<Boolean> {
@Override
public Boolean caseParameter(Parameter param1) {
Parameter param2 = (Parameter) compareElement;
String name1 = Strings.nullToEmpty(param1.getName());
String name2 = Strings.nullToEmpty(param2.getName());
return (name1.equals(name2));
}
}
/**
* Similarity decisions for reference elements.
*/
private class ReferencesSimilaritySwitch extends ReferencesSwitch<Boolean> {
@Override
public Boolean caseStringReference(StringReference ref1) {
StringReference ref2 = (StringReference) compareElement;
if (ref1.getValue() == null) {
return (ref2.getValue() == null);
}
return (ref1.getValue().equals(ref2.getValue()));
}
@Override
public Boolean caseIdentifierReference(IdentifierReference ref1) {
IdentifierReference ref2 = (IdentifierReference) compareElement;
ReferenceableElement target1 = ref1.getTarget();
ReferenceableElement target2 = ref2.getTarget();
// target identity similarity
Boolean similarity = similarityChecker.isSimilar(target1, target2);
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
if (target1 != null) {
// target container similarity
// check this only if the reference target is located
// in another container than the reference itself.
// Otherwise such a situation would lead to endless loops
// e.g. for for "(Iterator i = c.iterator(); i.hasNext(); ) {"
// Attention: The reference could be encapsulated by an expression!
EObject ref1Container = JaMoPPElementUtil.getNonExpressionContainer(ref1);
EObject ref2Container = JaMoPPElementUtil.getNonExpressionContainer(ref2);
EObject target1Container = target1.eContainer();
EObject target2Container = target2.eContainer();
if (target1Container != ref1Container && target2Container != ref2Container) {
Boolean containerSimilarity = similarityChecker.isSimilar(target1Container, target2Container);
if (containerSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
}
Reference next1 = ref1.getNext();
Reference next2 = ref2.getNext();
Boolean nextSimilarity = similarityChecker.isSimilar(next1, next2);
if (nextSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* Check element reference similarity.<br>
*
* Is checked by the target (the method called). Everything else are containment references
* checked indirectly.
*
* @param ref1
* The method call to compare with the compare element.
* @return True As null always means null.
*/
@Override
public Boolean caseElementReference(ElementReference ref1) {
ElementReference ref2 = (ElementReference) compareElement;
Boolean targetSimilarity = similarityChecker.isSimilar(ref1.getTarget(), ref2.getTarget());
if (targetSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* Proof method call similarity.
*
* Similarity is decided by the method referenced and the arguments passed by.
*
* @param call1
* The left / modified method call to compare with the original one.
* @return True/False if the method calls are similar or not.
*/
@Override
public Boolean caseMethodCall(MethodCall call1) {
MethodCall call2 = (MethodCall) compareElement;
Boolean targetSimilarity = similarityChecker.isSimilar(call1.getTarget(), call2.getTarget());
if (targetSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
if (call1.getArguments().size() != call2.getArguments().size()) {
return Boolean.FALSE;
}
for (int i = 0; i < call1.getArguments().size(); i++) {
Expression exp1 = call1.getArguments().get(i);
Expression exp2 = call2.getArguments().get(i);
Boolean argSimilarity = similarityChecker.isSimilar(exp1, exp2);
if (argSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
}
Boolean nextSimilarity = similarityChecker.isSimilar(call1.getNext(), call2.getNext());
if (nextSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for the statement elements.
*/
private class StatementsSimilaritySwitch extends StatementsSwitch<Boolean> {
/**
* Flag if the position of a statement should be considered for similarity or not.
*/
private boolean checkStatementPosition = true;
/**
* Constructor to set required configurations.
*
* @param checkStatementPosition
* Flag if the position of a statement should be considered for similarity or
* not.
*/
public StatementsSimilaritySwitch(boolean checkStatementPosition) {
this.checkStatementPosition = checkStatementPosition;
}
/**
* Check expression statement similarity.<br>
* Similarity is checked by
* <ul>
* <li>similarity statements expressions</li>
* </ul>
*
* @param statement1
* The expression statement to compare with the compare element.
* @return True/False if the expression statements are similar or not.
*/
@Override
public Boolean caseExpressionStatement(ExpressionStatement statement1) {
ExpressionStatement statement2 = (ExpressionStatement) compareElement;
Expression exp1 = statement1.getExpression();
Expression exp2 = statement2.getExpression();
Boolean expSimilarity = similarityChecker.isSimilar(exp1, exp2);
if (expSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
// check predecessor similarity
if (checkStatementPosition) {
if (differentPredecessor(statement1, statement2) && differentSuccessor(statement1, statement2)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
/**
* Check the similarity of a variable declaration.
*
* The similarity is decided by the declared variables name only. A changed variable type or
* value initialization should lead to a changed statement not a new one.
*
* @param varStmt1
* The variable to compare with the original / right-side one
* @return True/False if they are similar or not.
*/
@Override
public Boolean caseLocalVariableStatement(LocalVariableStatement varStmt1) {
LocalVariableStatement varStmt2 = (LocalVariableStatement) compareElement;
Variable var1 = varStmt1.getVariable();
Variable var2 = varStmt2.getVariable();
Boolean varSimilarity = similarityChecker.isSimilar(var1, var2);
if (varSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
/**
* Check return statement similarity.<br>
* Similarity is checked by
* <ul>
* <li>expressions similarity</li>
* </ul>
*
* @param returnStatement1
* The return statement to compare with the compare element.
* @return True/False if the return statements are similar or not.
*/
@Override
public Boolean caseReturn(Return returnStatement1) {
Return returnStatement2 = (Return) compareElement;
Expression exp1 = returnStatement1.getReturnValue();
Expression exp2 = returnStatement2.getReturnValue();
return similarityChecker.isSimilar(exp1, exp2);
}
/**
* Check synchronized statement similarity.<br>
* Similarity is checked by
* <ul>
* <li>expression similarity</li>
* </ul>
*
* @param statement1
* The synchronized statement to compare with the compare element.
* @return True/False if the synchronized statements are similar or not.
*/
@Override
public Boolean caseSynchronizedBlock(SynchronizedBlock statement1) {
SynchronizedBlock statement2 = (SynchronizedBlock) compareElement;
Expression exp1 = statement1.getLockProvider();
Expression exp2 = statement2.getLockProvider();
Boolean similarity = similarityChecker.isSimilar(exp1, exp2);
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
if (checkStatementPosition) {
if (differentPredecessor(statement1, statement2)) {
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
/**
* Check throw statement similarity.<br>
*
* Only one throw statement can exist at the same code location. As a result the container
* similarity checked implicitly is enough for this.
*
* @param throwStatement1
* The throw statement to compare with the compare element.
* @return True/False if the throw statements are similar or not.
*/
@Override
public Boolean caseThrow(Throw throwStatement1) {
return Boolean.TRUE;
}
@Override
public Boolean caseCatchBlock(CatchBlock catchBlock1) {
CatchBlock catchBlock2 = (CatchBlock) compareElement;
OrdinaryParameter catchedException1 = catchBlock1.getParameter();
OrdinaryParameter catchedException2 = catchBlock2.getParameter();
Boolean exceptionSimilarity = similarityChecker.isSimilar(catchedException1, catchedException2);
if (exceptionSimilarity == Boolean.FALSE) {
return exceptionSimilarity;
}
return Boolean.TRUE;
}
/**
* Check if two conditional statements are similar.
*
* Similarity is checked by:
* <ul>
* <li>similarity of the expressions</li>
* </ul>
*
* The then and else statements are not checked as part of the condition statement check
* because this is only about the container if statement similarity. The contained
* statements are checked in a separate step of the compare process if the enclosing
* condition statement matches.
*
* @param conditional1
* The statement to compare with the compare element.
* @return True/False whether they are similar or not.
*/
@Override
public Boolean caseConditional(Conditional conditional1) {
Conditional conditional2 = (Conditional) compareElement;
Expression expression1 = conditional1.getCondition();
Expression expression2 = conditional2.getCondition();
Boolean expressionSimilarity = similarityChecker.isSimilar(expression1, expression2);
if (expressionSimilarity == Boolean.FALSE) {
return expressionSimilarity;
}
return Boolean.TRUE;
}
@Override
public Boolean caseJump(Jump jump1) {
Jump jump2 = (Jump) compareElement;
Boolean similarity = similarityChecker.isSimilar(jump1.getTarget(), jump2.getTarget());
if (similarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseJumpLabel(JumpLabel label1) {
JumpLabel label2 = (JumpLabel) compareElement;
String name1 = Strings.nullToEmpty(label1.getName());
String name2 = Strings.nullToEmpty(label2.getName());
return (name1.equals(name2));
}
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
/**
* Decide of two statements differ from each other or not.
*
* @param statement1
* The first statement to compare
* @param statement2
* The second statement to compare.
* @return True if they differ, null if not.
*/
private boolean differentPredecessor(Statement statement1, Statement statement2) {
Statement pred1 = getPredecessor(statement1);
Statement pred2 = getPredecessor(statement2);
Boolean similarity = similarityChecker.isSimilar(pred1, pred2, false);
return similarity == Boolean.FALSE;
}
/**
* Check if two statements have differing successor statements.
*
* @param statement1
* The first statement to check.
* @param statement2
* The second statement to check.
* @return True if their successor differ, false if not.
*/
private boolean differentSuccessor(ExpressionStatement statement1, ExpressionStatement statement2) {
Statement pred1 = getSuccessor(statement1);
Statement pred2 = getSuccessor(statement2);
Boolean similarity = similarityChecker.isSimilar(pred1, pred2, false);
return similarity == Boolean.FALSE;
}
/**
* Get the predecessor statement of a statement within the parents container statement list.<br>
* If a statement is the first, the only one, or the container is not a
* {@link StatementListContainer}, or no predecessor exists, null will be returned.
*
* @param statement
* The statement to get the predecessor for.
* @return The predecessor or null if non exists.
*/
private Statement getPredecessor(Statement statement) {
int pos = JaMoPPElementUtil.getPositionInContainer(statement);
if (pos > 0) {
StatementListContainer container = (StatementListContainer) statement.eContainer();
return container.getStatements().get(pos - 1);
}
return null;
}
/**
* Get the successor statement of a statement within the parents container statement list.<br>
* If a statement is the last, the only one, or the container is not a
* {@link StatementListContainer}, no successor exists, null will be returned.
*
* @param statement
* The statement to get the predecessor for.
* @return The predecessor or null if non exists.
*/
private Statement getSuccessor(Statement statement) {
int pos = JaMoPPElementUtil.getPositionInContainer(statement);
if (pos != -1) {
StatementListContainer container = (StatementListContainer) statement.eContainer();
if (container.getStatements().size() > pos + 1) {
return container.getStatements().get(pos + 1);
}
}
return null;
}
}
/**
* Similarity decisions for elements of the types package.
*/
private class TypesSimilaritySwitch extends TypesSwitch<Boolean> {
/**
* Check element reference similarity.<br>
*
* Is checked by the target (the method called). Everything else are containment references
* checked indirectly.
*
* @param ref1
* The method call to compare with the compare element.
* @return True As null always means null.
*/
@Override
public Boolean caseClassifierReference(ClassifierReference ref1) {
ClassifierReference ref2 = (ClassifierReference) compareElement;
Boolean targetSimilarity = similarityChecker.isSimilar(ref1.getTarget(), ref2.getTarget());
if (targetSimilarity == Boolean.FALSE) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseNamespaceClassifierReference(NamespaceClassifierReference ref1) {
NamespaceClassifierReference ref2 = (NamespaceClassifierReference) compareElement;
String namespace1 = Strings.nullToEmpty(ref1.getNamespacesAsString());
String namespace2 = Strings.nullToEmpty(ref2.getNamespacesAsString());
return (namespace1.equals(namespace2));
}
/**
* Primitive type elements are strongly typed and the exact type is already checked by the
* outer {@link SimilarityChecker}. <br>
* {@inheritDoc}
*/
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* Similarity decisions for the variable elements.
*/
private class VariablesSimilaritySwitch extends VariablesSwitch<Boolean> {
/**
* Check variable declaration similarity.<br>
* Similarity is checked by
* <ul>
* <li>variable name</li>
* <li>variable container (name space)</li>
* </ul>
*
* @param var1
* The variable declaration to compare with the compare element.
* @return True/False if the variable declarations are similar or not.
*/
@Override
public Boolean caseVariable(Variable var1) {
Variable var2 = (Variable) compareElement;
// check the variables name equality
if (!var1.getName().equals(var2.getName())) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
@Override
public Boolean caseAdditionalLocalVariable(AdditionalLocalVariable var1) {
AdditionalLocalVariable var2 = (AdditionalLocalVariable) compareElement;
// check the variables name equality
String name1 = Strings.nullToEmpty(var1.getName());
String name2 = Strings.nullToEmpty(var2.getName());
if (!name1.equals(name2)) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}
/**
* Similarity Decisions for layout information is always true as they are not considered for
* now.
*/
private class LayoutSimilaritySwitch extends LayoutSwitch<Boolean> {
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
/**
* The default case for not explicitly handled elements always returns null to identify the open
* decision.
*
* @param object
* The object to compare with the compare element.
* @return null
*/
@Override
public Boolean defaultCase(EObject object) {
return Boolean.TRUE;
}
}
|
package build.pluto.dependency;
import java.io.File;
import java.io.IOException;
import build.pluto.builder.BuildUnitProvider;
import org.sugarj.common.FileCommands;
import build.pluto.builder.BuildManager;
public abstract class RemoteRequirement implements Requirement {
private static final long serialVersionUID = -637138545509445926L;
public static final long CHECK_NEVER = -1L;
public static final long CHECK_ALWAYS = 0L;
private long consistencyCheckInterval;
private File persistentPath;
/**
* @param persistentPath
* the file in which the timestamp of the last successful consistency
* check between remote and local resource was made.
* @param consistencyCheckInterval
* the milliseconds how long the consistency check between remote and
* local resource are not made. 0L means it gets checked everytime
* and -1L means it does not get checked ever.
*/
public RemoteRequirement(File persistentPath, long consistencyCheckInterval) {
if (consistencyCheckInterval < CHECK_NEVER) {
throw new IllegalArgumentException("consistencyCheckInterval has to be greater or equal than -1L");
}
this.persistentPath = persistentPath;
this.consistencyCheckInterval = consistencyCheckInterval;
long timestamp = getStartingTimestamp();
this.writePersistentPath(timestamp);
}
/**
* This implementation calls needsConsistencyCheck, isRemoteResourceAccessible,
* isLocalResourceAvailable and isConsistentWithRemote
*/
@Override
public boolean isConsistent() {
boolean offline = !isRemoteResourceAccessible();
if (offline)
return true;
boolean localAvailable = isLocalResourceAvailable();
if (!offline && !localAvailable)
return false;
long timestamp = getStartingTimestamp();
if (!needsConsistencyCheck(timestamp))
return true;
if (isConsistentWithRemote()) {
writePersistentPath(timestamp);
return true;
}
else
return false;
}
@Override
public boolean tryMakeConsistent(BuildUnitProvider manager) throws IOException {
return isConsistent();
}
protected long getStartingTimestamp() {
Thread currentThread = Thread.currentThread();
return BuildManager.getStartingTimeOfBuildManager(currentThread);
}
/**
* Checks if the remote resource can be accessed.
*
* @return true if remote resourse can be accessed.
*/
protected abstract boolean isRemoteResourceAccessible();
/**
* Checks if a version of the remote resource is available locally.
*
* @return true if a version of the remote resourse is locally available.
*/
protected abstract boolean isLocalResourceAvailable();
/**
* Checks if the local state is consistent with the remote state.
*
* @return true if local state is consistent with remote state.
*/
protected abstract boolean isConsistentWithRemote();
/**
* Checks if a consistencycheck needs to be made.
*
* @param currentTime
* the time to check if the consistency needs to be checked.
* @return true if a consistencycheck needs to be made.
*/
private boolean needsConsistencyCheck(long currentTime) {
if (consistencyCheckInterval == CHECK_NEVER)
return false;
if (!FileCommands.exists(persistentPath)) {
writePersistentPath(currentTime);
return true;
}
try {
long lastConsistencyCheck = readPersistentPath();
long afterInterval = lastConsistencyCheck + consistencyCheckInterval;
// if afterInterval is non-positive overflow occured
// can happen if consistencyCheckInterval is unusually big
if (afterInterval > 0 && afterInterval < currentTime)
return true;
} catch (IOException e) {
return true;
}
return false;
}
private long readPersistentPath() throws IOException {
String persistentPathContent = FileCommands.readFileAsString(persistentPath);
return Long.parseLong(persistentPathContent.replace("\n", ""));
}
private void writePersistentPath(long timeStamp) {
try {
if (!persistentPath.exists()) {
FileCommands.createFile(persistentPath);
}
FileCommands.writeToFile(persistentPath, String.valueOf(timeStamp));
} catch (IOException e) {
throw new RuntimeException("Failed to write remote requirement time stamp.", e);
}
}
}
|
package org.onebeartoe.modeling.openscad.test.suite;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.onebeartoe.modeling.openscad.test.suite.utils.OpenScadTestSuiteService;
import org.testng.annotations.Test;
public class OpenScadTestSuiteTest
{
private Logger logger;
public OpenScadTestSuiteTest()
{
logger = Logger.getLogger( getClass().getName() );
}
@Test(groups = {"test-suite"})
public void testSuite() throws Exception
{
OpenScadTestSuiteService testSuite = new OpenScadTestSuiteService();
RunProfile runProfile = new RunProfile();
runProfile.executablePath = "openscad-nightly";
runProfile.path = "../library/src/main/openscad/name-tags/examples/owl-of-diego/";
runProfile.redirectOpenscad = false;
testSuite.serviceRequest(runProfile);
}
}
|
package ca.cumulonimbus.pressurenetsdk;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabaseLockedException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
/**
* Represent developer-facing pressureNET API Background task; manage and run
* everything Handle Intents
*
* @author jacob
*
*/
public class CbService extends Service {
private CbDataCollector dataCollector;
private CbLocationManager locationManager;
private CbSettingsHandler settingsHandler;
private CbDb db;
public CbService service = this;
private String mAppDir;
IBinder mBinder;
ReadingSender sender;
Message recentMsg;
String serverURL = CbConfiguration.SERVER_URL;
public static String ACTION_SEND_MEASUREMENT = "SendMeasurement";
// Service Interaction API Messages
public static final int MSG_OKAY = 0;
public static final int MSG_STOP = 1;
public static final int MSG_GET_BEST_LOCATION = 2;
public static final int MSG_BEST_LOCATION = 3;
public static final int MSG_GET_BEST_PRESSURE = 4;
public static final int MSG_BEST_PRESSURE = 5;
public static final int MSG_START_AUTOSUBMIT = 6;
public static final int MSG_STOP_AUTOSUBMIT = 7;
public static final int MSG_SET_SETTINGS = 8;
public static final int MSG_GET_SETTINGS = 9;
public static final int MSG_SETTINGS = 10;
public static final int MSG_DATA_STREAM = 12;
// pressureNET Live API
public static final int MSG_GET_LOCAL_RECENTS = 14;
public static final int MSG_LOCAL_RECENTS = 15;
public static final int MSG_GET_API_RECENTS = 16;
public static final int MSG_API_RECENTS = 17;
public static final int MSG_MAKE_API_CALL = 18;
public static final int MSG_API_RESULT_COUNT = 19;
// pressureNET API Cache
public static final int MSG_CLEAR_LOCAL_CACHE = 20;
public static final int MSG_REMOVE_FROM_PRESSURENET = 21;
public static final int MSG_CLEAR_API_CACHE = 22;
// Current Conditions
public static final int MSG_ADD_CURRENT_CONDITION = 23;
public static final int MSG_GET_CURRENT_CONDITIONS = 24;
public static final int MSG_CURRENT_CONDITIONS = 25;
// Sending Data
public static final int MSG_SEND_OBSERVATION = 26;
public static final int MSG_SEND_CURRENT_CONDITION = 27;
// Current Conditions API
public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28;
// Notifications
public static final int MSG_CHANGE_NOTIFICATION = 31;
// Data management
public static final int MSG_COUNT_LOCAL_OBS = 32;
public static final int MSG_COUNT_API_CACHE = 33;
public static final int MSG_COUNT_LOCAL_OBS_TOTALS = 34;
public static final int MSG_COUNT_API_CACHE_TOTALS = 35;
// Graphing
public static final int MSG_GET_API_RECENTS_FOR_GRAPH = 36;
public static final int MSG_API_RECENTS_FOR_GRAPH = 37;
// Success / Failure notification for data submission
public static final int MSG_DATA_RESULT = 38;
long lastAPICall = System.currentTimeMillis();
long lastConditionNotification = System.currentTimeMillis() - (1000 * 60 * 60 * 6);
private CbObservation collectedObservation;
private final Handler mHandler = new Handler();
Messenger mMessenger = new Messenger(new IncomingHandler());
ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>();
private long lastPressureChangeAlert = 0;
private Messenger lastMessenger;
private boolean fromUser = false;
CbAlarm alarm = new CbAlarm();
double recentPressureReading = 0.0;
int recentPressureAccuracy = 0;
int batchReadingCount = 0;
private long lastSubmit = 0;
/**
* Collect data from onboard sensors and store locally
*
* @author jacob
*
*/
public class CbDataCollector implements SensorEventListener {
private SensorManager sm;
Sensor pressureSensor;
private final int TYPE_AMBIENT_TEMPERATURE = 13;
private final int TYPE_RELATIVE_HUMIDITY = 12;
private ArrayList<CbObservation> recentObservations = new ArrayList<CbObservation>();
public ArrayList<CbObservation> getRecentObservations() {
return recentObservations;
}
/**
* Access the database to fetch recent, locally-recorded observations
*
* @return
*/
public ArrayList<CbObservation> getRecentDatabaseObservations() {
ArrayList<CbObservation> recentDbList = new ArrayList<CbObservation>();
CbDb db = new CbDb(getApplicationContext());
db.open();
Cursor c = db.fetchAllObservations();
while (c.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(c.getDouble(1));
location.setLongitude(c.getDouble(2));
location.setAltitude(c.getDouble(3));
location.setAccuracy(c.getInt(4));
location.setProvider(c.getString(5));
obs.setLocation(location);
obs.setObservationType(c.getString(6));
obs.setObservationUnit(c.getString(7));
obs.setObservationValue(c.getDouble(8));
obs.setSharing(c.getString(9));
obs.setTime(c.getInt(10));
obs.setTimeZoneOffset(c.getInt(11));
obs.setUser_id(c.getString(12));
recentDbList.add(obs);
}
db.close();
return recentDbList;
}
public void setRecentObservations(
ArrayList<CbObservation> recentObservations) {
this.recentObservations = recentObservations;
}
/**
* Start collecting sensor data.
*
* @param m
* @return
*/
public boolean startCollectingData() {
batchReadingCount = 0;
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
pressureSensor = sm.getDefaultSensor(Sensor.TYPE_PRESSURE);
boolean collecting = false;
try {
if(sm != null) {
if (pressureSensor != null) {
log("cbservice sensor SDK " + android.os.Build.VERSION.SDK_INT + "");
if(android.os.Build.VERSION.SDK_INT == 19) {
collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI, 100000);
} else {
collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI);
}
} else {
log("cbservice pressure sensor is null");
}
} else {
log("cbservice sm is null");
}
return collecting;
} catch (Exception e) {
log("cbservice sensor error " + e.getMessage());
e.printStackTrace();
return collecting;
}
}
/**
* Stop collecting sensor data
*/
public void stopCollectingData() {
log("cbservice stop collecting data");
// sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(sm!=null) {
log("cbservice sensormanager not null, unregistering");
sm.unregisterListener(this);
sm = null;
} else {
log("cbservice sensormanager null, creating and then unregistering");
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.unregisterListener(this);
sm = null;
}
}
public CbDataCollector() {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
if (sensor.getType() == Sensor.TYPE_PRESSURE) {
recentPressureAccuracy = accuracy;
log("cbservice accuracy changed, new barometer accuracy " + recentPressureAccuracy);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
if(event.values.length > 0) {
if(event.values[0] >= 0) {
log("cbservice sensor; new pressure reading " + event.values[0]);
recentPressureReading = event.values[0];
} else {
log("cbservice sensor; pressure reading is 0 or negative" + event.values[0]);
}
} else {
log("cbservice sensor; no event values");
}
}
stopSoon();
/*
batchReadingCount++;
if(batchReadingCount>2) {
log("batch readings " + batchReadingCount + ", stopping");
//stopCollectingData();
} else {
log("batch readings " + batchReadingCount + ", not stopping");
}
*/
}
private class SensorStopper implements Runnable {
@Override
public void run() {
try {
stopCollectingData();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
private void stopSoon() {
SensorStopper stop = new SensorStopper();
mHandler.postDelayed(stop, 100);
}
}
/**
* Find all the data for an observation.
*
* Location, Measurement values, etc.
*
* @return
*/
public CbObservation collectNewObservation() {
try {
CbObservation pressureObservation = new CbObservation();
log("cb collecting new observation");
// Location values
locationManager = new CbLocationManager(getApplicationContext());
locationManager.startGettingLocations();
// Measurement values
pressureObservation = buildPressureObservation();
pressureObservation.setLocation(locationManager
.getCurrentBestLocation());
// stop listening for locations
LocationStopper stop = new LocationStopper();
mHandler.postDelayed(stop, 1000 * 3);
log("returning pressure obs: "
+ pressureObservation.getObservationValue());
return pressureObservation;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
private class LocationStopper implements Runnable {
@Override
public void run() {
try {
//System.out.println("locationmanager stop getting locations");
locationManager.stopGettingLocations();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
/**
* Send a single reading. TODO: Combine with ReadingSender for less code duplication.
* ReadingSender. Fix that.
*/
public class SingleReadingSender implements Runnable {
@Override
public void run() {
if(settingsHandler == null) {
log("single reading sender, loading settings from prefs");
loadSetttingsFromPreferences();
}
log("collecting and submitting single "
+ settingsHandler.getServerURL());
if(dataCollector!=null) {
dataCollector.stopCollectingData();
dataCollector = null;
dataCollector = new CbDataCollector();
} else {
dataCollector = new CbDataCollector();
}
dataCollector.startCollectingData();
CbObservation singleObservation = new CbObservation();
if (settingsHandler.isCollectingData()) {
// Collect
singleObservation = collectNewObservation();
if (singleObservation.getObservationValue() != 0.0) {
// Store in database
db.open();
long count = db.addObservation(singleObservation);
db.close();
try {
if (settingsHandler.isSharingData()) {
// Send if we're online
if (isNetworkAvailable()) {
log("online and sending single");
singleObservation
.setClientKey(CbConfiguration.API_KEY);
fromUser = true;
sendCbObservation(singleObservation);
fromUser = false;
// also check and send the offline buffer
if (offlineBuffer.size() > 0) {
log("sending " + offlineBuffer.size()
+ " offline buffered obs");
for (CbObservation singleOffline : offlineBuffer) {
sendCbObservation(singleObservation);
}
offlineBuffer.clear();
}
} else {
log("didn't send, not sharing data; i.e., offline");
// / offline buffer variable
// TODO: put this in the DB to survive longer
offlineBuffer.add(singleObservation);
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}
}
/**
* Put together all the information that defines
* an observation and store it in a single object.
* @return
*/
public CbObservation buildPressureObservation() {
CbObservation pressureObservation = new CbObservation();
pressureObservation.setTime(System.currentTimeMillis());
pressureObservation.setTimeZoneOffset(Calendar.getInstance()
.getTimeZone().getRawOffset());
pressureObservation.setUser_id(getID());
pressureObservation.setObservationType("pressure");
pressureObservation.setObservationValue(recentPressureReading);
pressureObservation.setObservationUnit("mbar");
// pressureObservation.setSensor(sm.getSensorList(Sensor.TYPE_PRESSURE).get(0));
pressureObservation.setSharing(settingsHandler.getShareLevel());
pressureObservation.setVersionNumber(getSDKVersion());
log("cbservice buildobs, share level "
+ settingsHandler.getShareLevel() + " " + getID());
return pressureObservation;
}
/**
* Return the version number of the SDK sending this reading
* @return
*/
public String getSDKVersion() {
String version = "-1.0";
try {
version = getPackageManager()
.getPackageInfo("ca.cumulonimbus.pressurenetsdk", 0).versionName;
} catch (NameNotFoundException nnfe) {
// TODO: this is not an okay return value
// (Don't send error messages as version numbers)
version = nnfe.getMessage();
}
return version;
}
/**
* Periodically check to see if someone has
* reported a current condition nearby. If it's
* appropriate, send a notification
*/
private void checkForLocalConditionReports() {
long now = System.currentTimeMillis();
long minWaitTime = 1000 * 60 * 60;
if(now - minWaitTime > lastConditionNotification) {
log("cbservice checking for local conditions reports");
// it has been long enough; make a conditions API call
// for the local area
CbApi conditionApi = new CbApi(getApplicationContext());
CbApiCall conditionApiCall = buildLocalConditionsApiCall();
if(conditionApiCall!=null) {
if (lastMessenger != null) {
log("cbservice making conditions api call for local reports");
conditionApi.makeAPICall(conditionApiCall, service,
lastMessenger, "Conditions");
} else {
log("cbservice not making condition call, messenger is null");
}
// TODO: store this more permanently
lastConditionNotification = now;
}
} else {
log("cbservice not checking for local conditions, too recent");
}
}
/**
* Make a CbApiCall object for local conditions
* @return
*/
public CbApiCall buildLocalConditionsApiCall() {
CbApiCall conditionApiCall = new CbApiCall();
conditionApiCall.setCallType("Conditions");
Location location = new Location("network");
location.setLatitude(0);
location.setLongitude(0);
if(locationManager != null) {
location = locationManager.getCurrentBestLocation();
conditionApiCall.setMinLat(location.getLatitude() - .1);
conditionApiCall.setMaxLat(location.getLatitude() + .1);
conditionApiCall.setMinLon(location.getLongitude() - .1);
conditionApiCall.setMaxLon(location.getLongitude() + .1);
conditionApiCall.setStartTime(System.currentTimeMillis() - (1000 * 60 * 60));
conditionApiCall.setEndTime(System.currentTimeMillis());
return conditionApiCall;
} else {
log("cbservice not checking location condition reports, no locationmanager");
return null;
}
}
/**
* Collect and send data in a different thread. This runs itself every
* "settingsHandler.getDataCollectionFrequency()" milliseconds
*/
private class ReadingSender implements Runnable {
public void run() {
long now = System.currentTimeMillis();
if(now - lastSubmit < 2000) {
log("too soon, bailing");
return;
}
// retrieve updated settings
if(settingsHandler == null) {
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler = settingsHandler.getSettings();
} else {
settingsHandler = settingsHandler.getSettings();
}
if(dataCollector!=null) {
dataCollector.stopCollectingData();
dataCollector = null;
dataCollector = new CbDataCollector();
} else {
dataCollector = new CbDataCollector();
}
dataCollector.startCollectingData();
log("collecting and submitting " + settingsHandler.getServerURL());
boolean okayToGo = true;
// Check if we're supposed to be charging and if we are.
// Bail if appropriate
if (settingsHandler.isOnlyWhenCharging()) {
if (!isCharging()) {
okayToGo = false;
}
}
if (okayToGo && settingsHandler.isCollectingData()) {
// Collect
CbObservation singleObservation = new CbObservation();
singleObservation = collectNewObservation();
if (singleObservation != null) {
if (singleObservation.getObservationValue() != 0.0) {
// Store in database
db.open();
long count = db.addObservation(singleObservation);
db.close();
try {
if (settingsHandler.isSharingData()) {
// Send if we're online
if (isNetworkAvailable()) {
lastSubmit = System.currentTimeMillis();
log("online and sending");
singleObservation
.setClientKey(CbConfiguration.API_KEY);
sendCbObservation(singleObservation);
// also check and send the offline buffer
if (offlineBuffer.size() > 0) {
log("sending " + offlineBuffer.size()
+ " offline buffered obs");
for (CbObservation singleOffline : offlineBuffer) {
sendCbObservation(singleObservation);
}
offlineBuffer.clear();
}
} else {
log("didn't send");
// / offline buffer variable
// TODO: put this in the DB to survive
// longer
offlineBuffer.add(singleObservation);
}
} else {
log("cbservice not sharing data, didn't send");
}
checkForLocalConditionReports();
// If notifications are enabled,
log("is send notif "
+ settingsHandler.isSendNotifications());
if (settingsHandler.isSendNotifications()) {
// check for pressure local trend changes and
// notify
// the client
// ensure this only happens every once in a
// while
long rightNow = System.currentTimeMillis();
long sixHours = 1000 * 60 * 60 * 6;
if (rightNow - lastPressureChangeAlert > (sixHours)) {
long timeLength = 1000 * 60 * 60 * 3;
db.open();
Cursor localCursor = db.runLocalAPICall(
-90, 90, -180, 180,
System.currentTimeMillis()
- (timeLength),
System.currentTimeMillis(), 1000);
ArrayList<CbObservation> recents = new ArrayList<CbObservation>();
while (localCursor.moveToNext()) {
// just need observation value, time,
// and
// location
CbObservation obs = new CbObservation();
obs.setObservationValue(localCursor
.getDouble(8));
obs.setTime(localCursor.getLong(10));
Location location = new Location(
"network");
location.setLatitude(localCursor
.getDouble(1));
location.setLongitude(localCursor
.getDouble(2));
obs.setLocation(location);
recents.add(obs);
}
String tendencyChange = CbScience
.changeInTrend(recents);
db.close();
log("cbservice tendency changes: "
+ tendencyChange);
if (tendencyChange.contains(",")
&& (!tendencyChange.toLowerCase()
.contains("unknown"))) {
String[] tendencies = tendencyChange
.split(",");
if (!tendencies[0]
.equals(tendencies[1])) {
log("Trend change! "
+ tendencyChange);
try {
if (lastMessenger != null) {
lastMessenger
.send(Message
.obtain(null,
MSG_CHANGE_NOTIFICATION,
tendencyChange));
} else {
log("readingsender didn't send notif, no lastMessenger");
}
} catch (Exception e) {
//e.printStackTrace();
}
lastPressureChangeAlert = rightNow;
// TODO: saveinprefs;
} else {
log("tendency equal");
}
}
} else {
// wait
log("tendency; hasn't been 6h, min wait time yet");
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
} else {
log("singleobservation is null, not sending");
}
} else {
log("cbservice is not collecting data.");
}
}
}
/**
* Check for network connection, return true
* if we're online.
*
* @return
*/
public boolean isNetworkAvailable() {
log("is net available?");
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
log("yes");
return true;
} else {
log("no");
return false;
}
}
/**
* Stop all listeners, active sensors, etc, and shut down.
*
*/
public void stopAutoSubmit() {
if (locationManager != null) {
locationManager.stopGettingLocations();
}
if (dataCollector != null) {
dataCollector.stopCollectingData();
}
log("cbservice stop autosubmit");
// alarm.cancelAlarm(getApplicationContext());
}
/**
* Send the observation to the server
*
* @param observation
* @return
*/
public boolean sendCbObservation(CbObservation observation) {
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
settingsHandler = settingsHandler.getSettings();
if(settingsHandler.getServerURL().equals("")) {
log("settings are empty; defaults");
//loadSetttingsFromPreferences();
// settingsHandler = settingsHandler.getSettings();
}
log("sendCbObservation with settings " + settingsHandler);
sender.setSettings(settingsHandler, locationManager,
lastMessenger, fromUser);
sender.execute(observation.getObservationAsParams());
return true;
} catch (Exception e) {
return false;
}
}
/**
* Send a new account to the server
*
* @param account
* @return
*/
public boolean sendCbAccount(CbAccount account) {
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
sender.setSettings(settingsHandler, locationManager,
null, true);
sender.execute(account.getAccountAsParams());
fromUser = false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Send the current condition to the server
*
* @param observation
* @return
*/
public boolean sendCbCurrentCondition(CbCurrentCondition condition) {
log("sending cbcurrent condition");
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
fromUser = true;
sender.setSettings(settingsHandler, locationManager,
lastMessenger, fromUser);
sender.execute(condition.getCurrentConditionAsParams());
fromUser = false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Start the periodic data collection.
*/
public void startSubmit() {
log("CbService: Starting to auto-collect and submit data.");
if (!alarm.isRepeating()) {
log("cbservice alarm not repeating, starting alarm");
alarm.setAlarm(getApplicationContext(),
settingsHandler.getDataCollectionFrequency());
} else {
log("cbservice startsubmit, alarm is already repeating. restarting.");
alarm.restartAlarm(getApplicationContext(),
settingsHandler.getDataCollectionFrequency());
}
}
@Override
public void onDestroy() {
log("on destroy");
stopAutoSubmit();
super.onDestroy();
}
@Override
public void onCreate() {
setUpFiles();
log("cb on create");
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.getSettings();
db = new CbDb(getApplicationContext());
super.onCreate();
}
/**
* Check charge state for preferences.
*
*/
public boolean isCharging() {
// Check battery and charging status
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = getApplicationContext().registerReceiver(null,
ifilter);
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL;
return isCharging;
}
/**
* Start running background data collection methods.
*
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
log("cb onstartcommand");
dataCollector = new CbDataCollector();
if (intent != null) {
if (intent.getAction() != null) {
if (intent.getAction().equals(ACTION_SEND_MEASUREMENT)) {
// send just a single measurement
log("sending single observation, request from intent");
sendSingleObs();
return START_NOT_STICKY;
}
} else if (intent.getBooleanExtra("alarm", false)) {
// This runs when the service is started from the alarm.
// Submit a data point
log("cbservice alarm firing, sending data");
if(settingsHandler == null) {
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.getSettings();
} else {
settingsHandler.getSettings();
}
if(settingsHandler.isSharingData()) {
dataCollector.startCollectingData();
startWithIntent(intent, true);
} else {
log("cbservice not sharing data");
}
LocationStopper stop = new LocationStopper();
mHandler.postDelayed(stop, 1000 * 3);
return START_NOT_STICKY;
} else {
// Check the database
log("starting service with db");
startWithDatabase();
return START_NOT_STICKY;
}
}
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
/**
* Convert time ago text to ms. TODO: not this. values in xml.
*
* @param timeAgo
* @return
*/
public static long stringTimeToLongHack(String timeAgo) {
if (timeAgo.equals("1 minute")) {
return 1000 * 60;
} else if (timeAgo.equals("5 minutes")) {
return 1000 * 60 * 5;
} else if (timeAgo.equals("10 minutes")) {
return 1000 * 60 * 10;
} else if (timeAgo.equals("30 minutes")) {
return 1000 * 60 * 30;
} else if (timeAgo.equals("1 hour")) {
return 1000 * 60 * 60;
} else if(timeAgo.equals("6 hours")) {
return 1000 * 60 * 60 * 6;
} else if(timeAgo.equals("12 hours")) {
return 1000 * 60 * 60 * 12;
}
return 1000 * 60 * 10;
}
public void loadSetttingsFromPreferences() {
log("loading settings from prefs");
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.setServerURL(serverURL);
settingsHandler.setAppID(getApplication().getPackageName());
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String preferenceCollectionFrequency = sharedPreferences.getString(
"autofrequency", "10 minutes");
boolean preferenceShareData = sharedPreferences.getBoolean(
"autoupdate", true);
String preferenceShareLevel = sharedPreferences.getString(
"sharing_preference", "Us, Researchers and Forecasters");
boolean preferenceSendNotifications = sharedPreferences.getBoolean(
"send_notifications", false);
settingsHandler
.setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency));
settingsHandler.setSendNotifications(preferenceSendNotifications);
boolean useGPS = sharedPreferences.getBoolean("use_gps", true);
boolean onlyWhenCharging = sharedPreferences.getBoolean(
"only_when_charging", false);
settingsHandler.setUseGPS(useGPS);
settingsHandler.setOnlyWhenCharging(onlyWhenCharging);
settingsHandler.setSharingData(preferenceShareData);
settingsHandler.setShareLevel(preferenceShareLevel);
// Seems like new settings. Try adding to the db.
settingsHandler.saveSettings();
}
public void startWithIntent(Intent intent, boolean fromAlarm) {
try {
if (!fromAlarm) {
// We arrived here from the user (i.e., not the alarm)
// start/(update?) the alarm
startSubmit();
} else {
// alarm. Go!
ReadingSender reading = new ReadingSender();
mHandler.post(reading);
}
} catch (Exception e) {
for (StackTraceElement ste : e.getStackTrace()) {
log(ste.getMethodName() + ste.getLineNumber());
}
}
}
public void startWithDatabase() {
try {
db.open();
// Check the database for Settings initialization
settingsHandler = new CbSettingsHandler(getApplicationContext());
Cursor allSettings = db.fetchSettingByApp(getPackageName());
log("cb intent null; checking db, size " + allSettings.getCount());
if (allSettings.moveToFirst()) {
settingsHandler.setAppID(allSettings.getString(1));
settingsHandler.setDataCollectionFrequency(allSettings
.getLong(2));
settingsHandler.setServerURL(serverURL);
int sendNotifications = allSettings.getInt(4);
int useGPS = allSettings.getInt(5);
int onlyWhenCharging = allSettings.getInt(6);
int sharingData = allSettings.getInt(7);
settingsHandler.setShareLevel(allSettings.getString(9));
boolean boolCharging = (onlyWhenCharging > 0);
boolean boolGPS = (useGPS > 0);
boolean boolSendNotifications = (sendNotifications > 0);
boolean boolSharingData = (sharingData > 0);
log("only when charging processed " + boolCharging + " gps "
+ boolGPS);
settingsHandler.setSendNotifications(boolSendNotifications);
settingsHandler.setOnlyWhenCharging(boolCharging);
settingsHandler.setUseGPS(boolGPS);
settingsHandler.setSharingData(boolSharingData);
settingsHandler.saveSettings();
}
log("cbservice startwithdb, " + settingsHandler);
ReadingSender reading = new ReadingSender();
mHandler.post(reading);
startSubmit();
db.close();
} catch (Exception e) {
for (StackTraceElement ste : e.getStackTrace()) {
log(ste.getMethodName() + ste.getLineNumber());
}
}
}
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_STOP:
log("message. bound service says stop");
try {
alarm.cancelAlarm(getApplicationContext());
} catch(Exception e) {
}
break;
case MSG_GET_BEST_LOCATION:
log("message. bound service requesting location");
if (locationManager != null) {
Location best = locationManager.getCurrentBestLocation();
try {
log("service sending best location");
msg.replyTo.send(Message.obtain(null,
MSG_BEST_LOCATION, best));
} catch (RemoteException re) {
re.printStackTrace();
}
} else {
log("error: location null, not returning");
}
break;
case MSG_GET_BEST_PRESSURE:
log("message. bound service requesting pressure. not responding");
break;
case MSG_START_AUTOSUBMIT:
// log("start autosubmit");
// startWithDatabase();
break;
case MSG_STOP_AUTOSUBMIT:
log("stop autosubmit");
stopAutoSubmit();
break;
case MSG_GET_SETTINGS:
log("get settings");
if(settingsHandler != null) {
settingsHandler.getSettings();
} else {
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.getSettings();
}
try {
msg.replyTo.send(Message.obtain(null, MSG_SETTINGS,
settingsHandler));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_DATA_STREAM:
break;
case MSG_SET_SETTINGS:
log("set settings");
settingsHandler = (CbSettingsHandler) msg.obj;
settingsHandler.saveSettings();
break;
case MSG_GET_LOCAL_RECENTS:
log("get local recents");
recentMsg = msg;
CbApiCall apiCall = (CbApiCall) msg.obj;
if (apiCall == null) {
// log("apicall null, bailing");
break;
}
// run API call
db.open();
Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(),
apiCall.getMaxLat(), apiCall.getMinLon(),
apiCall.getMaxLon(), apiCall.getStartTime(),
apiCall.getEndTime(), 2000);
ArrayList<CbObservation> results = new ArrayList<CbObservation>();
while (cursor.moveToNext()) {
// TODO: This is duplicated in CbDataCollector. Fix that
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
location.setAltitude(cursor.getDouble(3));
location.setAccuracy(cursor.getInt(4));
location.setProvider(cursor.getString(5));
obs.setLocation(location);
obs.setObservationType(cursor.getString(6));
obs.setObservationUnit(cursor.getString(7));
obs.setObservationValue(cursor.getDouble(8));
obs.setSharing(cursor.getString(9));
obs.setTime(cursor.getLong(10));
obs.setTimeZoneOffset(cursor.getInt(11));
obs.setUser_id(cursor.getString(12));
obs.setTrend(cursor.getString(18));
results.add(obs);
}
db.close();
log("cbservice: " + results.size() + " local api results");
try {
msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS,
results));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_GET_API_RECENTS:
CbApiCall apiCacheCall = (CbApiCall) msg.obj;
log("get api recents " + apiCacheCall.toString());
// run API call
try {
db.open();
Cursor cacheCursor = db.runAPICacheCall(
apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(),
apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(),
apiCacheCall.getStartTime(),
apiCacheCall.getEndTime(), apiCacheCall.getLimit());
ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>();
while (cacheCursor.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cacheCursor.getDouble(1));
location.setLongitude(cacheCursor.getDouble(2));
obs.setLocation(location);
obs.setObservationValue(cacheCursor.getDouble(3));
obs.setTime(cacheCursor.getLong(4));
cacheResults.add(obs);
}
db.close();
try {
msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS,
cacheResults));
} catch (RemoteException re) {
// re.printStackTrace();
}
} catch (Exception e) {
}
break;
case MSG_GET_API_RECENTS_FOR_GRAPH:
// TODO: Put this in a method. It's a copy+paste from
// GET_API_RECENTS
CbApiCall apiCacheCallGraph = (CbApiCall) msg.obj;
log("get api recents " + apiCacheCallGraph.toString());
// run API call
db.open();
Cursor cacheCursorGraph = db.runAPICacheCall(
apiCacheCallGraph.getMinLat(),
apiCacheCallGraph.getMaxLat(),
apiCacheCallGraph.getMinLon(),
apiCacheCallGraph.getMaxLon(),
apiCacheCallGraph.getStartTime(),
apiCacheCallGraph.getEndTime(),
apiCacheCallGraph.getLimit());
ArrayList<CbObservation> cacheResultsGraph = new ArrayList<CbObservation>();
while (cacheCursorGraph.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cacheCursorGraph.getDouble(1));
location.setLongitude(cacheCursorGraph.getDouble(2));
obs.setLocation(location);
obs.setObservationValue(cacheCursorGraph.getDouble(3));
obs.setTime(cacheCursorGraph.getLong(4));
cacheResultsGraph.add(obs);
}
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_API_RECENTS_FOR_GRAPH, cacheResultsGraph));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_MAKE_API_CALL:
CbApi api = new CbApi(getApplicationContext());
CbApiCall liveApiCall = (CbApiCall) msg.obj;
liveApiCall.setCallType("Readings");
long timeDiff = System.currentTimeMillis() - lastAPICall;
deleteOldData();
lastAPICall = api.makeAPICall(liveApiCall, service,
msg.replyTo, "Readings");
break;
case MSG_MAKE_CURRENT_CONDITIONS_API_CALL:
CbApi conditionApi = new CbApi(getApplicationContext());
CbApiCall conditionApiCall = (CbApiCall) msg.obj;
conditionApiCall.setCallType("Conditions");
conditionApi.makeAPICall(conditionApiCall, service,
msg.replyTo, "Conditions");
break;
case MSG_CLEAR_LOCAL_CACHE:
db.open();
db.clearLocalCache();
long count = db.getUserDataCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_LOCAL_OBS_TOTALS, (int) count, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_REMOVE_FROM_PRESSURENET:
// TODO: Implement a secure system to remove user data
break;
case MSG_CLEAR_API_CACHE:
db.open();
db.clearAPICache();
long countCache = db.getDataCacheCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_API_CACHE_TOTALS, (int) countCache, 0));
} catch (RemoteException re) {
//re.printStackTrace();
}
break;
case MSG_ADD_CURRENT_CONDITION:
CbCurrentCondition cc = (CbCurrentCondition) msg.obj;
try {
db.open();
db.addCondition(cc);
db.close();
} catch(SQLiteDatabaseLockedException dble) {
}
break;
case MSG_GET_CURRENT_CONDITIONS:
recentMsg = msg;
db.open();
CbApiCall currentConditionAPI = (CbApiCall) msg.obj;
ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>();
try {
Cursor ccCursor = db.getCurrentConditions(
currentConditionAPI.getMinLat(),
currentConditionAPI.getMaxLat(),
currentConditionAPI.getMinLon(),
currentConditionAPI.getMaxLon(),
currentConditionAPI.getStartTime(),
currentConditionAPI.getEndTime(), 1000);
while (ccCursor.moveToNext()) {
CbCurrentCondition cur = new CbCurrentCondition();
Location location = new Location("network");
location.setLatitude(ccCursor.getDouble(1));
location.setLongitude(ccCursor.getDouble(2));
location.setAltitude(ccCursor.getDouble(3));
location.setAccuracy(ccCursor.getInt(4));
location.setProvider(ccCursor.getString(5));
cur.setLocation(location);
cur.setTime(ccCursor.getLong(6));
cur.setTime(ccCursor.getLong(7));
cur.setUser_id(ccCursor.getString(9));
cur.setGeneral_condition(ccCursor.getString(10));
cur.setWindy(ccCursor.getString(11));
cur.setFog_thickness(ccCursor.getString(12));
cur.setCloud_type(ccCursor.getString(13));
cur.setPrecipitation_type(ccCursor.getString(14));
cur.setPrecipitation_amount(ccCursor.getDouble(15));
cur.setPrecipitation_unit(ccCursor.getString(16));
cur.setThunderstorm_intensity(ccCursor.getString(17));
cur.setUser_comment(ccCursor.getString(18));
conditions.add(cur);
}
} catch (Exception e) {
log("cbservice get_current_conditions failed " + e.getMessage());
} finally {
db.close();
}
try {
msg.replyTo.send(Message.obtain(null,
MSG_CURRENT_CONDITIONS, conditions));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_SEND_CURRENT_CONDITION:
CbCurrentCondition condition = (CbCurrentCondition) msg.obj;
if (settingsHandler == null) {
settingsHandler = new CbSettingsHandler(
getApplicationContext());
settingsHandler.setServerURL(serverURL);
settingsHandler
.setAppID(getApplication().getPackageName());
}
try {
condition
.setSharing_policy(settingsHandler.getShareLevel());
sendCbCurrentCondition(condition);
} catch (Exception e) {
//e.printStackTrace();
}
break;
case MSG_SEND_OBSERVATION:
log("sending single observation, request from app");
sendSingleObs();
break;
case MSG_COUNT_LOCAL_OBS:
db.open();
long countLocalObsOnly = db.getUserDataCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_LOCAL_OBS_TOTALS,
(int) countLocalObsOnly, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_COUNT_API_CACHE:
db.open();
long countCacheOnly = db.getDataCacheCount();
db.close();
try {
msg.replyTo.send(Message
.obtain(null, MSG_COUNT_API_CACHE_TOTALS,
(int) countCacheOnly, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_CHANGE_NOTIFICATION:
if (msg.replyTo != null) {
lastMessenger = msg.replyTo;
} else {
}
break;
default:
super.handleMessage(msg);
}
}
}
public void sendSingleObs() {
if (settingsHandler != null) {
if (settingsHandler.getServerURL() == null) {
settingsHandler.getSettings();
}
}
SingleReadingSender singleSender = new SingleReadingSender();
mHandler.post(singleSender);
}
/**
* Remove older data from cache to keep the size reasonable
*
* @return
*/
public void deleteOldData() {
log("deleting old data");
db.open();
db.deleteOldCacheData();
db.close();
}
public boolean notifyAPIResult(Messenger reply, int count) {
try {
if (reply == null) {
log("cannot notify, reply is null");
} else {
reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0));
}
} catch (RemoteException re) {
re.printStackTrace();
} catch (NullPointerException npe) {
//npe.printStackTrace();
}
return false;
}
public CbObservation recentPressureFromDatabase() {
CbObservation obs = new CbObservation();
double pressure = 0.0;
try {
long rowId = db.fetchObservationMaxID();
Cursor c = db.fetchObservation(rowId);
while (c.moveToNext()) {
pressure = c.getDouble(8);
}
log(pressure + " pressure from db");
if (pressure == 0.0) {
log("returning null");
return null;
}
obs.setObservationValue(pressure);
return obs;
} catch (Exception e) {
obs.setObservationValue(pressure);
return obs;
}
}
/**
* Get a hash'd device ID
*
* @return
*/
public String getID() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
String actual_id = Secure.getString(getApplicationContext()
.getContentResolver(), Secure.ANDROID_ID);
byte[] bytes = actual_id.getBytes();
byte[] digest = md.digest(bytes);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
hexString.append(Integer.toHexString(0xFF & digest[i]));
}
return hexString.toString();
} catch (Exception e) {
return "
}
}
// Used to write a log to SD card. Not used unless logging enabled.
public void setUpFiles() {
try {
File homeDirectory = getExternalFilesDir(null);
if (homeDirectory != null) {
mAppDir = homeDirectory.getAbsolutePath();
}
} catch (Exception e) {
//e.printStackTrace();
}
}
// Log data to SD card for debug purposes.
// To enable logging, ensure the Manifest allows writing to SD card.
public void logToFile(String text) {
try {
OutputStream output = new FileOutputStream(mAppDir + "/log.txt",
true);
String logString = (new Date()).toString() + ": " + text + "\n";
output.write(logString.getBytes());
output.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException ioe) {
//ioe.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
log("on bind");
return mMessenger.getBinder();
}
@Override
public void onRebind(Intent intent) {
log("on rebind");
super.onRebind(intent);
}
public void log(String message) {
if(CbConfiguration.DEBUG_MODE) {
logToFile(message);
System.out.println(message);
}
}
public CbDataCollector getDataCollector() {
return dataCollector;
}
public void setDataCollector(CbDataCollector dataCollector) {
this.dataCollector = dataCollector;
}
public CbLocationManager getLocationManager() {
return locationManager;
}
public void setLocationManager(CbLocationManager locationManager) {
this.locationManager = locationManager;
}
}
|
package biz.netcentric.cq.tools.actool.installhook;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.jcr.Session;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import biz.netcentric.cq.tools.actool.aceservice.AceService;
import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableCreatorException;
import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableInstallationHistory;
import biz.netcentric.cq.tools.actool.installationhistory.AcInstallationHistoryPojo;
import com.day.jcr.vault.fs.io.Archive;
import com.day.jcr.vault.fs.io.Archive.Entry;
import com.day.jcr.vault.packaging.InstallContext;
import com.day.jcr.vault.packaging.PackageException;
public class AcToolInstallHook extends OsgiAwareInstallHook {
private static final Logger LOG = LoggerFactory.getLogger(AcToolInstallHook.class);
@Override
public void execute(InstallContext context) throws PackageException {
LOG.debug("Executing install hook for phase {}.", context.getPhase());
switch (context.getPhase()) {
case PREPARE:
// check if AcTool is installed
log("Installing ACLs through AcToolInstallHook...", context.getOptions());
ServiceReference aceServiceReference = getServiceReference("biz.netcentric.cq.tools.actool.aceservice.AceService");
if (aceServiceReference == null) {
throw new PackageException(
"Could not get AceService from OSGI service registry. Make sure the ACTool is installed!");
}
AceService aceService = (biz.netcentric.cq.tools.actool.aceservice.AceService) getBundleContext()
.getService(aceServiceReference);
if (aceService == null) {
throw new PackageException(
"Could not instanciate AceService. Make sure the ACTool is installed and check the log for errors");
}
try {
installConfigs(context.getPackage().getArchive(), context.getSession(), aceService);
log("Installed ACLs through AcToolInstallHook!", context.getOptions());
} catch (Exception e) {
log("Exception while installing configurations: " + e, context.getOptions());
throw new PackageException(e.getMessage(), e);
} finally {
getBundleContext().ungetService(aceServiceReference);
}
break;
default:
// nothing to do in all other phases
break;
}
}
private void installConfigs(Archive archive, Session session, AceService aceService) throws Exception {
AcInstallationHistoryPojo history = new AcInstallationHistoryPojo();
Set<AuthorizableInstallationHistory> authorizableInstallationHistorySet = new LinkedHashSet<AuthorizableInstallationHistory>();
try {
Map<String, String> configs = getConfigurations(archive, archive.getJcrRoot(), session);
aceService.installNewConfigurations(session, history, configs, authorizableInstallationHistorySet);
} catch (Exception e) {
history.setException(e.toString());
throw e;
} finally {
// TODO: acHistoryService.persistHistory(history, this.configurationPath);
}
}
private Map<String, String> getConfigurations(Archive archive, Entry parent, Session session) throws IOException {
Map<String, String> configs = new HashMap<String, String>();
// Read the configuration files from the archive
for (Entry entry : parent.getChildren()) {
if (entry.isDirectory()) {
configs.putAll(getConfigurations(archive, entry, session));
} else {
if (entry.getName().endsWith(".yaml")) {
LOG.info("Reading YAML file {}", entry.getName());
BufferedReader reader = new BufferedReader(new InputStreamReader(archive.getInputSource(entry).getByteStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
reader.close();
// We cannot use the entry's name, since it might not be unique, and we don't have its full path
// so we add its has code as a key for the map of configs.
configs.put(parent.getName() + "/" + entry.getName() + " (" + entry.hashCode() + ")", sb.toString());
}
}
}
return configs;
}
}
|
package com.noveogroup.android.task.ui;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
public class NewUIHandler {
private static class AssociationSet<V> {
private final Map<V, Set<String>> values = new HashMap<V, Set<String>>();
public void clear() {
values.clear();
}
public void add(V value, Collection<String> tags) {
values.put(value, new HashSet<String>(tags));
}
public void remove(V value) {
values.remove(value);
}
public Set<V> getAssociated(Collection<String> tags) {
Set<V> set = new HashSet<V>();
for (Map.Entry<V, Set<String>> entry : values.entrySet()) {
if (entry.getValue().containsAll(tags)) {
set.add(entry.getKey());
}
}
return Collections.unmodifiableSet(set);
}
}
private static class WaitCallback implements Runnable {
private final Object lock = new Object();
private boolean finished = false;
protected void runCallback() {
}
@Override
public final void run() {
try {
runCallback();
} finally {
release();
}
}
public final void join() throws InterruptedException {
synchronized (lock) {
while (!finished) {
lock.wait();
}
}
}
public final void release() {
synchronized (lock) {
finished = true;
lock.notifyAll();
}
}
}
private final Object lock;
private final Handler handler;
private final AssociationSet<WaitCallback> associationSet;
private final Map<Runnable, Set<WaitCallback>> callbacks;
private final NewUIHandler root;
private final Set<String> tags;
private final WeakHashMap<Set<String>, NewUIHandler> subCache;
public NewUIHandler() {
this(new Handler());
}
public NewUIHandler(Looper looper) {
this(new Handler(looper));
}
public NewUIHandler(Context context) {
this(new Handler(context.getMainLooper()));
}
public NewUIHandler(Handler handler) {
this.lock = new Object();
this.handler = handler;
this.associationSet = new AssociationSet<WaitCallback>();
this.callbacks = new HashMap<Runnable, Set<WaitCallback>>();
this.root = this;
this.tags = Collections.emptySet();
this.subCache = new WeakHashMap<Set<String>, NewUIHandler>();
}
private NewUIHandler(NewUIHandler root, Set<String> tags) {
this.lock = root.lock;
this.handler = root.handler;
this.associationSet = root.associationSet;
this.callbacks = root.callbacks;
this.tags = tags;
this.root = root;
this.subCache = root.subCache;
}
public NewUIHandler sub(String... tags) {
return sub(Arrays.asList(tags));
}
public NewUIHandler sub(Collection<String> tags) {
Set<String> tagSet = Collections.unmodifiableSet(new HashSet<String>(tags));
synchronized (lock) {
NewUIHandler uiHandler = subCache.get(tagSet);
if (uiHandler == null) {
uiHandler = new NewUIHandler(this, tagSet);
subCache.put(tagSet, uiHandler);
}
return uiHandler;
}
}
public Set<String> tags() {
return tags;
}
private void checkJoinAbility() {
if (Thread.currentThread() == handler.getLooper().getThread()) {
throw new RuntimeException("current thread is a looper thread and cannot wait itself");
}
}
private WaitCallback createWaitCallback(final Runnable callback) {
return new WaitCallback() {
@Override
protected void runCallback() {
try {
callback.run();
} finally {
removeWaitCallback(callback, this);
}
}
};
}
private void addWaitCallback(Runnable callback, WaitCallback waitCallback) {
synchronized (lock) {
associationSet.add(waitCallback, tags);
Set<WaitCallback> waitCallbacks = callbacks.get(callback);
if (waitCallbacks == null) {
waitCallbacks = new HashSet<WaitCallback>();
}
waitCallbacks.add(waitCallback);
}
}
private void removeWaitCallback(Runnable callback, WaitCallback waitCallback) {
synchronized (lock) {
associationSet.remove(waitCallback);
Set<WaitCallback> waitCallbacks = callbacks.get(callback);
if (waitCallbacks != null) {
waitCallbacks.remove(waitCallback);
if (waitCallbacks.isEmpty()) {
callbacks.remove(callback);
}
}
}
}
private WaitCallback postCallback(Runnable callback) {
WaitCallback waitCallback = createWaitCallback(callback);
synchronized (lock) {
if (handler.post(waitCallback)) {
addWaitCallback(callback, waitCallback);
return waitCallback;
} else {
throw new RuntimeException("cannot post callback to the handler");
}
}
}
private WaitCallback postCallback(long delay, Runnable callback) {
WaitCallback waitCallback = createWaitCallback(callback);
synchronized (lock) {
if (handler.postDelayed(waitCallback, delay)) {
addWaitCallback(callback, waitCallback);
return waitCallback;
} else {
throw new RuntimeException("cannot post callback to the handler");
}
}
}
public void post(Runnable callback) {
postCallback(callback);
}
public void post(long delay, Runnable callback) {
postCallback(delay, callback);
}
public void single(Runnable callback) {
synchronized (lock) {
remove(callback);
post(callback);
}
}
public void single(long delay, Runnable callback) {
synchronized (lock) {
remove(callback);
post(delay, callback);
}
}
public void sync(Runnable callback) throws InterruptedException {
checkJoinAbility();
postCallback(callback).join();
}
public void sync(long delay, Runnable callback) throws InterruptedException {
checkJoinAbility();
postCallback(delay, callback).join();
}
private Set<WaitCallback> getWaitCallbacks(Runnable callback) {
synchronized (lock) {
Set<WaitCallback> waitCallbacks = callbacks.get(callback);
if (waitCallbacks == null) {
return Collections.emptySet();
} else {
return new HashSet<WaitCallback>(waitCallbacks);
}
}
}
private Set<WaitCallback> getWaitCallbacks() {
synchronized (lock) {
Set<WaitCallback> waitCallbacks = new HashSet<WaitCallback>();
for (Runnable callback : callbacks.keySet()) {
waitCallbacks.addAll(getWaitCallbacks(callback));
}
return waitCallbacks;
}
}
public void join(Runnable callback) throws InterruptedException {
checkJoinAbility();
for (WaitCallback waitCallback : getWaitCallbacks(callback)) {
waitCallback.join();
}
}
public void join() throws InterruptedException {
checkJoinAbility();
for (WaitCallback waitCallback : getWaitCallbacks()) {
waitCallback.join();
}
}
public void remove(Runnable callback) {
synchronized (lock) {
Set<WaitCallback> waitCallbacks = callbacks.remove(callback);
if (waitCallbacks != null) {
for (WaitCallback waitCallback : waitCallbacks) {
associationSet.remove(waitCallback);
}
}
}
}
public void remove() {
synchronized (lock) {
associationSet.clear();
callbacks.clear();
}
}
}
|
package com.gmail.stefvanschiedev.buildinggame.utils.scoreboards;
import com.gmail.stefvanschiedev.buildinggame.managers.files.SettingsManager;
import com.gmail.stefvanschiedev.buildinggame.managers.messages.MessageManager;
import com.gmail.stefvanschiedev.buildinggame.managers.softdependencies.SDVault;
import com.gmail.stefvanschiedev.buildinggame.utils.Conditional;
import com.gmail.stefvanschiedev.buildinggame.utils.arena.Arena;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.*;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import java.time.LocalDateTime;
import java.time.format.TextStyle;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
/**
* The base class for all scoreboards that belong to an arena
*
* @since 5.1.0
*/
public abstract class ArenaScoreboard {
/**
* The scoreboard this class is a wrapper for
*/
final Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
/**
* The objective used for this scoreboard
*/
final Objective objective = scoreboard.registerNewObjective("bg-build", "dummy", getHeader());
/**
* A list of the text to display on the scoreboard after the basic placeholders have been parsed and a conditional
* to determine if the line should be displayed altogether. The conditional may be null if there is no conditional
* assigned to this line.
*/
private final List<Map.Entry<String, Conditional>> strings = new ArrayList<>();
/**
* A list of teams that's used to hold the text
*/
private final List<Team> teams = new ArrayList<>();
/**
* The red and green team
*/
private final Team redTeam, greenTeam;
/**
* A map of replacements for placeholders
*/
private final Map<String, Function<Player, String>> replacements = new HashMap<>();
/**
* The arena this scoreboard belongs to
*/
private final Arena arena;
/**
* Constructs a new arena scoreboard
*
* @param arena the arena this scoreboard belongs to
*/
ArenaScoreboard(Arena arena) {
this.arena = arena;
objective.setDisplaySlot(DisplaySlot.SIDEBAR);
redTeam = scoreboard.registerNewTeam("bg-red");
greenTeam = scoreboard.registerNewTeam("bg-green");
redTeam.setPrefix(ChatColor.RED.toString());
greenTeam.setPrefix(ChatColor.GREEN.toString());
List<String> strings = getLines();
for (int i = 0; i < strings.size(); i++) {
var team = scoreboard.registerNewTeam(i + "");
team.addEntry(ChatColor.values()[i].toString());
team.setDisplayName("");
teams.add(team);
//parse conditional
var text = MessageManager.translate(strings.get(i));
Conditional conditional = null;
if (!text.isEmpty() && text.charAt(0) == '$') {
var conditionalText = text.split(" ")[0];
conditional = Conditional.parse(conditionalText);
//add one because of the extra space after the conditional
text = text.substring(conditionalText.length() + 1);
}
this.strings.add(new AbstractMap.SimpleEntry<>(text, conditional));
}
//initialize replacements
replacements.put("arena", player -> arena.getName());
replacements.put("players", player -> String.valueOf(arena.getPlayers()));
replacements.put("max_players", player -> String.valueOf(arena.getMaxPlayers()));
replacements.put("subject", player -> arena.getSubject());
replacements.put("seconds", player -> {
var timer = arena.getActiveTimer();
return timer == null ? "0" : String.valueOf(timer.getSeconds());
});
replacements.put("minutes", player -> {
var timer = arena.getActiveTimer();
return timer == null ? "0" : String.valueOf(timer.getMinutes());
});
replacements.put("plot", player -> String.valueOf(arena.getPlot(player).getId()));
replacements.put("time", player -> {
var timer = arena.getActiveTimer();
return timer == null ? "0" : timer.getMinutes() + ":" + timer.getSecondsFromMinute();
});
replacements.put("seconds_from_minute", player -> {
var timer = arena.getActiveTimer();
return timer == null ? "0" : String.valueOf(timer.getSecondsFromMinute());
});
replacements.put("blocks_placed", player -> String.valueOf(arena.getPlot(player).getGamePlayer(player)
.getBlocksPlaced()));
replacements.put("money", player ->
SDVault.getInstance().isEnabled() ? String.valueOf(SDVault.getEconomy().getBalance(player)) : "0");
replacements.put("vote", player -> {
var plot = arena.getVotingPlot();
return plot == null ? "0" : plot.getVote(player) == null ? "0" : plot.getVote(player) + "";
});
replacements.put("playerplot", player -> {
var votingPlot = arena.getVotingPlot();
var plot = arena.getPlot(player);
return votingPlot == null ? plot == null ? "?" : plot.getPlayerFormat() : votingPlot.getPlayerFormat();
});
replacements.put("date_day_of_month", player -> String.valueOf(LocalDateTime.now().getDayOfMonth()));
replacements.put("date_day_of_week", player -> String.valueOf(LocalDateTime.now().getDayOfWeek()));
replacements.put("date_day_of_year", player -> String.valueOf(LocalDateTime.now().getDayOfYear()));
replacements.put("date_hour", player -> String.valueOf(LocalDateTime.now().getHour()));
replacements.put("date_minute", player -> String.valueOf(LocalDateTime.now().getMinute()));
replacements.put("date_month", player -> LocalDateTime.now().getMonth().getDisplayName(TextStyle.FULL,
Locale.getDefault()));
replacements.put("date_month_numeric", player -> String.valueOf(LocalDateTime.now().getMonthValue()));
replacements.put("date_second", player -> String.valueOf(LocalDateTime.now().getSecond()));
replacements.put("date_year", player -> String.valueOf(LocalDateTime.now().getYear()));
replacements.put("vote_name", player -> {
YamlConfiguration messages = SettingsManager.getInstance().getMessages();
var votingPlot = arena.getVotingPlot();
if (votingPlot == null)
return "?";
var vote = votingPlot.getVote(player);
if (vote == null)
return "?";
switch (vote.getPoints()) {
case 2:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.second-slot-block"));
case 3:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.third-slot-block"));
case 4:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.fourth-slot-block"));
case 5:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.fifth-slot-block"));
case 6:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.sixth-slot-block"));
case 7:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.seventh-slot-block"));
case 8:
return ChatColor.translateAlternateColorCodes('&', messages
.getString("voting.eighth-slot-block"));
default:
return "?";
}
});
replacements.put("first_players", player -> {
var firstPlot = arena.getFirstPlot();
return firstPlot == null ? "?" : firstPlot.getPlayerFormat();
});
replacements.put("second_players", player -> {
var secondPlot = arena.getSecondPlot();
return secondPlot == null ? "?" : secondPlot.getPlayerFormat();
});
replacements.put("third_players", player -> {
var thirdPlot = arena.getThirdPlot();
return thirdPlot == null ? "?" : thirdPlot.getPlayerFormat();
});
}
/**
* Updates/Shows the scoreboard for the specified player
*
* @param player the player to update the scoreboard for
* @since 5.3.0
*/
@Contract("null -> fail")
public void show(Player player) {
//keep track of the line count cause lines may not be displayed at all
var lineCount = 0;
for (var i = 0; i < strings.size(); i++) {
Map.Entry<String, Conditional> line = strings.get(i);
var conditional = line.getValue();
if (conditional != null && !conditional.evaluate(arena))
continue;
var text = replace(line.getKey(), player);
var length = text.length();
var team = teams.get(lineCount);
team.setPrefix(text.substring(0, Math.min(length, 16)));
if (length > 16)
team.setSuffix(ChatColor.getLastColors(team.getPrefix()) + text.substring(16, Math.min(length, 32)));
objective.getScore(ChatColor.values()[lineCount].toString()).setScore(strings.size() - lineCount);
lineCount++;
}
player.setScoreboard(scoreboard);
}
/**
* Replaces all values in the input with the corresponding values from the {@link ArenaScoreboard#replacements}
*
* @param input the input string
* @param player the player
* @return the new string
* @since 5.3.0
*/
@NotNull
@Contract(value = "null, _ -> fail", pure = true)
private String replace(String input, Player player) {
var matcher = Pattern.compile("%([^%]+)%").matcher(input);
while (matcher.find()) {
Function<Player, String> replacement = replacements.get(matcher.group(1));
if (replacement == null) {
continue;
}
input = matcher.replaceFirst(replacement.apply(player));
matcher.reset(input);
}
return input;
}
/**
* Gets the green team
*
* @return the green team
* @since 5.9.0
*/
@NotNull
@Contract(pure = true)
public Team getGreenTeam() {
return greenTeam;
}
/**
* Gets the red team
*
* @return the red team
* @since 5.9.0
*/
@NotNull
@Contract(pure = true)
public Team getRedTeam() {
return redTeam;
}
/**
* Returns the header of this scoreboard
*
* @return the header
* @since 5.1.0
*/
@Nls
@NotNull
@Contract(pure = true)
protected abstract String getHeader();
/**
* Returns a list of all displayed lines
*
* @return a list of lines
* @since 5.1.0
*/
@NotNull
@Contract(pure = true)
protected abstract List<String> getLines();
}
|
package co.epitre.aelf_lectures;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import co.epitre.aelf_lectures.data.LectureItem;
import co.epitre.aelf_lectures.data.LecturesController;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
class WhatWhen {
public LecturesController.WHAT what;
public GregorianCalendar when;
public int position;
}
public class LecturesActivity extends SherlockFragmentActivity implements DatePickerFragment.CalendarDialogListener,
ActionBar.OnNavigationListener {
public static final String PREFS_NAME = "aelf-prefs";
public static final long DATE_TODAY = 0;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
LecturesController lecturesCtrl = null;
SectionsPagerAdapterFragment mSectionsPagerAdapter;
WhatWhen whatwhen;
Menu mMenu;
List<LectureItem> networkError = new ArrayList<LectureItem>(1);
/**
* Sync account related vars
*/
// The authority for the sync adapter's content provider
public static final String AUTHORITY = "co.epitre.aelf"; // DANGER: must be the same as the provider's in the manifest
// An account type, in the form of a domain name
public static final String ACCOUNT_TYPE = "epitre.co";
// The account name
public static final String ACCOUNT = "www.aelf.org";
// Sync interval in s. ~ 1 Day
public static final long SYNC_INTERVAL = 60L*60L*22L;
// Instance fields
Account mAccount;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
// TODO: detect first launch + trigger initial sync
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int currentVersion, savedVersion;
// current version
PackageInfo packageInfo;
try {
packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
throw new RuntimeException("Could not determine current version");
}
currentVersion = packageInfo.versionCode;
// load saved version, if any
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
savedVersion = settings.getInt("version", -1);
// upgrade logic, primitive at the moment...
if(savedVersion != currentVersion) {
if(savedVersion < 5) {
// delete cache DB: needs to force regenerate
getApplicationContext().deleteDatabase("aelf_cache.db");
}
// update saved version
SharedPreferences.Editor editor = settings.edit();
editor.putInt("version", currentVersion);
editor.commit();
}
// create dummy account for our background sync engine
mAccount = CreateSyncAccount(this);
// init the lecture controller
lecturesCtrl = LecturesController.getInstance(this);
// load the "lectures" for today
whatwhen = new WhatWhen();
whatwhen.when = new GregorianCalendar();
whatwhen.what = LecturesController.WHAT.MESSE;
whatwhen.position = -1; // for mass, load gospel first
// error handler
networkError.add(new LectureItem("Erreur Réseau", "<p>Connexion au serveur AELF impossible<br />Veuillez ré-essayer plus tard.</p>", "erreur", -1));
// some UI. Most UI init are done in the prev async task
setContentView(R.layout.activity_lectures);
// Spinner
ActionBar actionBar = getSupportActionBar();
Context context = actionBar.getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.spinner, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(list, this);
// finally, turn on periodic lectures caching
if(mAccount != null) {
ContentResolver.setIsSyncable(mAccount, AUTHORITY, 1);
ContentResolver.setSyncAutomatically(mAccount, AUTHORITY, true);
ContentResolver.addPeriodicSync(mAccount, AUTHORITY, new Bundle(1), SYNC_INTERVAL);
}
}
private boolean isToday(GregorianCalendar when){
GregorianCalendar today = new GregorianCalendar();
return (when.get(GregorianCalendar.ERA) == today.get(GregorianCalendar.ERA) &&
when.get(GregorianCalendar.YEAR) == today.get(GregorianCalendar.YEAR) &&
when.get(GregorianCalendar.DAY_OF_YEAR) == today.get(GregorianCalendar.DAY_OF_YEAR));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save instance state. Especially useful on screen rotate on older phones
// - what --> mass, tierce, ... ? (id)
// - when --> date (timestamp)
// - position --> active tab (id)
super.onSaveInstanceState(outState);
outState.putInt("what", whatwhen.what.getPosition());
outState.putInt("position", mViewPager.getCurrentItem());
if(isToday(whatwhen.when)) {
outState.putLong("when", DATE_TODAY);
} else {
outState.putLong("when", whatwhen.when.getTimeInMillis());
}
}
@Override
protected void onRestoreInstanceState (Bundle savedInstanceState) {
// Restore saved instance state. Especially useful on screen rotate on older phones
// - what --> mass, tierce, ... ? (id)
// - when --> date (timestamp)
// - position --> active tab (id)
super.onRestoreInstanceState(savedInstanceState);
// load state
whatwhen.what = LecturesController.WHAT.values()[savedInstanceState.getInt("what")];
whatwhen.position = savedInstanceState.getInt("position");
long timestamp = savedInstanceState.getLong("when");
if(timestamp == DATE_TODAY) {
whatwhen.when = new GregorianCalendar();
} else {
whatwhen.when.setTimeInMillis(timestamp);
}
// update UI
ActionBar actionBar = getSupportActionBar();
actionBar.setSelectedNavigationItem(whatwhen.what.getPosition());
// nota: date UI is updated on menu creation
// nota: data reload + move to position is triggered by spinner callback
// FIXME: factorize date UI
// TODO: tab
}
public boolean onAbout(MenuItem item) {
AboutDialogFragment aboutDialog = new AboutDialogFragment();
aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
return true;
}
public boolean onSyncPref(MenuItem item) {
Intent intent = new Intent(this, SyncPrefActivity.class);
startActivity(intent);
return true;
}
public boolean onSyncDo(MenuItem item) {
// Pass the settings flags by inserting them in a bundle
Bundle settingsBundle = new Bundle();
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
// start sync
ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle);
// done
return true;
}
public boolean onCalendar(MenuItem item) {
Bundle args = new Bundle();
args.putLong("time", whatwhen.when.getTimeInMillis());
DatePickerFragment calendarDialog = new DatePickerFragment();
calendarDialog.setArguments(args);
calendarDialog.show(getSupportFragmentManager(), "datePicker");
return true;
}
@SuppressLint("SimpleDateFormat") // I know but currently French only
public void onCalendarDialogPicked(int year, int month, int day) {
whatwhen.when = new GregorianCalendar(year, month, day);
whatwhen.position = mViewPager.getCurrentItem(); // keep on the same reading on date change
new DownloadXmlTask().execute(whatwhen);
// Update to date button with "this.date"
MenuItem calendarItem = mMenu.findItem(R.id.action_calendar);
SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst
calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime()));
}
@Override
public boolean onNavigationItemSelected(int position, long itemId) {
// Are we actually *changing* ? --> maybe not if coming from state reload
if(whatwhen.what != LecturesController.WHAT.values()[position]) {
whatwhen.what = LecturesController.WHAT.values()[position];
whatwhen.position = 0; // on what change, move to 1st
}
new DownloadXmlTask().execute(whatwhen);
return true;
}
@SuppressLint("SimpleDateFormat") // I know but currently French only
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar
getSupportMenuInflater().inflate(R.menu.lectures, menu);
// Update to date button with "this.date"
MenuItem calendarItem = menu.findItem(R.id.action_calendar);
SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst
calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime()));
mMenu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
return onAbout(item);
case R.id.action_sync_settings:
return onSyncPref(item);
case R.id.action_sync_do:
return onSyncDo(item);
case R.id.action_calendar:
return onCalendar(item);
}
return true;
}
/**
* Create a new dummy account for the sync adapter
*
* @param context The application context
*/
public static Account CreateSyncAccount(Context context) {
// Create the account type and default account
Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
// Get an instance of the Android account manager
AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
/*
* Add the account and account type, no password or user data
* If successful, return the Account object, otherwise report an error.
*/
if (accountManager.addAccountExplicitly(newAccount, null, null)) {
return newAccount;
} else {
return accountManager.getAccountsByType(ACCOUNT_TYPE)[0];
}
}
protected void setLoading(final boolean loading) {
final RelativeLayout loadingOverlay = (RelativeLayout)findViewById(R.id.loadingOverlay);
loadingOverlay.post(new Runnable() {
public void run() {
if(loading) {
loadingOverlay.setVisibility(View.VISIBLE);
} else {
loadingOverlay.setVisibility(View.INVISIBLE);
}
}
});
}
// Async loader
private class DownloadXmlTask extends AsyncTask<WhatWhen, Void, List<LectureItem>> {
@Override
protected List<LectureItem> doInBackground(WhatWhen... whatwhen) {
WhatWhen ww = whatwhen[0];
try {
// attempt to load from cache: skip loading indicator (avoids flickering)
List<LectureItem> lectures = lecturesCtrl.getLectures(ww.what, ww.when, true);
if(lectures != null) return lectures;
// attempts to load from network, with loading indicator
setLoading(true);
return lecturesCtrl.getLectures(ww.what, ww.when, false);
} catch (IOException e) {
// TODO print error message
setLoading(false);
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(List<LectureItem> lectures) {
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
if(lectures == null) {
lectures = networkError;
}
mSectionsPagerAdapter = new SectionsPagerAdapterFragment(getSupportFragmentManager(), lectures);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
int start = (whatwhen.position < 0)?lectures.size():0;
mViewPager.setCurrentItem(start + whatwhen.position);
setLoading(false);
}
}
}
|
package com.andyiac.button.selecter;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends Activity {
private FlowLayout flowLayout;
private String[] mVals = new String[]
{"Hello", "Android", "Weclome Hi ", "Button", "TextView", "Hello",
"Android", "Weclome", "Button ImageView", "TextView", "Helloworld",
"Android", "Weclome Hello", "Button Text", "TextView"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
flowLayout = (FlowLayout) findViewById(R.id.flow_layout);
initData();
}
private ArrayList<String> lables = new ArrayList<String>();
public void initData() {
LayoutInflater mInflater = LayoutInflater.from(this);
// todo SelectView list
for (int i = 0; i < mVals.length; i++) {
final SelectView sv = (SelectView) mInflater.inflate(R.layout.select_view_item, flowLayout, false);
sv.setText(mVals[i]);
flowLayout.addView(sv);
sv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
lables = sv.mToggle(lables);
Log.e("TAG", "=====lables====>" + lables);
}
});
}
}
}
|
package com.buddycloud.http;
import java.security.KeyStore;
import javax.net.ssl.HostnameVerifier;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import com.buddycloud.model.ModelCallback;
import com.buddycloud.preferences.Preferences;
public class BuddycloudHTTPHelper {
private static final String TAG = "BuddycloudHTTPHelper";
private static final HttpClient CLIENT = createHttpClient();
public static void getObject(String url, Context parent,
final ModelCallback<JSONObject> callback) {
getObject(url, true, true, parent, callback);
}
public static void getArray(String url, Context parent,
final ModelCallback<JSONArray> callback) {
getArray(url, true, true, parent, callback);
}
public static void post(String url, HttpEntity entity, Context parent,
final ModelCallback<JSONObject> callback) {
post(url, true, true, entity, parent, callback);
}
public static void getObject(String url, boolean auth, boolean acceptsJSON, Context parent,
final ModelCallback<JSONObject> callback) {
reqObject("get", url, auth, acceptsJSON, null, parent, callback);
}
public static void getArray(String url, boolean auth, boolean acceptsJSON, Context parent,
final ModelCallback<JSONArray> callback) {
reqArray("get", url, auth, acceptsJSON, null, parent, callback);
}
public static void post(String url, boolean auth, boolean acceptsJSON, HttpEntity entity, Context parent,
final ModelCallback<JSONObject> callback) {
reqObject("post", url, auth, acceptsJSON, entity, parent, callback);
}
private static void reqObject(String method, String url, boolean auth, boolean acceptsJSON,
HttpEntity entity, Context parent, ModelCallback<JSONObject> callback) {
new RequestAsyncTask<JSONObject>(method, url, entity, auth, acceptsJSON, parent, callback) {
@Override
protected JSONObject toJSON(String responseStr) throws JSONException {
if (responseStr == null || responseStr.length() == 0 || responseStr.equals("OK")) {
return new JSONObject();
}
return new JSONObject(responseStr);
}
}.execute();
}
private static void reqArray(String method, String url, boolean auth, boolean acceptsJSON,
HttpEntity entity, Context parent, ModelCallback<JSONArray> callback) {
new RequestAsyncTask<JSONArray>(method, url, entity, auth, acceptsJSON, parent, callback) {
@Override
protected JSONArray toJSON(String responseStr) throws JSONException {
return new JSONArray(responseStr);
}
}.execute();
}
protected static void addAcceptJSONHeader(HttpRequestBase method) {
method.setHeader("Accept", "application/json");
}
protected static void addAuthHeader(HttpRequestBase method, Context parent) {
String loginPref = Preferences.getPreference(parent, Preferences.MY_CHANNEL_JID);
String passPref = Preferences.getPreference(parent, Preferences.PASSWORD);
String auth = loginPref.split("@")[0] + ":" + passPref;
String authToken = Base64.encodeToString(auth.getBytes(), Base64.NO_WRAP);
method.setHeader("Authorization", "Basic " + authToken);
}
public static HttpClient createHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = new TrustAllSSLSocketFactory(trustStore);
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", socketFactory, 443));
ClientConnectionManager ccm = new SingleClientConnManager(
new DefaultHttpClient().getParams(), registry);
DefaultHttpClient client = new DefaultHttpClient(ccm, null);
client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
return client;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static abstract class RequestAsyncTask<T extends Object> extends AsyncTask<Void, Void, Object> {
private String methodType;
private String url;
private HttpEntity entity;
private boolean auth;
private boolean acceptsJSON;
private Context parent;
private ModelCallback<T> callback;
public RequestAsyncTask(String methodType, String url, HttpEntity entity,
boolean auth, boolean acceptsJSON, Context parent,
ModelCallback<T> callback) {
this.methodType = methodType;
this.url = url;
this.entity = entity;
this.auth = auth;
this.acceptsJSON = acceptsJSON;
this.parent = parent;
this.callback = callback;
}
@Override
protected Object doInBackground(Void... params) {
try {
long t = System.currentTimeMillis();
HttpRequestBase method = null;
if (methodType.equals("get")) {
method = new HttpGet(url);
method.setHeader("Accept", "application/json");
} else if (methodType.equals("post")) {
method = new HttpPost(url);
if (entity != null) {
((HttpPost)method).setEntity(entity);
}
}
if (acceptsJSON) {
addAcceptJSONHeader(method);
}
if (auth) {
addAuthHeader(method, parent);
}
HttpResponse response = CLIENT.execute(method);
if (response.getStatusLine().getStatusCode() >= 400) {
// Make sure entity is consumed (released) so connection can be re-used
// this avoids the SingleClientConnManager warning about invalid status connection not released
response.getEntity().consumeContent();
throw new Exception(response.getStatusLine().toString());
}
HttpEntity resEntityGet = ((HttpResponse)response).getEntity();
if (resEntityGet == null) {
return "";
}
String responseStr = EntityUtils.toString(resEntityGet);
Log.d(TAG, "HTTP: {M: " + methodType + ", U: " + url + ", T: " + (System.currentTimeMillis() - t) + "}");
return responseStr;
} catch (Throwable e) {
Log.e(TAG, e.getLocalizedMessage(), e);
return e;
}
}
@Override
protected void onPostExecute(Object response) {
if (response instanceof Throwable) {
callback.error((Throwable) response);
} else {
try {
T jsonResponse = (T) toJSON(response.toString());
callback.success(jsonResponse);
} catch (Throwable e) {
callback.error(e);
}
}
}
protected abstract T toJSON(String responseStr) throws JSONException;
}
}
|
package com.delormeloic.generator.view;
import java.lang.reflect.InvocationTargetException;
import com.delormeloic.generator.model.slides.Slide;
import com.delormeloic.generator.model.slides.SlideWithImage;
import com.delormeloic.generator.model.slides.SlideWithImageWithSpeech;
import com.delormeloic.generator.model.slides.SlideWithMovie;
import com.delormeloic.generator.model.slides.SlideWithMovieWithSpeech;
import com.delormeloic.generator.model.slides.SlideWithTitle;
import com.delormeloic.generator.model.slides.SlideWithTitleWithSpeechWithImage;
import com.delormeloic.generator.model.slides.SlideWithTitleWithSpeechWithMovie;
import com.delormeloic.generator.view.slidesforms.SlideForm;
import com.delormeloic.generator.view.slidesforms.SlideWithImageForm;
import com.delormeloic.generator.view.slidesforms.SlideWithImageWithSpeechForm;
import com.delormeloic.generator.view.slidesforms.SlideWithMovieForm;
import com.delormeloic.generator.view.slidesforms.SlideWithMovieWithSpeechForm;
import com.delormeloic.generator.view.slidesforms.SlideWithTitleForm;
import com.delormeloic.generator.view.slidesforms.SlideWithTitleWithSpeechWithImageForm;
import com.delormeloic.generator.view.slidesforms.SlideWithTitleWithSpeechWithMovieForm;
import com.delormeloic.utils.logger.Logger;
public enum SlideType
{
/**
* A slide with a title.
*/
SLIDE_WITH_TITLE("/com/delormeloic/generator/view/resources/images/slide_with_title.png", SlideWithTitle.class, SlideWithTitleForm.class),
/**
* A slide with a title with a speech with an image.
*/
SLIDE_WITH_TITLE_WITH_SPEECH_WITH_IMAGE("/com/delormeloic/generator/view/resources/images/slide_with_title_with_speech_with_image.png", SlideWithTitleWithSpeechWithImage.class, SlideWithTitleWithSpeechWithImageForm.class),
/**
* A slide with a title with a speech with a movie.
*/
SLIDE_WITH_TITLE_WITH_SPEECH_WITH_MOVIE("/com/delormeloic/generator/view/resources/images/slide_with_title_with_speech_with_movie.png", SlideWithTitleWithSpeechWithMovie.class, SlideWithTitleWithSpeechWithMovieForm.class),
/**
* A slide with an image with a speech.
*/
SLIDE_WITH_IMAGE_WITH_SPEECH("/com/delormeloic/generator/view/resources/images/slide_with_image_with_speech.png", SlideWithImageWithSpeech.class, SlideWithImageWithSpeechForm.class),
/**
* A slide with a movie with a speech.
*/
SLIDE_WITH_MOVIE_WITH_SPEECH("/com/delormeloic/generator/view/resources/images/slide_with_movie_with_speech.png", SlideWithMovieWithSpeech.class, SlideWithMovieWithSpeechForm.class),
/**
* A slide with an image.
*/
SLIDE_WITH_IMAGE("/com/delormeloic/generator/view/resources/images/slide_with_image.png", SlideWithImage.class, SlideWithImageForm.class),
/**
* A slide with a movie.
*/
SLIDE_WITH_MOVIE("/com/delormeloic/generator/view/resources/images/slide_with_movie.png", SlideWithMovie.class, SlideWithMovieForm.class);
/**
* The image path.
*/
private final String imagePath;
/**
* The slide class.
*/
private final Class<? extends Slide> slideClass;
/**
* The slide form class.
*/
private final Class<? extends SlideForm> slideFormClass;
/**
* Private constructor.
*
* @param imagePath
* The image path.
* @param slideClass
* The slide class.
* @param slideFormClass
* The slide form class.
*/
private SlideType(String imagePath, Class<? extends Slide> slideClass, Class<? extends SlideForm> slideFormClass)
{
this.imagePath = imagePath;
this.slideClass = slideClass;
this.slideFormClass = slideFormClass;
}
/**
* Get the image path.
*
* @return The image path.
*/
public String getImagePath()
{
return this.imagePath;
}
/**
* Get a slide form instance.
*
* @return The slide form instance.
*/
public SlideForm getSlideFormInstance()
{
try
{
return this.slideFormClass.getConstructor(this.slideClass).newInstance(this.slideClass.getConstructor(String.class).newInstance(this.slideClass.getSimpleName()));
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e)
{
Logger.severe(e);
return null;
}
}
}
|
package net.bytebuddy.agent.builder;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ByteArrayClassLoader;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.loading.PackageDefinitionStrategy;
import net.bytebuddy.dynamic.scaffold.TypeValidation;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.test.packaging.SimpleOptionalType;
import net.bytebuddy.test.packaging.SimpleType;
import net.bytebuddy.test.utility.AgentAttachmentRule;
import net.bytebuddy.test.utility.ClassFileExtraction;
import net.bytebuddy.test.utility.IntegrationRule;
import net.bytebuddy.test.utility.JavaVersionRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static net.bytebuddy.dynamic.loading.ClassInjector.DEFAULT_PROTECTION_DOMAIN;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.none;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Parameterized.class)
public class AgentBuilderDefaultApplicationRedefineTest {
private static final String FOO = "foo", BAR = "bar";
@Parameterized.Parameters
public static Collection<Object[]> data() {
List<Object[]> list = new ArrayList<Object[]>();
for (AgentBuilder.DescriptionStrategy descriptionStrategy : AgentBuilder.DescriptionStrategy.Default.values()) {
list.add(new Object[]{descriptionStrategy});
}
return list;
}
private final AgentBuilder.DescriptionStrategy descriptionStrategy;
public AgentBuilderDefaultApplicationRedefineTest(AgentBuilder.DescriptionStrategy descriptionStrategy) {
this.descriptionStrategy = descriptionStrategy;
}
@Rule
public MethodRule agentAttachmentRule = new AgentAttachmentRule();
@Rule
public MethodRule javaVersionRule = new JavaVersionRule();
@Rule
public MethodRule integrationRule = new IntegrationRule();
private ClassLoader simpleTypeLoader, optionalTypeLoader;
@Before
public void setUp() throws Exception {
simpleTypeLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
ClassFileExtraction.of(SimpleType.class),
DEFAULT_PROTECTION_DOMAIN,
ByteArrayClassLoader.PersistenceHandler.MANIFEST,
PackageDefinitionStrategy.NoOp.INSTANCE);
optionalTypeLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER,
ClassFileExtraction.of(SimpleOptionalType.class),
DEFAULT_PROTECTION_DOMAIN,
ByteArrayClassLoader.PersistenceHandler.MANIFEST,
PackageDefinitionStrategy.NoOp.INSTANCE);
}
@Test
@AgentAttachmentRule.Enforce(redefinesClasses = true)
@IntegrationRule.Enforce
public void testRedefinition() throws Exception {
// A redefinition reflects on loaded types which are eagerly validated types (Java 7- for redefinition).
// This causes type equality for outer/inner classes to fail which is why an external class is used.
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
assertThat(simpleTypeLoader.loadClass(SimpleType.class.getName()).getName(), is(SimpleType.class.getName())); // ensure that class is loaded
ClassFileTransformer classFileTransformer = new AgentBuilder.Default()
.ignore(none())
.disableClassFormatChanges()
.with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
.with(descriptionStrategy)
.type(ElementMatchers.is(SimpleType.class), ElementMatchers.is(simpleTypeLoader)).transform(new FooTransformer())
.installOnByteBuddyAgent();
try {
Class<?> type = simpleTypeLoader.loadClass(SimpleType.class.getName());
assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) BAR));
} finally {
ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
}
}
@Test
@AgentAttachmentRule.Enforce(redefinesClasses = true)
@IntegrationRule.Enforce
public void testRedefinitionOptionalType() throws Exception {
// A redefinition reflects on loaded types which are eagerly validated types (Java 7- for redefinition).
// This causes type equality for outer/inner classes to fail which is why an external class is used.
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
assertThat(optionalTypeLoader.loadClass(SimpleOptionalType.class.getName()).getName(), is(SimpleOptionalType.class.getName())); // ensure that class is loaded
ClassFileTransformer classFileTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED))
.ignore(none())
.disableClassFormatChanges()
.with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
.with(descriptionStrategy)
.type(ElementMatchers.is(SimpleOptionalType.class), ElementMatchers.is(optionalTypeLoader)).transform(new FooTransformer())
.installOnByteBuddyAgent();
try {
Class<?> type = optionalTypeLoader.loadClass(SimpleOptionalType.class.getName());
// The hybrid strategy cannot transform optional types.
assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) BAR));
} finally {
ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
}
}
@Test
@AgentAttachmentRule.Enforce(retransformsClasses = true)
@IntegrationRule.Enforce
public void testRetransformation() throws Exception {
// A redefinition reflects on loaded types which are eagerly validated types (Java 7- for redefinition).
// This causes type equality for outer/inner classes to fail which is why an external class is used.
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
assertThat(simpleTypeLoader.loadClass(SimpleType.class.getName()).getName(), is(SimpleType.class.getName())); // ensure that class is loaded
ClassFileTransformer classFileTransformer = new AgentBuilder.Default()
.ignore(none())
.disableClassFormatChanges()
.with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
.with(descriptionStrategy)
.type(ElementMatchers.is(SimpleType.class), ElementMatchers.is(simpleTypeLoader)).transform(new FooTransformer())
.installOnByteBuddyAgent();
try {
Class<?> type = simpleTypeLoader.loadClass(SimpleType.class.getName());
assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) BAR));
} finally {
ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
}
}
@Test
@AgentAttachmentRule.Enforce(retransformsClasses = true)
@IntegrationRule.Enforce
public void testRetransformationOptionalType() throws Exception {
// A redefinition reflects on loaded types which are eagerly validated types (Java 7- for redefinition).
// This causes type equality for outer/inner classes to fail which is why an external class is used.
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
assertThat(optionalTypeLoader.loadClass(SimpleOptionalType.class.getName()).getName(), is(SimpleOptionalType.class.getName())); // ensure that class is loaded
ClassFileTransformer classFileTransformer = new AgentBuilder.Default(new ByteBuddy().with(TypeValidation.DISABLED))
.ignore(none())
.disableClassFormatChanges()
.with(AgentBuilder.RedefinitionStrategy.REDEFINITION)
.with(descriptionStrategy)
.type(ElementMatchers.is(SimpleOptionalType.class), ElementMatchers.is(optionalTypeLoader)).transform(new FooTransformer())
.installOnByteBuddyAgent();
try {
Class<?> type = optionalTypeLoader.loadClass(SimpleOptionalType.class.getName());
// The hybrid strategy cannot transform optional types.
assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) BAR));
} finally {
ByteBuddyAgent.getInstrumentation().removeTransformer(classFileTransformer);
}
}
private static class FooTransformer implements AgentBuilder.Transformer {
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader) {
return builder.method(named(FOO)).intercept(FixedValue.value(BAR));
}
}
}
|
package com.droidtools.rubiksolver;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MoveNavigator extends SurfaceView implements
SurfaceHolder.Callback {
SurfaceHolder mSurfaceHolder;
int mCanvasWidth;
int mCanvasHeight;
int mPosition;
boolean mRunning;
List<RubikMove> mSol;
Map<String, Bitmap> icons;
Thread drawThread;
public MoveNavigator(Context context, AttributeSet attrs) {
super(context, attrs);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
setFocusable(true); // make sure we get key events
//setWillNotDraw(false);
}
public void init(List<RubikMove> sol, int pos) {
mSol = sol;
mPosition = pos;
icons = new HashMap<String, Bitmap>();
for (Map.Entry<String, Integer> entry : RubikMove.icons.entrySet()) {
Bitmap icon = BitmapFactory.decodeResource(getResources(),
entry.getValue());
icons.put(entry.getKey(), icon);
}
drawThread = new Thread(new Runnable() {
@Override
public void run() {
while (mRunning) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
if (c != null) {
doDraw(c);
}
}
} finally {
// do this in a finally so that if an exception is
// thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}, "Cube Drawer");
}
public void setRunning(boolean running) {
mRunning = running;
}
public void setPosition(int pos) {
mPosition = pos;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
synchronized (mSurfaceHolder) {
Log.d("SURFACE_CHANGE",
String.format("Width - %d Height - %d", width, height));
mCanvasWidth = width;
mCanvasHeight = height;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!isInEditMode()) {
setRunning(true);
drawThread.start();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
setRunning(false);
retry = true;
while (retry) {
try {
drawThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
Log.d("SURFACE", "draw thread dead");
}
public void doDraw(Canvas canvas) {
final int sectionSize = 50;
// Use a local copy of the position here because it could change
// at any time during the draw call. We just want to be consistent.
int position = mPosition;
int num = mCanvasWidth / sectionSize;
if (num % 2 == 0)
num
int s = (position - num/2);
int e = (position + num/2)+1;
int leftBuffer = (mCanvasWidth - num * sectionSize) / 2;
int x;
Paint clearPaint = new Paint();
//blackPaint.setStyle(Style.FILL);
clearPaint.setColor(Color.BLACK);
Paint backPaint = new Paint();
//paint.setStyle(Style.FILL);
backPaint.setARGB(255, 255, 80, 80);
for (int i=s; i<e; i++) {
x = leftBuffer + sectionSize*(i-s);
Log.d("MOVENAV X:", ""+x+","+s+","+e+","+num+","+mCanvasWidth);
if (i < 0 || i >= mSol.size()) {
canvas.drawRect(new RectF(x,0,x+sectionSize,sectionSize), clearPaint);
continue;
}
if (i == position) {
canvas.drawRect(new RectF(x,0,x+sectionSize,sectionSize), backPaint);
}
// TODO(bbrown): This offset probably can be precalculated.
Bitmap bitmap = icons.get(mSol.get(i).getMoveRep());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int leftOffset = (sectionSize - width) / 2;
int topOffset = (sectionSize - height) / 2;
canvas.drawBitmap(bitmap, x + leftOffset, topOffset, null);
}
}
}
|
package edu.kit.iks.Cryptographics.DiffieHellman.Demonstration;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import edu.kit.iks.CryptographicsLib.VisualizationView;
public class AliceChooseSecretView extends VisualizationView {
private JLabel aliceExplain;
private ColorChannel cc;
private ColorMix cm;
private static final long serialVersionUID = 87178534093974249L;
public AliceChooseSecretView() {
super();
GridBagConstraints gbc = new GridBagConstraints();
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
layout.setConstraints(this.getNextButton(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
layout.setConstraints(this.getBackButton(), gbc);
this.aliceExplain = new JLabel();
this.aliceExplain.setText("<html><div style=\"width:120px\">Alice chooses a public color and sends it to Bob" +
"Eve listens to the channel and gets a copy</div></html>");
gbc.weightx = 0.1;
gbc.weighty = 0.1;
gbc.gridx = 1;
gbc.gridy = 2;
this.add(aliceExplain, gbc);
this.cc = new ColorChannel(new Dimension(700, 200), 50);
gbc.weightx = 0.1;
gbc.weighty = 0.1;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
this.add(this.cc, gbc);
this.cc.choosePublicColor(Color.BLUE);
this.cm = new ColorMix(50, new Dimension(200, 200));
gbc.weightx = 0.1;
gbc.weighty = 0.1;
gbc.gridx = 2;
gbc.gridy = 0;
this.add(this.cm, gbc);
this.cc.loadView();
this.cc.setRepeat(false);
this.cc.setKeepColor(true);
this.validate();
this.cc.sendPublicColor(new NextStepCallback() {
@Override
public void callback() {
for(ActionListener al : getNextButton().getActionListeners()) {
getNextButton().removeActionListener(al);
}
getNextButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cc.chooseAlicePrivateColor(Color.GREEN);
cc.mixAlicePrivatePublic();
cm.setEllipColor(0, cc.getPublicColor());
cm.setEllipColor(1, cc.getAlicePrivateColor());
cm.mixColors(true, false, new NextStepCallback() {
@Override
public void callback() {
for(ActionListener al : getNextButton().getActionListeners()) {
getNextButton().removeActionListener(al);
}
getNextButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cc.sendAliceMixedColorToBob(new NextStepCallback() {
@Override
public void callback() {
for(ActionListener al : getNextButton().getActionListeners()) {
getNextButton().removeActionListener(al);
}
getNextButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cc.chooseBobPrivateColor(Color.RED);
cm.setEllipColor(1, cc.getBobPrivateColor());
cm.mixColors(true, false, new NextStepCallback() {
@Override
public void callback() {
cc.setColorNextToSend(cm.getMixedColor());
cc.sendBobMixedColorToAlice(new NextStepCallback() {
@Override
public void callback() {
cc.mixAliceFinalSecret(new NextStepCallback() {
@Override
public void callback() {
cc.mixBobFinalSecret(null);
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
public ColorChannel getColorChannel() {
return this.cc;
}
}
|
package es.deusto.weblab.client.lab.experiments.plugins.es.deusto.weblab.labview.ui;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.comm.exceptions.WlCommException;
import es.deusto.weblab.client.configuration.IConfigurationRetriever;
import es.deusto.weblab.client.dto.experiments.ResponseCommand;
import es.deusto.weblab.client.lab.comm.callbacks.IResponseCommandCallback;
import es.deusto.weblab.client.lab.ui.BoardBase;
import es.deusto.weblab.client.ui.widgets.WlTimer;
public class LabVIEWBoard extends BoardBase {
@SuppressWarnings("unused")
private IConfigurationRetriever configurationRetriever;
private VerticalPanel panel = new VerticalPanel();
private HTML html = new HTML();
private Button openPopupButton = new Button("Click here to open the experiment");
private WlTimer timer = new WlTimer(false);
public LabVIEWBoard(IConfigurationRetriever configurationRetriever, IBoardBaseController boardController) {
super(boardController);
this.configurationRetriever = configurationRetriever;
this.timer.setStyleName("wl-time_remaining");
this.openPopupButton.setVisible(false);
}
@Override
public void setTime(int time) {
this.timer.updateTime(time);
}
final IResponseCommandCallback callback = new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
e.printStackTrace();
LabVIEWBoard.this.html.setText("Error checking the state of the experiment: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
if(responseCommand.getCommandString().equals("yes")) {
displayExperiment();
} else {
final Timer timer = new Timer() {
@Override
public void run() {
LabVIEWBoard.this.boardController.sendCommand("is_open", LabVIEWBoard.this.callback);
}
};
timer.schedule(500);
}
}
};
@Override
public void start() {
this.panel.add(this.timer);
this.timer.start();
this.timer.setTimerFinishedCallback(new WlTimer.IWlTimerFinishedCallback() {
@Override
public void onFinished() {
LabVIEWBoard.this.boardController.onClean();
}
});
this.panel.add(this.html);
this.html.setText("Waiting for experiment...");
this.boardController.sendCommand("is_open", this.callback);
}
private void displayExperiment() {
this.boardController.sendCommand("get_url", new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
e.printStackTrace();
LabVIEWBoard.this.html.setText("Error getting url to show LabVIEW panel: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
LabVIEWBoard.this.html.setText("");
LabVIEWBoard.this.openPopupButton.setVisible(true);
LabVIEWBoard.this.openPopupButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.open("/weblab/web/upload/?session_id=" + LabVIEWBoard.this.boardController.getSessionId().getRealId(), "_blank", null);
}
});
/*
final String [] commands = responseCommand.getCommandString().split(";");
if(commands.length < 5){
LabVIEWBoard.this.html.setHTML("Invalid response: not enough arguments: " + responseCommand.getCommandString());
return;
}
final int height = Integer.parseInt(commands[0]);
final int width = Integer.parseInt(commands[1]);
final String viName = commands[2];
final String server = commands[3];
final String version = commands[4];
final String htmlCode = LabViewObjectGenerator.generate(height, width, viName, server, version);
LabVIEWBoard.this.html.setHTML(htmlCode);
*/
}
});
}
@Override
public void end() {
if(this.timer != null)
this.timer.dispose();
if(this.html != null)
this.html.setHTML("");
}
@Override
public Widget getWidget() {
return this.panel;
}
}
|
package es.deusto.weblab.client.lab.experiments.plugins.es.deusto.weblab.labview.ui;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import es.deusto.weblab.client.comm.exceptions.WlCommException;
import es.deusto.weblab.client.configuration.IConfigurationRetriever;
import es.deusto.weblab.client.dto.experiments.ResponseCommand;
import es.deusto.weblab.client.lab.comm.UploadStructure;
import es.deusto.weblab.client.lab.comm.callbacks.IResponseCommandCallback;
import es.deusto.weblab.client.lab.ui.BoardBase;
import es.deusto.weblab.client.ui.widgets.WlTimer;
public class LabVIEWBoard extends BoardBase {
private IConfigurationRetriever configurationRetriever;
private VerticalPanel panel = new VerticalPanel();
private HTML html = new HTML();
private Button openPopupButton = new Button("Click here to open the experiment");
private WlTimer timer = new WlTimer(false);
private final boolean sendFile;
private HorizontalPanel uploadStructurePanel = new HorizontalPanel();
private UploadStructure uploadStructure;
public LabVIEWBoard(IConfigurationRetriever configurationRetriever, IBoardBaseController boardController) {
super(boardController);
this.configurationRetriever = configurationRetriever;
this.timer.setStyleName("wl-time_remaining");
this.openPopupButton.setVisible(false);
this.sendFile = this.configurationRetriever.getBoolProperty("send.file", false);
this.uploadStructure = new UploadStructure();
this.uploadStructure.setFileInfo("program");
}
@Override
public void setTime(int time) {
this.timer.updateTime(time);
}
private final IResponseCommandCallback isOpenCallback = new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
e.printStackTrace();
LabVIEWBoard.this.html.setText("Error checking the state of the experiment: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
if(responseCommand.getCommandString().equals("yes")) {
displayExperiment();
} else {
final Timer timer = new Timer() {
@Override
public void run() {
LabVIEWBoard.this.boardController.sendCommand("is_open", LabVIEWBoard.this.isOpenCallback);
}
};
timer.schedule(500);
}
}
};
private final IResponseCommandCallback readyToProgramFileCallback = new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
LabVIEWBoard.this.html.setText("Error checking if it's ready to program a file: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
if(responseCommand.getCommandString().equals("yes")){
LabVIEWBoard.this.uploadStructure.getFormPanel().setVisible(false);
LabVIEWBoard.this.boardController.sendFile(LabVIEWBoard.this.uploadStructure, LabVIEWBoard.this.sendFileCallback);
}else if(responseCommand.getCommandString().equals("no")){
LabVIEWBoard.this.boardController.sendCommand("is_ready_to_program", LabVIEWBoard.this.readyToProgramFileCallback);
}else{
LabVIEWBoard.this.html.setText("Error checking if it's ready to program a file: got " + responseCommand.getCommandString());
}
}
};
private final IResponseCommandCallback sendFileCallback = new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
e.printStackTrace();
LabVIEWBoard.this.html.setText("Error sending file: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
LabVIEWBoard.this.boardController.sendCommand("is_open", LabVIEWBoard.this.isOpenCallback);
}
};
@Override
public void initialize() {
this.panel.add(this.uploadStructurePanel);
this.uploadStructurePanel.add(new Label("Select the bit file"));
this.uploadStructurePanel.add(this.uploadStructure.getFormPanel());
}
@Override
public void start() {
this.panel.add(this.timer);
this.timer.start();
this.timer.setTimerFinishedCallback(new WlTimer.IWlTimerFinishedCallback() {
@Override
public void onFinished() {
LabVIEWBoard.this.boardController.onClean();
}
});
this.panel.add(this.html);
this.panel.add(this.openPopupButton);
this.html.setText("Waiting for experiment...");
if(this.sendFile){
this.boardController.sendCommand("is_ready_to_program", this.readyToProgramFileCallback);
}else{
this.boardController.sendCommand("is_open", this.isOpenCallback);
}
}
private void displayExperiment() {
this.boardController.sendCommand("get_url", new IResponseCommandCallback() {
@Override
public void onFailure(WlCommException e) {
e.printStackTrace();
LabVIEWBoard.this.html.setText("Error getting url to show LabVIEW panel: " + e.getMessage());
}
@Override
public void onSuccess(ResponseCommand responseCommand) {
LabVIEWBoard.this.html.setText("");
LabVIEWBoard.this.openPopupButton.setVisible(true);
LabVIEWBoard.this.openPopupButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.open("/weblab/web/labview/?session_id=" + LabVIEWBoard.this.boardController.getSessionId().getRealId(), "_blank", "resizable=yes,scrollbars=yes,dependent=yes,width=1000,height=800,top=0");
}
});
/*
final String [] commands = responseCommand.getCommandString().split(";");
if(commands.length < 5){
LabVIEWBoard.this.html.setHTML("Invalid response: not enough arguments: " + responseCommand.getCommandString());
return;
}
final int height = Integer.parseInt(commands[0]);
final int width = Integer.parseInt(commands[1]);
final String viName = commands[2];
final String server = commands[3];
final String version = commands[4];
final String htmlCode = LabViewObjectGenerator.generate(height, width, viName, server, version);
LabVIEWBoard.this.html.setHTML(htmlCode);
*/
}
});
}
@Override
public void end() {
if(this.timer != null)
this.timer.dispose();
if(this.html != null)
this.html.setHTML("");
}
@Override
public Widget getWidget() {
return this.panel;
}
}
|
package com.haya.tabulae.activities;
import java.util.ArrayList;
import java.util.Iterator;
import com.activeandroid.query.Select;
import com.haya.tabulae.R;
import com.haya.tabulae.adapters.ListedItemAdapter;
import com.haya.tabulae.models.Item;
import com.haya.tabulae.models.ListedItem;
import com.haya.tabulae.models.Market;
import com.haya.tabulae.models.Price;
import com.haya.tabulae.utils.Utils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.InputType;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
// Mock
final static String DEFAULT_LIST = "My quick list";
private String[] mPlanetTitles = {"All items", "Settings", "About"};
@SuppressWarnings("unused")
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
@SuppressWarnings("unused")
private ActionMode actionMode;
private ListView listView;
private Spinner marketSpinner;
private TextView price;
private ArrayList<ListedItem> listedItems;
private ListedItemAdapter adapterListedItems;
private ArrayList<Item> allItems = new ArrayList<Item>();
private ArrayList<Market> markets;
private ArrayAdapter<Market> adapterSpinner;
private final int NEW_MARKET_RESULT = 100;
private final int ITEM_DETAIL = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.setBackground(this, android.R.color.holo_purple);
// Keep the screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
init();
loadData();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
startItemDetail(position);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_add:
addItemDialog();
return true;
case R.id.action_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (NEW_MARKET_RESULT) :
if (resultCode == Activity.RESULT_OK) {
loadMarkets();
}
break;
case (ITEM_DETAIL) :
if (resultCode == Activity.RESULT_OK) {
recalculatePrice();
}
}
}
private void init() {
listView = (ListView) findViewById(android.R.id.list);
marketSpinner = (Spinner) findViewById(R.id.marketSelector);
price = (TextView) findViewById(R.id.price);
listView.setOnItemClickListener(this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int numSelected = 0;
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
MenuItem item = menu.findItem(R.id.item_edit);
if (numSelected == 1) {
item.setVisible(true);
} else {
item.setVisible(false);
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
adapterListedItems.clearSelection();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
numSelected = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contextual, menu);
actionMode = mode;
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.item_delete:
deleteItemsDialog(numSelected, mode);
numSelected = 0;
break;
case R.id.item_edit:
Toast.makeText(getApplicationContext(), "Editing item...", Toast.LENGTH_SHORT).show();
mode.finish();
break;
}
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
if (checked) {
numSelected++;
adapterListedItems.setNewSelection(position, checked);
} else {
numSelected
adapterListedItems.removeSelection(position);
}
mode.setTitle(numSelected + " selected");
mode.invalidate();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
listView.setItemChecked(position, !adapterListedItems.isPositionChecked(position));
return false;
}
});
marketSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
adapterListedItems.notifyDataSetChanged();
recalculatePrice();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
// Populate View
private void loadData() {
loadDrawer();
loadItems();
loadMarkets();
loadPrices();
recalculatePrice();
}
@SuppressLint("NewApi")
private void loadDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), mPlanetTitles[position] + " pushed", Toast.LENGTH_LONG).show();
}
});
}
private void loadItems() {
listedItems = new Select().from(ListedItem.class).execute();
if ( listedItems.isEmpty() ) {
Log.d("Tabulae", "Loading data base 1st time.");
Item item = new Item("Tomate");
ListedItem temp = new ListedItem(DEFAULT_LIST, item);
listedItems.add(temp);
item.save();
temp.save();
item = new Item("Pan");
temp = new ListedItem(DEFAULT_LIST, item);
listedItems.add(temp);
item.save();
temp.save();
item = new Item("Detergente");
temp = new ListedItem(DEFAULT_LIST, item);
listedItems.add(temp);
item.save();
temp.save();
} else {
Log.d("Tabulae", "Data base was loaded.");
}
adapterListedItems = new ListedItemAdapter(this, R.layout.listed_item, R.id.ItemTitle, listedItems, marketSpinner);
listView.setAdapter(adapterListedItems);
}
private void loadMarkets() {
markets = new Select().from(Market.class).execute();
if ( markets.isEmpty() ) {
Market market = new Market("Mercadona");
markets.add(market);
market.save();
adapterSpinner = new ArrayAdapter<Market>(this, R.layout.spinner_item, markets);
marketSpinner.setAdapter(adapterSpinner);
} else {
adapterSpinner = new ArrayAdapter<Market>(this, R.layout.spinner_item, markets);
marketSpinner.setAdapter(adapterSpinner);
}
}
private void loadPrices() {
ArrayList<Price> prices = new Select().from(Price.class).execute();
if ( prices.isEmpty() ) {
for(ListedItem listedItem : listedItems) {
Market market = (Market) marketSpinner.getSelectedItem();
Price price = new Price(listedItem.getItem(), market, (float) Math.random() * 15);
price.save();
}
adapterSpinner = new ArrayAdapter<Market>(this, R.layout.spinner_item, markets);
marketSpinner.setAdapter(adapterSpinner);
}
}
private void recalculatePrice() {
float totalPrice = 0.0f;
Market selectedMarket = (Market) marketSpinner.getSelectedItem();
ArrayList<Price> itemPrices;
for(ListedItem listedItem : listedItems) {
itemPrices = (ArrayList<Price>) listedItem.getItem().prices();
for(Price price : itemPrices) {
if ( price.getMarket().equals(selectedMarket) ) {
totalPrice += price.getPrice();
}
}
}
price.setText(totalPrice + "");
}
// Item
private void addItemDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog;
builder.setTitle(getResources().getText(R.string.newItem));
allItems = new Select().from(Item.class).execute();
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this, android.R.layout.simple_dropdown_item_1line, allItems);
final AutoCompleteTextView autoText = new AutoCompleteTextView(this);
autoText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
autoText.requestFocus();
autoText.setAdapter(adapter);
autoText.setThreshold(2);
builder.setView(autoText);
builder.setPositiveButton(getResources().getText(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String itemName = autoText.getText().toString().trim();
if ( !itemName.isEmpty() ) {
addItem(itemName);
}
}
});
// CANCEL
builder.setNegativeButton(getResources().getText(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = builder.create();
dialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
private void addItem(String itemName) {
Item item = new Select().from(Item.class).where("name = ?", itemName).executeSingle();
if ( item == null ) {
item = new Item(itemName);
item.save();
ListedItem listedItem = new ListedItem(DEFAULT_LIST, item);
listedItems.add(listedItem);
listedItem.save();
startItemDetail(listedItems.size() - 1);
} else {
ListedItem listedItem = new ListedItem(DEFAULT_LIST, item);
listedItems.add(listedItem);
listedItem.save();
adapterListedItems.notifyDataSetChanged();
}
}
private void startItemDetail(int position) {
Intent intent = new Intent(this, ItemDetailActivity.class);
long idItem = listedItems.get(position).getItem().getId();
intent.putExtra("idItem", idItem);
startActivityForResult(intent, ITEM_DETAIL);
}
public void checkItem(View v) {
adapterListedItems.notifyDataSetChanged();
}
private void deleteItemsDialog(int numItems, final ActionMode mode) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog;
String title = getText(R.string.deleteItem).toString() + " " + numItems + " ";
title += numItems > 1 ? getResources().getText(R.string.items) : getResources().getText(R.string.item);
builder.setTitle(title);
builder.setPositiveButton(getResources().getText(android.R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteItem(mode);
}
});
// CANCEL
builder.setNegativeButton(getResources().getText(android.R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog = builder.create();
dialog.show();
}
private void deleteItem(ActionMode mode) {
Iterator<Integer> it = adapterListedItems.getCurrentCheckedPosition().iterator();
ArrayList<ListedItem> deletedItems = new ArrayList<ListedItem>();
while ( it.hasNext() ) {
int index = it.next().intValue();
ListedItem temp = listedItems.get(index);
deletedItems.add(temp);
temp.delete();
}
listedItems.removeAll(deletedItems);
adapterListedItems.clearSelection();
mode.finish();
}
// Market
public void addMarket(View v) {
Intent intent = new Intent(getApplicationContext(), NewMarketActivity.class);
startActivityForResult(intent, NEW_MARKET_RESULT);
}
}
|
package com.kovaciny.linemonitorbot;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
MenuItem mJobPicker;
MenuItem mLinePicker;
MenuItem mDebugDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mJobPicker = (MenuItem) menu.findItem(R.id.action_pick_job);
mLinePicker = (MenuItem) menu.findItem(R.id.action_pick_line);
mDebugDisplay = (MenuItem) menu.findItem(R.id.debug_display);
mDebugDisplay.setVisible(false);
//populate the line picker with lines
new PopulateMenusTask().execute();
Menu pickLineSubMenu = mLinePicker.getSubMenu();
pickLineSubMenu.clear();
String lineList[] = getResources().getStringArray(R.array.line_list);
for (int i=0; i<lineList.length; i++) {
pickLineSubMenu.add(lineList[i]);
}
//populate the job picker with jobs
Menu pickJobSubMenu = mJobPicker.getSubMenu();
pickJobSubMenu.clear();
String jobList[]= {"Wo #1", "Wo #2"};
int jobListGroup = 0;
for (int i=0; i<jobList.length; i++) {
int menuId = i;
pickJobSubMenu.add(jobListGroup, menuId, Menu.FLAG_APPEND_TO_GROUP, jobList[i]);
}
int jobOptionsGroup = 1;
pickJobSubMenu.add(jobOptionsGroup, R.id.new_wo, Menu.FLAG_APPEND_TO_GROUP, "+ New");
pickJobSubMenu.add(jobOptionsGroup, R.id.clear_wos, Menu.FLAG_APPEND_TO_GROUP, "Clear");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_wo:
item.setTitle("new wo");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a SectionFragment with the page number as its lone argument.
Fragment fragment;
switch(position){
case 0:
fragment = new SkidTimesFragment();
break;
case 1:
fragment = new RatesFragment();
break;
case 2:
fragment = new DrainingFragment();
break;
default:
fragment = new SectionFragment();
}
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class PopulateMenusTask extends AsyncTask<Void,Void,Void> {
public PopulateMenusTask() {
super();
}
@Override
protected Void doInBackground(Void... arg0) {
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}
|
package org.phenotips.data.script;
import org.phenotips.data.Consent;
import org.phenotips.data.ConsentManager;
import org.phenotips.data.Patient;
import org.phenotips.entities.PrimaryEntity;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.test.mockito.MockitoComponentMockingRule;
import java.util.LinkedHashSet;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.when;
public class ConsentManagerScriptServiceTest
{
@Rule
public final MockitoComponentMockingRule<ConsentManagerScriptService> mocker = new MockitoComponentMockingRule<>(
ConsentManagerScriptService.class);
private ConsentManager consentManager;
@Mock
private Patient patient;
@Mock
private Consent consent1;
@Mock
private Consent consent2;
@Before
public void setUp() throws ComponentLookupException
{
MockitoAnnotations.initMocks(this);
this.consentManager = this.mocker.getInstance(ConsentManager.class);
}
@Test
public void hasConsentTest() throws ComponentLookupException
{
when(this.consentManager.hasConsent("P0123456", "consent")).thenReturn(true);
Assert.assertTrue(this.mocker.getComponentUnderTest().hasConsent("P0123456", "consent"));
}
@Test
public void hasNoConsentTest() throws ComponentLookupException
{
when(this.consentManager.hasConsent("P0123456", "consent")).thenReturn(false);
Assert.assertFalse(this.mocker.getComponentUnderTest().hasConsent("P0123456", "consent"));
}
@Test
public void invalidPatientId() throws ComponentLookupException
{
Set<Consent> consents = new LinkedHashSet<>();
consents.add(this.consent1);
consents.add(this.consent2);
when(this.consentManager.toJSON(consents)).thenReturn(null);
Assert.assertNull(this.mocker.getComponentUnderTest().getAllConsentsForPatient(PrimaryEntity.JSON_KEY_ID));
}
@Test
public void getConsentsForPatientWithException() throws ComponentLookupException
{
Set<Consent> consents = new LinkedHashSet<>();
Assert.assertTrue(consents.isEmpty());
when(this.consentManager.getAllConsentsForPatient(this.patient)).thenThrow(new NullPointerException());
Assert.assertNull(this.mocker.getComponentUnderTest().getAllConsentsForPatient(PrimaryEntity.JSON_KEY_ID));
}
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.motion.MotionEditorAction;
import com.maddyhome.idea.vim.action.motion.TextObjectAction;
import com.maddyhome.idea.vim.command.*;
import com.maddyhome.idea.vim.common.Jump;
import com.maddyhome.idea.vim.common.Mark;
import com.maddyhome.idea.vim.common.TextRange;
import com.maddyhome.idea.vim.helper.ApiHelper;
import com.maddyhome.idea.vim.helper.EditorData;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.key.KeyParser;
import com.maddyhome.idea.vim.option.BoundStringOption;
import com.maddyhome.idea.vim.option.NumberOption;
import com.maddyhome.idea.vim.option.Options;
import com.maddyhome.idea.vim.ui.ExEntryPanel;
import com.maddyhome.idea.vim.ui.MorePanel;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.File;
/**
* This handles all motion related commands and marks
*/
public class MotionGroup extends AbstractActionGroup {
public static final int LAST_F = 1;
public static final int LAST_f = 2;
public static final int LAST_T = 3;
public static final int LAST_t = 4;
public static final int LAST_COLUMN = 9999;
/**
* Create the group
*/
public MotionGroup() {
EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(EditorFactoryEvent event) {
final Editor editor = event.getEditor();
// This ridiculous code ensures that a lot of events are processed BEFORE we finally start listening
// to visible area changes. The primary reason for this change is to fix the cursor position bug
// using the gd and gD commands (Goto Declaration). This bug has been around since Idea 6.0.4?
// Prior to this change the visible area code was moving the cursor around during file load and messing
// with the cursor position of the Goto Declaration processing.
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
addEditorListener(editor);
EditorData.setMotionGroup(editor, true);
}
});
}
});
}
});
}
public void editorReleased(EditorFactoryEvent event) {
Editor editor = event.getEditor();
if (EditorData.getMotionGroup(editor)) {
removeEditorListener(editor);
EditorData.setMotionGroup(editor, false);
}
}
});
}
public void turnOn() {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
addEditorListener(editor);
}
}
public void turnOff() {
Editor[] editors = EditorFactory.getInstance().getAllEditors();
for (Editor editor : editors) {
removeEditorListener(editor);
}
}
private void addEditorListener(Editor editor) {
editor.addEditorMouseListener(mouseHandler);
editor.addEditorMouseMotionListener(mouseHandler);
editor.getSelectionModel().addSelectionListener(selectionHandler);
editor.getScrollingModel().addVisibleAreaListener(scrollHandler);
}
private void removeEditorListener(Editor editor) {
editor.removeEditorMouseListener(mouseHandler);
editor.removeEditorMouseMotionListener(mouseHandler);
editor.getSelectionModel().removeSelectionListener(selectionHandler);
editor.getScrollingModel().removeVisibleAreaListener(scrollHandler);
}
/**
* Process mouse clicks by setting/resetting visual mode. There are some strange scenerios to handle.
*
* @param editor The editor
* @param event The mouse event
*/
private void processMouseClick(Editor editor, MouseEvent event) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
if (MorePanel.getInstance().isActive()) {
MorePanel.getInstance().deactivate(false);
}
int visualMode = 0;
switch (event.getClickCount() % 3) {
case 1: // Single click or quad click
visualMode = 0;
break;
case 2: // Double click
visualMode = Command.FLAG_MOT_CHARACTERWISE;
break;
case 0: // Triple click
visualMode = Command.FLAG_MOT_LINEWISE;
// Pop state of being in Visual Char mode
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
editor.getSelectionModel().setSelection(start, end - 1);
break;
}
setVisualMode(editor, null, visualMode);
switch (CommandState.getInstance(editor).getSubMode()) {
case 0:
VisualPosition vp = editor.getCaretModel().getVisualPosition();
int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column,
CommandState.getInstance(editor).getMode() == CommandState.MODE_INSERT ||
CommandState.getInstance(editor).getMode() == CommandState.MODE_REPLACE);
if (col != vp.column) {
editor.getCaretModel().moveToVisualPosition(new VisualPosition(vp.line, col));
}
MotionGroup.scrollCaretIntoView(editor);
break;
case Command.FLAG_MOT_CHARACTERWISE:
/*
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive"))
{
adj = 0;
}
*/
editor.getCaretModel().moveToOffset(visualEnd);
break;
case Command.FLAG_MOT_LINEWISE:
editor.getCaretModel().moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint()));
break;
}
visualOffset = editor.getCaretModel().getOffset();
EditorData.setLastColumn(editor, EditorHelper.getCurrentVisualColumn(editor));
if (logger.isDebugEnabled()) {
logger.debug("Mouse click: vp=" + editor.getCaretModel().getVisualPosition() +
"lp=" + editor.getCaretModel().getLogicalPosition() +
"offset=" + editor.getCaretModel().getOffset());
}
}
/**
* Handles mouse drags by properly setting up visual mode based on the new selection.
*
* @param editor The editor the mouse drag occured in.
* @param update True if update, false if not.
*/
private void processLineSelection(Editor editor, boolean update) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
if (MorePanel.getInstance().isActive()) {
MorePanel.getInstance().deactivate(false);
}
if (update) {
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
updateSelection(editor, null, editor.getCaretModel().getOffset());
}
}
else {
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (logger.isDebugEnabled()) {
logger.debug("start=" + start);
logger.debug("end=" + end);
}
editor.getSelectionModel().setSelection(start, end - 1);
setVisualMode(editor, null, Command.FLAG_MOT_LINEWISE);
VisualChange range = getVisualOperatorRange(editor, Command.FLAG_MOT_LINEWISE);
if (logger.isDebugEnabled()) logger.debug("range=" + range);
if (range.getLines() > 1) {
MotionGroup.moveCaret(editor, null, moveCaretVertical(editor, -1));
}
}
}
private void processMouseReleased(Editor editor, int mode, int startOff, int endOff) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
if (MorePanel.getInstance().isActive()) {
MorePanel.getInstance().deactivate(false);
}
logger.debug("mouse released");
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandState.getInstance(editor).popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (logger.isDebugEnabled()) {
logger.debug("startOff=" + startOff);
logger.debug("endOff=" + endOff);
logger.debug("start=" + start);
logger.debug("end=" + end);
}
if (mode == Command.FLAG_MOT_LINEWISE) {
end
endOff
}
if (end == startOff || end == endOff) {
int t = start;
start = end;
end = t;
if (mode == Command.FLAG_MOT_CHARACTERWISE) {
start
}
}
MotionGroup.moveCaret(editor, null, start);
toggleVisual(editor, null, 1, 0, mode);
MotionGroup.moveCaret(editor, null, end);
KeyHandler.getInstance().reset(editor);
}
public static int moveCaretToMotion(Editor editor, DataContext context, int count, int rawCount, Argument argument) {
Command cmd = argument.getMotion();
// Normalize the counts between the command and the motion argument
int cnt = cmd.getCount() * count;
int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt;
MotionEditorAction action = (MotionEditorAction)cmd.getAction();
// Execute the motion (without moving the cursor) and get where we end
int offset = action.getOffset(editor, context, cnt, raw, cmd.getArgument());
moveCaret(editor, context, offset);
return offset;
}
public TextRange getWordRange(Editor editor, DataContext context, int count, boolean isOuter, boolean isBig) {
int dir = 1;
boolean selection = false;
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
if (visualEnd < visualStart) {
dir = -1;
}
if (visualStart != visualEnd) {
selection = true;
}
}
return SearchHelper.findWordUnderCursor(editor, count, dir, isOuter, isBig, selection);
}
public TextRange getBlockRange(Editor editor, DataContext context, int count, boolean isOuter, char type) {
return SearchHelper.findBlockRange(editor, type, count, isOuter);
}
public TextRange getSentenceRange(Editor editor, DataContext context, int count, boolean isOuter) {
return SearchHelper.findSentenceRange(editor, count, isOuter);
}
public TextRange getParagraphRange(Editor editor, DataContext context, int count, boolean isOuter) {
return SearchHelper.findParagraphRange(editor, count, isOuter);
}
/**
* This helper method calculates the complete range a motion will move over taking into account whether
* the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE).
*
* @param editor The editor the motion takes place in
* @param context The data context
* @param count The count applied to the motion
* @param rawCount The actual count entered by the user
* @param argument Any argument needed by the motion
* @param incNewline True if to include newline
* @param moveCursor True if cursor should be moved just as if motion command were executed by user, false if not
* @return The motion's range
*/
public static TextRange getMotionRange(Editor editor, DataContext context, int count, int rawCount,
Argument argument, boolean incNewline, boolean moveCursor) {
Command cmd = argument.getMotion();
// Normalize the counts between the command and the motion argument
int cnt = cmd.getCount() * count;
int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt;
int start = 0;
int end = 0;
if (cmd.getAction() instanceof MotionEditorAction) {
MotionEditorAction action = (MotionEditorAction)cmd.getAction();
// This is where we are now
start = editor.getCaretModel().getOffset();
// Execute the motion (without moving the cursor) and get where we end
end = action.getOffset(editor, context, cnt, raw, cmd.getArgument());
// Invalid motion
if (end == -1) {
return null;
}
if (moveCursor) {
moveCaret(editor, context, end);
}
}
else if (cmd.getAction() instanceof TextObjectAction) {
TextObjectAction action = (TextObjectAction)cmd.getAction();
TextRange range = action.getRange(editor, context, cnt, raw, cmd.getArgument());
if (range == null) {
return null;
}
start = range.getStartOffset();
end = range.getEndOffset();
if (moveCursor) {
moveCaret(editor, context, start);
}
}
// If we are a linewise motion we need to normalize the start and stop then move the start to the beginning
// of the line and move the end to the end of the line.
int flags = cmd.getFlags();
if ((flags & Command.FLAG_MOT_LINEWISE) != 0) {
if (start > end) {
int t = start;
start = end;
end = t;
}
start = EditorHelper.getLineStartForOffset(editor, start);
end = Math.min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0),
EditorHelper.getFileSize(editor));
}
// If characterwise and inclusive, add the last character to the range
else if ((flags & Command.FLAG_MOT_INCLUSIVE) != 0) {
end = end + (start <= end ? 1 : -1);
}
// Normalize the range
if (start > end) {
int t = start;
start = end;
end = t;
}
return new TextRange(start, end);
}
public int moveCaretToNthCharacter(Editor editor, int count) {
return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1));
}
public int moveCaretToMarkLine(Editor editor, DataContext context, char ch) {
Mark mark = CommandGroups.getInstance().getMark().getMark(editor, ch);
if (mark != null) {
VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
int line = mark.getLogicalLine();
if (!mark.getFilename().equals(vf.getPath())) {
editor = selectEditor(editor, EditorData.getVirtualFile(editor));
if (editor != null) {
moveCaret(editor, context, moveCaretToLineStartSkipLeading(editor, line));
}
return -2;
}
else {
return moveCaretToLineStartSkipLeading(editor, line);
}
}
else {
return -1;
}
}
public int moveCaretToFileMarkLine(Editor editor, DataContext context, char ch) {
Mark mark = CommandGroups.getInstance().getMark().getFileMark(editor, ch);
if (mark != null) {
int line = mark.getLogicalLine();
return moveCaretToLineStartSkipLeading(editor, line);
}
else {
return -1;
}
}
public int moveCaretToMark(Editor editor, DataContext context, char ch) {
Mark mark = CommandGroups.getInstance().getMark().getMark(editor, ch);
if (mark != null) {
VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol());
if (!vf.getPath().equals(mark.getFilename())) {
editor = selectEditor(editor, EditorData.getVirtualFile(editor));
if (editor != null) {
moveCaret(editor, context, editor.logicalPositionToOffset(lp));
}
return -2;
}
else {
return editor.logicalPositionToOffset(lp);
}
}
else {
return -1;
}
}
public int moveCaretToJump(Editor editor, DataContext context, int count) {
int spot = CommandGroups.getInstance().getMark().getJumpSpot();
Jump jump = CommandGroups.getInstance().getMark().getJump(count);
if (jump != null) {
VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
LogicalPosition lp = new LogicalPosition(jump.getLogicalLine(), jump.getCol());
if (!vf.getPath().equals(jump.getFilename())) {
VirtualFile newFile = LocalFileSystem.getInstance().findFileByPath(jump.getFilename().replace(File.separatorChar, '/'));
if (newFile == null) return -2;
Editor newEditor = selectEditor(editor, newFile);
if (newEditor != null) {
if (spot == -1) {
CommandGroups.getInstance().getMark().addJump(editor, context, false);
}
moveCaret(newEditor, context, EditorHelper.normalizeOffset(newEditor, newEditor.logicalPositionToOffset(lp), false));
}
return -2;
}
else {
if (spot == -1) {
CommandGroups.getInstance().getMark().addJump(editor, context, false);
}
return editor.logicalPositionToOffset(lp);
}
}
else {
return -1;
}
}
public int moveCaretToFileMark(Editor editor, DataContext context, char ch) {
Mark mark = CommandGroups.getInstance().getMark().getFileMark(editor, ch);
if (mark != null) {
LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol());
return editor.logicalPositionToOffset(lp);
}
else {
return -1;
}
}
private Editor selectEditor(Editor editor, VirtualFile file) {
Project proj = EditorData.getProject(editor);
return CommandGroups.getInstance().getFile().selectEditor(proj, file);
}
public int moveCaretToMatchingPair(Editor editor, DataContext context) {
int pos = SearchHelper.findMatchingPairOnCurrentLine(editor);
if (pos >= 0) {
return pos;
}
else {
return -1;
}
}
/**
* This moves the caret to the start of the next/previous camel word.
*
* @param editor The editor to move in
* @param count The number of words to skip
* @return position
*/
public int moveCaretToNextCamel(Editor editor, int count) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
return SearchHelper.findNextCamelStart(editor, count);
}
}
/**
* This moves the caret to the start of the next/previous camel word.
*
* @param editor The editor to move in
* @param count The number of words to skip
* @return position
*/
public int moveCaretToNextCamelEnd(Editor editor, int count) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
return SearchHelper.findNextCamelEnd(editor, count);
}
}
/**
* This moves the caret to the start of the next/previous word/WORD.
*
* @param editor The editor to move in
* @param count The number of words to skip
* @param skipPunc If true then find WORD, if false then find word
* @return position
*/
public int moveCaretToNextWord(Editor editor, int count, boolean skipPunc) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
return SearchHelper.findNextWord(editor, count, skipPunc);
}
}
/**
* This moves the caret to the end of the next/previous word/WORD.
*
* @param editor The editor to move in
* @param count The number of words to skip
* @param skipPunc If true then find WORD, if false then find word
* @return position
*/
public int moveCaretToNextWordEnd(Editor editor, int count, boolean skipPunc) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
// If we are doing this move as part of a change command (e.q. cw), we need to count the current end of
// word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count
// the current word.
boolean stay = CommandState.getInstance(editor).getCommand().getType() == Command.CHANGE;
int pos = SearchHelper.findNextWordEnd(editor, count, skipPunc, stay);
if (pos == -1) {
if (count < 0) {
return moveCaretToLineStart(editor, 0);
}
else {
return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false);
}
}
else {
return pos;
}
}
/**
* This moves the caret to the start of the next/previous paragraph.
*
* @param editor The editor to move in
* @param count The number of paragraphs to skip
* @return position
*/
public int moveCaretToNextParagraph(Editor editor, int count) {
int res = SearchHelper.findNextParagraph(editor, count, false);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
else {
res = -1;
}
return res;
}
public int moveCaretToNextSentenceStart(Editor editor, int count) {
int res = SearchHelper.findNextSentenceStart(editor, count, false, true);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
else {
res = -1;
}
return res;
}
public int moveCaretToNextSentenceEnd(Editor editor, int count) {
int res = SearchHelper.findNextSentenceEnd(editor, count, false, true);
if (res >= 0) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
else {
res = -1;
}
return res;
}
public int moveCaretToUnmatchedBlock(Editor editor, int count, char type) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
int res = SearchHelper.findUnmatchedBlock(editor, type, count);
if (res != -1) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
return res;
}
}
public int moveCaretToSection(Editor editor, char type, int dir, int count) {
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0)) {
return -1;
}
else {
int res = SearchHelper.findSection(editor, type, dir, count);
if (res != -1) {
res = EditorHelper.normalizeOffset(editor, res, false);
}
return res;
}
}
public int moveCaretToMethodStart(Editor editor, int count) {
return SearchHelper.findMethodStart(editor, count);
}
public int moveCaretToMethodEnd(Editor editor, int count) {
return SearchHelper.findMethodEnd(editor, count);
}
public void setLastFTCmd(int lastFTCmd, char lastChar) {
this.lastFTCmd = lastFTCmd;
this.lastFTChar = lastChar;
}
public int repeatLastMatchChar(Editor editor, int count) {
int res = -1;
switch (lastFTCmd) {
case LAST_F:
res = moveCaretToNextCharacterOnLine(editor, -count, lastFTChar);
break;
case LAST_f:
res = moveCaretToNextCharacterOnLine(editor, count, lastFTChar);
break;
case LAST_T:
res = moveCaretToBeforeNextCharacterOnLine(editor, -count, lastFTChar);
break;
case LAST_t:
res = moveCaretToBeforeNextCharacterOnLine(editor, count, lastFTChar);
break;
}
return res;
}
/**
* This moves the caret to the next/previous matching character on the current line
*
* @param count The number of occurences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToNextCharacterOnLine(Editor editor, int count, char ch) {
int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch);
if (pos >= 0) {
return pos;
}
else {
return -1;
}
}
/**
* This moves the caret next to the next/previous matching character on the current line
*
* @param count The number of occurences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToBeforeNextCharacterOnLine(Editor editor, int count, char ch) {
int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch);
if (pos >= 0) {
int step = count >= 0 ? 1 : -1;
return pos - step;
}
else {
return -1;
}
}
public boolean scrollLineToFirstScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start) {
scrollLineToScreenLine(editor, context, 1, rawCount, count, start);
return true;
}
public boolean scrollLineToMiddleScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start) {
scrollLineToScreenLine(editor, context, EditorHelper.getScreenHeight(editor) / 2 + 1, rawCount, count, start);
return true;
}
public boolean scrollLineToLastScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start) {
scrollLineToScreenLine(editor, context, EditorHelper.getScreenHeight(editor), rawCount, count, start);
return true;
}
public boolean scrollColumnToFirstScreenColumn(Editor editor, DataContext context) {
scrollColumnToScreenColumn(editor, 0);
return true;
}
public boolean scrollColumnToLastScreenColumn(Editor editor, DataContext context) {
scrollColumnToScreenColumn(editor, EditorHelper.getScreenWidth(editor));
return true;
}
private void scrollColumnToScreenColumn(Editor editor, int scol) {
int scrolloff = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value();
int width = EditorHelper.getScreenWidth(editor);
if (scrolloff > width / 2) {
scrolloff = width / 2;
}
if (scol <= width / 2) {
if (scol < scrolloff + 1) {
scol = scrolloff + 1;
}
}
else {
if (scol > width - scrolloff) {
scol = width - scrolloff;
}
}
int vcol = EditorHelper.getCurrentVisualColumn(editor);
scrollColumnToLeftOfScreen(editor, EditorHelper.normalizeVisualColumn(editor,
EditorHelper.getCurrentVisualLine(editor), vcol - scol + 1,
false));
}
private void scrollLineToScreenLine(Editor editor, DataContext context, int sline, int rawCount, int count,
boolean start) {
int scrolloff = ((NumberOption)Options.getInstance().getOption("scrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
if (scrolloff > height / 2) {
scrolloff = height / 2;
}
if (sline <= height / 2) {
if (sline < scrolloff + 1) {
sline = scrolloff + 1;
}
}
else {
if (sline > height - scrolloff) {
sline = height - scrolloff;
}
}
int vline = rawCount == 0 ?
EditorHelper.getCurrentVisualLine(editor) : EditorHelper.logicalLineToVisualLine(editor, count - 1);
scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, vline - sline + 1));
if (vline != EditorHelper.getCurrentVisualLine(editor) || start) {
int offset;
if (start) {
offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, vline));
}
else {
offset = moveCaretVertical(editor,
EditorHelper.visualLineToLogicalLine(editor, vline) - EditorHelper.getCurrentLogicalLine(editor));
}
moveCaret(editor, context, offset);
}
}
public int moveCaretToFirstScreenLine(Editor editor, DataContext context, int count) {
return moveCaretToScreenLine(editor, count);
}
public int moveCaretToLastScreenLine(Editor editor, DataContext context, int count) {
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count + 1);
}
public int moveCaretToLastScreenLineEnd(Editor editor, DataContext context, int count) {
int offset = moveCaretToLastScreenLine(editor, context, count);
LogicalPosition lline = editor.offsetToLogicalPosition(offset);
return moveCaretToLineEnd(editor, lline.line, false);
}
public int moveCaretToMiddleScreenLine(Editor editor, DataContext context) {
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2 + 1);
}
private int moveCaretToScreenLine(Editor editor, int line) {
//saveJumpLocation(editor, context);
int scrolloff = ((NumberOption)Options.getInstance().getOption("scrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
if (scrolloff > height / 2) {
scrolloff = height / 2;
}
int top = EditorHelper.getVisualLineAtTopOfScreen(editor);
if (line > height - scrolloff && top < EditorHelper.getLineCount(editor) - height) {
line = height - scrolloff;
}
else if (line <= scrolloff && top > 0) {
line = scrolloff + 1;
}
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, top + line - 1));
}
public boolean scrollHalfPage(Editor editor, DataContext context, int dir, int count) {
NumberOption scroll = (NumberOption)Options.getInstance().getOption("scroll");
int height = EditorHelper.getScreenHeight(editor) / 2;
if (count == 0) {
count = scroll.value();
if (count == 0) {
count = height;
}
}
else {
scroll.set(count);
}
return scrollPage(editor, context, dir, count, EditorHelper.getCurrentVisualScreenLine(editor), true);
}
public boolean scrollColumn(Editor editor, DataContext context, int columns) {
int vcol = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
vcol = EditorHelper.normalizeVisualColumn(editor, EditorHelper.getCurrentVisualLine(editor), vcol + columns,
false);
scrollColumnToLeftOfScreen(editor, vcol);
moveCaretToView(editor, context);
return true;
}
public boolean scrollLine(Editor editor, DataContext context, int lines) {
if (logger.isDebugEnabled()) logger.debug("lines=" + lines);
int vline = EditorHelper.getVisualLineAtTopOfScreen(editor);
vline = EditorHelper.normalizeVisualLine(editor, vline + lines);
scrollLineToTopOfScreen(editor, vline);
moveCaretToView(editor, context);
return true;
}
public static void moveCaretToView(Editor editor, DataContext context) {
if (logger.isDebugEnabled()) logger.debug("editor=" + editor);
int scrolloff = ((NumberOption)Options.getInstance().getOption("scrolloff")).value();
int sidescrolloff = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value();
int height = EditorHelper.getScreenHeight(editor);
int width = EditorHelper.getScreenWidth(editor);
if (scrolloff > height / 2) {
scrolloff = height / 2;
}
if (sidescrolloff > width / 2) {
sidescrolloff = width / 2;
}
int vline = EditorHelper.getVisualLineAtTopOfScreen(editor);
int cline = EditorHelper.getCurrentVisualLine(editor);
int newline = cline;
if (cline < vline + scrolloff) {
newline = EditorHelper.normalizeVisualLine(editor, vline + scrolloff);
}
else if (cline >= vline + height - scrolloff) {
newline = EditorHelper.normalizeVisualLine(editor, vline + height - scrolloff - 1);
}
if (logger.isDebugEnabled()) logger.debug("vline=" + vline + ", cline=" + cline + ", newline=" + newline);
int col = EditorHelper.getCurrentVisualColumn(editor);
int ocol = col;
if (col >= EditorHelper.getLineLength(editor) - 1) {
col = EditorData.getLastColumn(editor);
}
int vcol = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
int ccol = col;
int newcol = ccol;
if (ccol < vcol + sidescrolloff) {
newcol = vcol + sidescrolloff;
}
else if (ccol >= vcol + width - sidescrolloff) {
newcol = vcol + width - sidescrolloff - 1;
}
if (logger.isDebugEnabled()) logger.debug("col=" + col + ", vcol=" + vcol + ", ccol=" + ccol + ", newcol=" + newcol);
if (newline == cline && newcol != ccol) {
col = newcol;
}
newcol = EditorHelper.normalizeVisualColumn(editor, newline, newcol, CommandState.inInsertMode(editor));
if (newline != cline || newcol != ocol) {
int offset = EditorHelper.visualPostionToOffset(editor, new VisualPosition(newline, newcol));
moveCaret(editor, context, offset);
EditorData.setLastColumn(editor, col);
}
}
public boolean scrollFullPage(Editor editor, DataContext context, int pages) {
int height = EditorHelper.getScreenHeight(editor);
int line = pages > 0 ? 1 : height;
return scrollPage(editor, context, pages, height - 2, line, false);
}
public boolean scrollPage(Editor editor, DataContext context, int pages, int height, int line, boolean partial) {
if (logger.isDebugEnabled()) logger.debug("scrollPage(" + pages + ")");
int tline = EditorHelper.getVisualLineAtTopOfScreen(editor);
/*
if ((tline == 0 && pages < 0) || (tline == EditorHelper.getVisualLineCount(editor) - 1 && pages > 0))
{
return false;
}
*/
int newline = tline + pages * height;
int topline = EditorHelper.normalizeVisualLine(editor, newline);
boolean moved = scrollLineToTopOfScreen(editor, topline);
tline = EditorHelper.getVisualLineAtTopOfScreen(editor);
if (moved && topline == newline && topline == tline) {
moveCaret(editor, context, moveCaretToScreenLine(editor, line));
return true;
}
else if (moved && !partial) {
int vline = Math.abs(tline - newline) % height + 1;
if (pages < 0) {
vline = height - vline + 3;
}
moveCaret(editor, context, moveCaretToScreenLine(editor, vline));
return true;
}
else if (partial) {
int cline = EditorHelper.getCurrentVisualLine(editor);
int vline = cline + pages * height;
vline = EditorHelper.normalizeVisualLine(editor, vline);
if (cline == vline) {
return false;
}
int lline = editor.visualToLogicalPosition(new VisualPosition(vline, 0)).line;
moveCaret(editor, context, moveCaretToLineStartSkipLeading(editor, lline));
return true;
}
else {
moveCaret(editor, context, moveCaretToLineStartSkipLeading(editor));
return false;
}
}
private static boolean scrollLineToTopOfScreen(Editor editor, int vline) {
EditorScrollHandler.ignoreChanges(true);
int pos = vline * editor.getLineHeight();
int vpos = editor.getScrollingModel().getVerticalScrollOffset();
editor.getScrollingModel().scrollVertically(pos);
EditorScrollHandler.ignoreChanges(false);
return vpos != editor.getScrollingModel().getVerticalScrollOffset();
}
private static void scrollColumnToLeftOfScreen(Editor editor, int vcol) {
EditorScrollHandler.ignoreChanges(true);
editor.getScrollingModel().scrollHorizontally(vcol * EditorHelper.getColumnWidth(editor));
EditorScrollHandler.ignoreChanges(false);
}
public int moveCaretToMiddleColumn(Editor editor) {
int width = EditorHelper.getScreenWidth(editor) / 2;
int len = EditorHelper.getLineLength(editor);
return moveCaretToColumn(editor, Math.max(0, Math.min(len - 1, width)), false);
}
public int moveCaretToColumn(Editor editor, int count, boolean allowEnd) {
int line = EditorHelper.getCurrentLogicalLine(editor);
int pos = EditorHelper.normalizeColumn(editor, line, count, allowEnd);
return editor.logicalPositionToOffset(new LogicalPosition(line, pos));
}
public int moveCaretToLineStartSkipLeading(Editor editor) {
int lline = EditorHelper.getCurrentLogicalLine(editor);
return moveCaretToLineStartSkipLeading(editor, lline);
}
public int moveCaretToLineStartSkipLeadingOffset(Editor editor, int offset) {
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineStartSkipLeading(Editor editor, int lline) {
return EditorHelper.getLeadingCharacterOffset(editor, lline);
}
public int moveCaretToLineEndSkipLeadingOffset(Editor editor, int offset) {
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineEndSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineEndSkipLeading(Editor editor, int lline) {
int start = EditorHelper.getLineStartOffset(editor, lline);
int end = EditorHelper.getLineEndOffset(editor, lline, true);
CharSequence chars = EditorHelper.getDocumentChars(editor);
int pos = start;
for (int offset = end; offset > start; offset
if (offset >= chars.length()) {
break;
}
if (!Character.isWhitespace(chars.charAt(offset))) {
pos = offset;
break;
}
}
return pos;
}
public int moveCaretToLineEnd(Editor editor, boolean allowPastEnd) {
return moveCaretToLineEnd(editor, EditorHelper.getCurrentLogicalLine(editor), allowPastEnd);
}
public int moveCaretToLineEnd(Editor editor, int lline, boolean allowPastEnd) {
return EditorHelper.normalizeOffset(editor, lline, EditorHelper.getLineEndOffset(editor, lline, allowPastEnd),
allowPastEnd);
}
public int moveCaretToLineEndOffset(Editor editor, int cntForward, boolean allowPastEnd) {
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + cntForward);
if (line < 0) {
return 0;
}
else {
return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd);
}
}
public int moveCaretToLineStart(Editor editor) {
int lline = EditorHelper.getCurrentLogicalLine(editor);
return moveCaretToLineStart(editor, lline);
}
public int moveCaretToLineStart(Editor editor, int lline) {
if (lline >= EditorHelper.getLineCount(editor)) {
return EditorHelper.getFileSize(editor);
}
return EditorHelper.getLineStartOffset(editor, lline);
}
public int moveCaretToLineStartOffset(Editor editor, int offset) {
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineStart(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineScreenStart(Editor editor) {
int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
return moveCaretToColumn(editor, col, false);
}
public int moveCaretToLineScreenStartSkipLeading(Editor editor) {
int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
int lline = EditorHelper.getCurrentLogicalLine(editor);
return EditorHelper.getLeadingCharacterOffset(editor, lline, col);
}
public int moveCaretToLineScreenEnd(Editor editor, boolean allowEnd) {
int col = EditorHelper.getVisualColumnAtLeftOfScreen(editor) + EditorHelper.getScreenWidth(editor) - 1;
return moveCaretToColumn(editor, col, allowEnd);
}
public int moveCaretHorizontalWrap(Editor editor, int count) {
// FIX - allows cursor over newlines
int oldoffset = editor.getCaretModel().getOffset();
int offset = Math.min(Math.max(0, editor.getCaretModel().getOffset() + count), EditorHelper.getFileSize(editor));
if (offset == oldoffset) {
return -1;
}
else {
return offset;
}
}
public int moveCaretHorizontal(Editor editor, int count, boolean allowPastEnd) {
int oldoffset = editor.getCaretModel().getOffset();
int offset = EditorHelper.normalizeOffset(editor, EditorHelper.getCurrentLogicalLine(editor), oldoffset + count,
allowPastEnd);
if (offset == oldoffset) {
return -1;
}
else {
return offset;
}
}
public int moveCaretVertical(Editor editor, int count) {
VisualPosition pos = editor.getCaretModel().getVisualPosition();
if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0)) {
return -1;
}
else {
int col = EditorData.getLastColumn(editor);
int line = EditorHelper.normalizeVisualLine(editor, pos.line + count);
VisualPosition newPos = new VisualPosition(line, EditorHelper.normalizeVisualColumn(editor, line, col, CommandState.inInsertMode(editor)));
return EditorHelper.visualPostionToOffset(editor, newPos);
}
}
public int moveCaretToLine(Editor editor, DataContext context, int lline) {
int col = EditorData.getLastColumn(editor);
int line = lline;
if (lline < 0) {
line = 0;
col = 0;
}
else if (lline >= EditorHelper.getLineCount(editor)) {
line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1);
col = EditorHelper.getLineLength(editor, line);
}
LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col, false));
return editor.logicalPositionToOffset(newPos);
}
public int moveCaretToLinePercent(Editor editor, DataContext context, int count) {
if (count > 100) count = 100;
return moveCaretToLineStartSkipLeading(editor, EditorHelper.normalizeLine(
editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1));
}
public int moveCaretGotoLineLast(Editor editor, DataContext context, int rawCount, int lline) {
return moveCaretToLineStartSkipLeading(editor, rawCount == 0 ?
EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : lline);
}
public int moveCaretGotoLineLastEnd(Editor editor, DataContext context, int rawCount, int lline, boolean pastEnd) {
return moveCaretToLineEnd(editor, rawCount == 0 ?
EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : lline, pastEnd);
}
public int moveCaretGotoLineFirst(Editor editor, DataContext context, int lline) {
return moveCaretToLineStartSkipLeading(editor, lline);
}
public static void moveCaret(Editor editor, DataContext context, int offset) {
if (offset >= 0 && offset <= editor.getDocument().getTextLength()) {
editor.getCaretModel().moveToOffset(offset);
EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
scrollCaretIntoView(editor);
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandGroups.getInstance().getMotion().updateSelection(editor, context, offset);
}
else {
editor.getSelectionModel().removeSelection();
}
}
}
public int moveCaretGotoPreviousTab(final DataContext context) {
final AnAction previousTab = ActionManager.getInstance().getAction("PreviousTab");
previousTab.actionPerformed(new AnActionEvent(
null,
context,
"",
new Presentation(),
ActionManager.getInstance(),
0));
return 0;
}
public int moveCaretGotoNextTab(final DataContext context) {
final AnAction previousTab = ActionManager.getInstance().getAction("NextTab");
previousTab.actionPerformed(new AnActionEvent(
null,
context,
"",
new Presentation(),
ActionManager.getInstance(),
0));
return 0;
}
public static void scrollCaretIntoView(Editor editor) {
int cline = EditorHelper.getCurrentVisualLine(editor);
int vline = EditorHelper.getVisualLineAtTopOfScreen(editor);
boolean scrolljump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SCROLL_JUMP) == 0;
int scrolloff = ((NumberOption)Options.getInstance().getOption("scrolloff")).value();
int sjSize = 0;
if (scrolljump) {
sjSize = Math.max(0, ((NumberOption)Options.getInstance().getOption("scrolljump")).value() - 1);
}
int height = EditorHelper.getScreenHeight(editor);
int vtop = vline + scrolloff;
int vbot = vline + height - scrolloff;
if (scrolloff >= height / 2) {
scrolloff = height / 2;
vtop = vline + scrolloff;
vbot = vline + height - scrolloff;
if (vtop == vbot) {
vbot++;
}
}
int diff;
if (cline < vtop) {
diff = cline - vtop;
sjSize = -sjSize;
}
else {
diff = cline - vbot + 1;
if (diff < 0) {
diff = 0;
}
}
if (diff != 0) {
int line;
// If we need to move the top line more than a half screen worth then we just center the cursor line
if (Math.abs(diff) > height / 2) {
line = cline - height / 2 - 1;
}
// Otherwise put the new cursor line "scrolljump" lines from the top/bottom
else {
line = vline + diff + sjSize;
}
line = Math.min(line, EditorHelper.getVisualLineCount(editor) - height);
line = Math.max(0, line);
scrollLineToTopOfScreen(editor, line);
}
int ccol = EditorHelper.getCurrentVisualColumn(editor);
int vcol = EditorHelper.getVisualColumnAtLeftOfScreen(editor);
int width = EditorHelper.getScreenWidth(editor);
scrolljump = (CommandState.getInstance(editor).getFlags() & Command.FLAG_IGNORE_SIDE_SCROLL_JUMP) == 0;
scrolloff = ((NumberOption)Options.getInstance().getOption("sidescrolloff")).value();
sjSize = 0;
if (scrolljump) {
sjSize = Math.max(0, ((NumberOption)Options.getInstance().getOption("sidescroll")).value() - 1);
if (sjSize == 0) {
sjSize = width / 2;
}
}
int vleft = vcol + scrolloff;
int vright = vcol + width - scrolloff;
if (scrolloff >= width / 2) {
scrolloff = width / 2;
vleft = vcol + scrolloff;
vright = vcol + width - scrolloff;
if (vleft == vright) {
vright++;
}
}
sjSize = Math.min(sjSize, width / 2 - scrolloff);
if (ccol < vleft) {
diff = ccol - vleft + 1;
sjSize = -sjSize;
}
else {
diff = ccol - vright + 1;
if (diff < 0) {
diff = 0;
}
}
if (diff != 0) {
int col;
if (Math.abs(diff) > width / 2) {
col = ccol - width / 2 - 1;
}
else {
col = vcol + diff + sjSize;
}
//col = Math.min(col, EditorHelper.getMaximumColumnWidth());
col = Math.max(0, col);
scrollColumnToLeftOfScreen(editor, col);
}
}
public boolean selectPreviousVisualMode(Editor editor, DataContext context) {
logger.debug("selectPreviousVisualMode");
VisualRange vr = EditorData.getLastVisualRange(editor);
if (vr == null) {
return false;
}
if (logger.isDebugEnabled()) logger.debug("vr=" + vr);
CommandState.getInstance(editor).pushState(CommandState.MODE_VISUAL, vr.getType(), KeyParser.MAPPING_VISUAL);
visualStart = vr.getStart();
visualEnd = vr.getEnd();
visualOffset = vr.getOffset();
updateSelection(editor, context, visualEnd);
editor.getCaretModel().moveToOffset(visualOffset);
//EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
//MotionGroup.moveCaret(editor, context, vr.getOffset());
return true;
}
public boolean swapVisualSelections(Editor editor, DataContext context) {
VisualRange vr = EditorData.getLastVisualRange(editor);
if (vr == null) {
return false;
}
EditorData.setLastVisualRange(editor, new VisualRange(visualStart, visualEnd,
CommandState.getInstance(editor).getSubMode(), visualOffset));
visualStart = vr.getStart();
visualEnd = vr.getEnd();
visualOffset = vr.getOffset();
CommandState.getInstance(editor).setSubMode(vr.getType());
updateSelection(editor, context, visualEnd);
editor.getCaretModel().moveToOffset(visualOffset);
//EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
//MotionGroup.moveCaret(editor, context, vr.getOffset());
return true;
}
public void setVisualMode(Editor editor, DataContext context, int mode) {
logger.debug("setVisualMode");
int oldMode = CommandState.getInstance(editor).getSubMode();
if (mode == 0) {
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (start != end) {
int line = editor.offsetToLogicalPosition(start).line;
int lstart = EditorHelper.getLineStartOffset(editor, line);
int lend = EditorHelper.getLineEndOffset(editor, line, true);
if (logger.isDebugEnabled()) logger.debug("start=" + start + ", end=" + end + ", lstart=" + lstart + ", lend=" + lend);
if (lstart == start && lend + 1 == end) {
mode = Command.FLAG_MOT_LINEWISE;
}
else {
mode = Command.FLAG_MOT_CHARACTERWISE;
}
}
}
if (oldMode == 0 && mode == 0) {
editor.getSelectionModel().removeSelection();
return;
}
if (mode == 0) {
exitVisual(editor);
}
else {
CommandState.getInstance(editor).pushState(CommandState.MODE_VISUAL, mode, KeyParser.MAPPING_VISUAL);
}
KeyHandler.getInstance().reset(editor);
visualStart = editor.getSelectionModel().getSelectionStart();
visualEnd = editor.getSelectionModel().getSelectionEnd();
if (CommandState.getInstance(editor).getSubMode() == Command.FLAG_MOT_CHARACTERWISE) {
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive")) {
adj = 0;
}
visualEnd -= adj;
}
visualOffset = editor.getCaretModel().getOffset();
if (logger.isDebugEnabled()) logger.debug("visualStart=" + visualStart + ", visualEnd=" + visualEnd);
CommandGroups.getInstance().getMark().setMark(editor, context, '<', visualStart);
CommandGroups.getInstance().getMark().setMark(editor, context, '>', visualEnd);
}
public boolean toggleVisual(Editor editor, DataContext context, int count, int rawCount, int mode) {
if (logger.isDebugEnabled()) logger.debug("toggleVisual: mode=" + mode);
int currentMode = CommandState.getInstance(editor).getSubMode();
if (CommandState.getInstance(editor).getMode() != CommandState.MODE_VISUAL) {
int start;
int end;
if (rawCount > 0) {
VisualChange range = EditorData.getLastVisualOperatorRange(editor);
if (range == null) {
logger.debug("no prior visual range");
return false;
}
else {
if (logger.isDebugEnabled()) logger.debug("last visual change: " + range);
}
mode = range.getType();
start = editor.getCaretModel().getOffset();
end = calculateVisualRange(editor, context, range, count);
}
else {
start = end = editor.getSelectionModel().getSelectionStart();
}
CommandState.getInstance(editor).pushState(CommandState.MODE_VISUAL, mode, KeyParser.MAPPING_VISUAL);
visualStart = start;
updateSelection(editor, context, end);
MotionGroup.moveCaret(editor, context, visualEnd);
}
else if (mode == currentMode) {
exitVisual(editor);
}
else {
CommandState.getInstance(editor).setSubMode(mode);
updateSelection(editor, context, visualEnd);
}
return true;
}
private int calculateVisualRange(Editor editor, DataContext context, VisualChange range, int count) {
int lines = range.getLines();
int chars = range.getColumns();
if (range.getType() == Command.FLAG_MOT_LINEWISE || range.getType() == Command.FLAG_MOT_BLOCKWISE || lines > 1) {
lines *= count;
}
if ((range.getType() == Command.FLAG_MOT_CHARACTERWISE && lines == 1) || range.getType() == Command.FLAG_MOT_BLOCKWISE) {
chars *= count;
}
int start = editor.getCaretModel().getOffset();
LogicalPosition sp = editor.offsetToLogicalPosition(start);
int endLine = sp.line + lines - 1;
int res;
if (range.getType() == Command.FLAG_MOT_LINEWISE) {
res = moveCaretToLine(editor, context, endLine);
}
else if (range.getType() == Command.FLAG_MOT_CHARACTERWISE) {
if (lines > 1) {
res = moveCaretToLineStart(editor, endLine) +
Math.min(EditorHelper.getLineLength(editor, endLine), chars);
}
else {
res = EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false);
}
}
else {
int endcol = Math.min(EditorHelper.getLineLength(editor, endLine), sp.column + chars - 1);
res = editor.logicalPositionToOffset(new LogicalPosition(endLine, endcol));
}
return res;
}
public void exitVisual(Editor editor) {
resetVisual(editor);
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandState.getInstance(editor).popState();
}
}
public void resetVisual(Editor editor) {
logger.debug("resetVisual");
EditorData.setLastVisualRange(editor, new VisualRange(visualStart,
visualEnd, CommandState.getInstance(editor).getSubMode(), visualOffset));
if (logger.isDebugEnabled()) logger.debug("visualStart=" + visualStart + ", visualEnd=" + visualEnd);
editor.getSelectionModel().removeSelection();
CommandState.getInstance(editor).setSubMode(0);
}
public VisualChange getVisualOperatorRange(Editor editor, int cmdFlags) {
logger.debug("vis op range");
int start = visualStart;
int end = visualEnd;
if (start > end) {
int t = start;
start = end;
end = t;
}
start = EditorHelper.normalizeOffset(editor, start, false);
end = EditorHelper.normalizeOffset(editor, end, false);
if (logger.isDebugEnabled()) {
logger.debug("start=" + start);
logger.debug("end=" + end);
}
LogicalPosition sp = editor.offsetToLogicalPosition(start);
LogicalPosition ep = editor.offsetToLogicalPosition(end);
int lines = ep.line - sp.line + 1;
int chars;
int type;
if (CommandState.getInstance(editor).getSubMode() == Command.FLAG_MOT_LINEWISE ||
(cmdFlags & Command.FLAG_MOT_LINEWISE) != 0) {
chars = ep.column;
type = Command.FLAG_MOT_LINEWISE;
}
else if (CommandState.getInstance(editor).getSubMode() == Command.FLAG_MOT_CHARACTERWISE) {
type = Command.FLAG_MOT_CHARACTERWISE;
if (lines > 1) {
chars = ep.column;
}
else {
chars = ep.column - sp.column + 1;
}
}
else {
chars = ep.column - sp.column + 1;
if (EditorData.getLastColumn(editor) == MotionGroup.LAST_COLUMN) {
chars = MotionGroup.LAST_COLUMN;
}
type = Command.FLAG_MOT_BLOCKWISE;
}
if (logger.isDebugEnabled()) {
logger.debug("lines=" + lines);
logger.debug("chars=" + chars);
logger.debug("type=" + type);
}
return new VisualChange(lines, chars, type);
}
public TextRange getVisualRange(Editor editor) {
if (ApiHelper.supportsBlockSelection() && editor.getSelectionModel().hasBlockSelection()) {
TextRange res = new TextRange(editor.getSelectionModel().getBlockSelectionStarts(),
editor.getSelectionModel().getBlockSelectionEnds());
// If the last left/right motion was the $ command, simulate each line being selected to end-of-line
if (EditorData.getLastColumn(editor) >= MotionGroup.LAST_COLUMN) {
int[] starts = res.getStartOffsets();
int[] ends = res.getEndOffsets();
for (int i = 0; i < starts.length; i++) {
if (ends[i] > starts[i]) {
ends[i] = EditorHelper.getLineEndForOffset(editor, starts[i]);
}
}
res = new TextRange(starts, ends);
}
return res;
}
else {
return new TextRange(editor.getSelectionModel().getSelectionStart(),
editor.getSelectionModel().getSelectionEnd());
}
}
public TextRange getRawVisualRange() {
return new TextRange(visualStart, visualEnd);
}
private void updateSelection(Editor editor, DataContext context, int offset) {
logger.debug("updateSelection");
visualEnd = offset;
visualOffset = offset;
int start = visualStart;
int end = visualEnd;
if (start > end) {
int t = start;
start = end;
end = t;
}
if (CommandState.getInstance(editor).getSubMode() == Command.FLAG_MOT_CHARACTERWISE) {
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int lineend = EditorHelper.getLineEndForOffset(editor, end);
if (logger.isDebugEnabled()) {
logger.debug("lineend=" + lineend);
logger.debug("end=" + end);
}
int adj = 1;
if (opt.getValue().equals("exclusive") || end == lineend) {
adj = 0;
}
end = Math.min(EditorHelper.getFileSize(editor), end + adj);
if (logger.isDebugEnabled()) logger.debug("start=" + start + ", end=" + end);
editor.getSelectionModel().setSelection(start, end);
}
else if (CommandState.getInstance(editor).getSubMode() == Command.FLAG_MOT_LINEWISE) {
start = EditorHelper.getLineStartForOffset(editor, start);
end = EditorHelper.getLineEndForOffset(editor, end);
if (logger.isDebugEnabled()) logger.debug("start=" + start + ", end=" + end);
editor.getSelectionModel().setSelection(start, end);
}
else if (ApiHelper.supportsBlockSelection()) {
LogicalPosition lstart = editor.offsetToLogicalPosition(start);
LogicalPosition lend = editor.offsetToLogicalPosition(end);
if (logger.isDebugEnabled()) logger.debug("lstart=" + lstart + ", lend=" + lend);
editor.getSelectionModel().setBlockSelection(lstart, lend);
}
CommandGroups.getInstance().getMark().setMark(editor, context, '<', start);
CommandGroups.getInstance().getMark().setMark(editor, context, '>', end);
}
public boolean swapVisualEnds(Editor editor, DataContext context) {
int t = visualEnd;
visualEnd = visualStart;
visualStart = t;
moveCaret(editor, context, visualEnd);
return true;
}
public boolean swapVisualEndsBlock(Editor editor, DataContext context) {
if (CommandState.getInstance(editor).getSubMode() != Command.FLAG_MOT_BLOCKWISE) {
return swapVisualEnds(editor, context);
}
LogicalPosition lstart = editor.getSelectionModel().getBlockStart();
LogicalPosition lend = editor.getSelectionModel().getBlockEnd();
if (lstart == null || lend == null) {
return false;
}
if (visualStart > visualEnd) {
LogicalPosition t = lend;
lend = lstart;
lstart = t;
}
LogicalPosition nstart = new LogicalPosition(lstart.line, lend.column);
LogicalPosition nend = new LogicalPosition(lend.line, lstart.column);
visualStart = editor.logicalPositionToOffset(nstart);
visualEnd = editor.logicalPositionToOffset(nend);
moveCaret(editor, context, visualEnd);
return true;
}
public void moveVisualStart(Editor editor, int startOffset) {
visualStart = startOffset;
}
public void processEscape(Editor editor, DataContext context) {
exitVisual(editor);
}
public static class MotionEditorChange extends FileEditorManagerAdapter {
public void selectionChanged(FileEditorManagerEvent event) {
if (ExEntryPanel.getInstance().isActive()) {
ExEntryPanel.getInstance().deactivate(false);
}
if (MorePanel.getInstance().isActive()) {
MorePanel.getInstance().deactivate(false);
}
FileEditor fe = event.getOldEditor();
if (fe instanceof TextEditor) {
Editor editor = ((TextEditor)fe).getEditor();
if (CommandState.getInstance(editor).getMode() == CommandState.MODE_VISUAL) {
CommandGroups.getInstance().getMotion().exitVisual(
EditorHelper.getEditor(event.getManager(), event.getOldFile()));
}
}
}
}
private static class EditorSelectionHandler implements SelectionListener {
public void selectionChanged(SelectionEvent selectionEvent) {
if (makingChanges) return;
makingChanges = true;
Editor editor = selectionEvent.getEditor();
TextRange range = new TextRange(selectionEvent.getNewRange().getStartOffset(), selectionEvent.getNewRange().getEndOffset());
Editor[] editors = EditorFactory.getInstance().getEditors(editor.getDocument());
for (Editor ed : editors) {
if (ed.equals(editor)) {
continue;
}
ed.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
ed.getCaretModel().moveToOffset(editor.getCaretModel().getOffset());
}
makingChanges = false;
}
private boolean makingChanges = false;
}
private static class EditorScrollHandler implements VisibleAreaListener {
public static void ignoreChanges(boolean ignore) {
EditorScrollHandler.ignore = ignore;
}
public void visibleAreaChanged(VisibleAreaEvent visibleAreaEvent) {
if (ignore) return;
Editor editor = visibleAreaEvent.getEditor();
if (CommandState.inInsertMode(editor)) {
return;
}
if (logger.isDebugEnabled()) {
logger.debug("old=" + visibleAreaEvent.getOldRectangle());
logger.debug("new=" + visibleAreaEvent.getNewRectangle());
}
if (!visibleAreaEvent.getNewRectangle().equals(visibleAreaEvent.getOldRectangle())) {
if (!EditorData.isConsoleOutput(editor) && !isTabSwitchEvent(visibleAreaEvent)) {
MotionGroup.moveCaretToView(editor, null);
}
}
}
private static boolean isTabSwitchEvent(final VisibleAreaEvent visibleAreaEvent) {
final Rectangle newRectangle = visibleAreaEvent.getNewRectangle();
return newRectangle.width == 0 || newRectangle.height == 0;
}
private static boolean ignore = false;
}
private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener {
public void mouseMoved(EditorMouseEvent event) {
// no-op
}
public void mouseDragged(EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA ||
event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) {
if (dragEditor == null) {
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
mode = Command.FLAG_MOT_CHARACTERWISE;
}
else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA) {
mode = Command.FLAG_MOT_LINEWISE;
}
startOff = event.getEditor().getSelectionModel().getSelectionStart();
endOff = event.getEditor().getSelectionModel().getSelectionEnd();
if (logger.isDebugEnabled()) logger.debug("startOff=" + startOff);
}
dragEditor = event.getEditor();
}
}
public void mousePressed(EditorMouseEvent event) {
// no-op
}
public void mouseClicked(EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA) {
CommandGroups.getInstance().getMotion().processMouseClick(event.getEditor(), event.getMouseEvent());
//event.consume();
}
else if (event.getArea() != EditorMouseEventArea.ANNOTATIONS_AREA && event.getArea() != EditorMouseEventArea.FOLDING_OUTLINE_AREA) {
CommandGroups.getInstance().getMotion().processLineSelection(
event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3);
//event.consume();
}
}
public void mouseReleased(EditorMouseEvent event) {
if (!VimPlugin.isEnabled()) return;
if (event.getEditor().equals(dragEditor)) {
CommandGroups.getInstance().getMotion().processMouseReleased(event.getEditor(), mode, startOff, endOff);
//event.consume();
dragEditor = null;
}
}
public void mouseEntered(EditorMouseEvent event) {
// no-op
}
public void mouseExited(EditorMouseEvent event) {
// no-op
}
private Editor dragEditor = null;
private int mode;
private int startOff;
private int endOff;
}
private int lastFTCmd = 0;
private char lastFTChar;
private int visualStart;
private int visualEnd;
private int visualOffset;
private EditorMouseHandler mouseHandler = new EditorMouseHandler();
private EditorSelectionHandler selectionHandler = new EditorSelectionHandler();
private EditorScrollHandler scrollHandler = new EditorScrollHandler();
private static Logger logger = Logger.getInstance(MotionGroup.class.getName());
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.VisualPosition;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.event.EditorMouseEventArea;
import com.intellij.openapi.editor.event.EditorMouseListener;
import com.intellij.openapi.editor.event.EditorMouseMotionListener;
import com.intellij.openapi.editor.event.SelectionEvent;
import com.intellij.openapi.editor.event.SelectionListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerAdapter;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.KeyHandler;
import com.maddyhome.idea.vim.VimPlugin;
import com.maddyhome.idea.vim.action.motion.MotionEditorAction;
import com.maddyhome.idea.vim.command.Argument;
import com.maddyhome.idea.vim.command.Command;
import com.maddyhome.idea.vim.command.CommandState;
import com.maddyhome.idea.vim.command.VisualChange;
import com.maddyhome.idea.vim.command.VisualRange;
import com.maddyhome.idea.vim.common.Mark;
import com.maddyhome.idea.vim.helper.EditorData;
import com.maddyhome.idea.vim.helper.EditorHelper;
import com.maddyhome.idea.vim.helper.SearchHelper;
import com.maddyhome.idea.vim.key.KeyParser;
import com.maddyhome.idea.vim.option.BoundStringOption;
import com.maddyhome.idea.vim.option.NumberOption;
import com.maddyhome.idea.vim.option.Options;
import java.awt.event.MouseEvent;
/**
* This handles all motion related commands and marks
* TODO:
* Jumplists
*/
public class MotionGroup extends AbstractActionGroup
{
public static final int LAST_F = 1;
public static final int LAST_f = 2;
public static final int LAST_T = 3;
public static final int LAST_t = 4;
/**
* Create the group
*/
public MotionGroup()
{
EditorFactory.getInstance().addEditorFactoryListener(new EditorFactoryAdapter() {
public void editorCreated(EditorFactoryEvent event)
{
Editor editor = event.getEditor();
EditorMouseHandler handler = new EditorMouseHandler();
editor.addEditorMouseListener(handler);
editor.addEditorMouseMotionListener(handler);
editor.getSelectionModel().addSelectionListener(selectionHandler);
}
});
}
/**
* Handles mouse drags by properly setting up visual mode based on the new selection
* @param editor The editor the mouse drag occured in
*/
private void processMouseDrag(Editor editor)
{
// Mouse drags can only result in CHARWISE selection
// We want to move the mouse back one character to be consistence with how regular motion highlights text.
// Don't move the cursor if the user ended up selecting no characters.
// Once the cursor is set, save the current column.
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandState.getInstance().popState();
}
int offset = editor.getCaretModel().getOffset();
int start = editor.getSelectionModel().getSelectionStart();
logger.debug("offset=" + offset + ", start=" + start);
if (offset > start)
{
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
if (!opt.getValue().equals("exclusive"))
{
logger.debug("moved cursor");
editor.getCaretModel().moveToOffset(offset - 1);
}
}
setVisualMode(editor, null, Command.FLAG_MOT_CHARACTERWISE);
EditorData.setLastColumn(editor, EditorHelper.getCurrentVisualColumn(editor));
}
/**
* Process mouse clicks by setting/resetting visual mode. There are some strange scenerios to handle.
* @param editor
* @param event
*/
private void processMouseClick(Editor editor, MouseEvent event)
{
int visualMode = 0;
switch (event.getClickCount() % 3)
{
case 1: // Single click or quad click
visualMode = 0;
break;
case 2: // Double click
visualMode = Command.FLAG_MOT_CHARACTERWISE;
break;
case 0: // Triple click
visualMode = Command.FLAG_MOT_LINEWISE;
// Pop state of being in Visual Char mode
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandState.getInstance().popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
editor.getSelectionModel().setSelection(start, end - 1);
break;
}
setVisualMode(editor, null, visualMode);
switch (CommandState.getInstance().getSubMode())
{
case 0:
VisualPosition vp = editor.getCaretModel().getVisualPosition();
int col = EditorHelper.normalizeVisualColumn(editor, vp.line, vp.column,
CommandState.getInstance().getMode() == CommandState.MODE_INSERT ||
CommandState.getInstance().getMode() == CommandState.MODE_REPLACE);
if (col != vp.column)
{
editor.getCaretModel().moveToVisualPosition(new VisualPosition(vp.line, col));
}
break;
case Command.FLAG_MOT_CHARACTERWISE:
/*
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive"))
{
adj = 0;
}
*/
editor.getCaretModel().moveToOffset(visualEnd);
break;
case Command.FLAG_MOT_LINEWISE:
editor.getCaretModel().moveToLogicalPosition(editor.xyToLogicalPosition(event.getPoint()));
break;
}
visualOffset = editor.getCaretModel().getOffset();
EditorData.setLastColumn(editor, EditorHelper.getCurrentVisualColumn(editor));
logger.debug("Mouse click: vp=" + editor.getCaretModel().getVisualPosition() +
"lp=" + editor.getCaretModel().getLogicalPosition() +
"offset=" + editor.getCaretModel().getOffset());
}
/**
* Handles mouse drags by properly setting up visual mode based on the new selection
* @param editor The editor the mouse drag occured in
*/
private void processLineSelection(Editor editor, boolean update)
{
if (update)
{
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
updateSelection(editor, null, editor.getCaretModel().getOffset());
}
}
else
{
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandState.getInstance().popState();
}
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
editor.getSelectionModel().setSelection(start, end - 1);
setVisualMode(editor, null, Command.FLAG_MOT_LINEWISE);
VisualChange range = getVisualOperatorRange(editor, Command.FLAG_MOT_LINEWISE);
logger.debug("range=" + range);
if (range.getLines() > 1)
{
MotionGroup.moveCaret(editor, null, moveCaretVertical(editor, -1));
}
}
}
public static int moveCaretToMotion(Editor editor, DataContext context, int count, int rawCount, Argument argument)
{
Command cmd = argument.getMotion();
// Normalize the counts between the command and the motion argument
int cnt = cmd.getCount() * count;
int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt;
MotionEditorAction action = (MotionEditorAction)cmd.getAction();
// Execute the motion (without moving the cursor) and get where we end
int offset = action.getOffset(editor, context, cnt, raw, cmd.getArgument());
moveCaret(editor, context, offset);
return offset;
}
/**
* This helper method calculates the complete range a motion will move over taking into account whether
* the motion is FLAG_MOT_LINEWISE or FLAG_MOT_CHARACTERWISE (FLAG_MOT_INCLUSIVE or FLAG_MOT_EXCLUSIVE).
* @param editor The editor the motion takes place in
* @param context The data context
* @param count The count applied to the motion
* @param rawCount The actual count entered by the user
* @param argument Any argument needed by the motion
* @param moveCursor True if cursor should be moved just as if motion command were executed by user, false if not
* @return The motion's range
*/
public static TextRange getMotionRange(Editor editor, DataContext context, int count, int rawCount,
Argument argument, boolean incNewline, boolean moveCursor)
{
Command cmd = argument.getMotion();
// Normalize the counts between the command and the motion argument
int cnt = cmd.getCount() * count;
int raw = rawCount == 0 && cmd.getRawCount() == 0 ? 0 : cnt;
MotionEditorAction action = (MotionEditorAction)cmd.getAction();
// This is where we are now
int start = editor.getCaretModel().getOffset();
// Execute the motion (without moving the cursor) and get where we end
int end = action.getOffset(editor, context, cnt, raw, cmd.getArgument());
// Invalid motion
if (end == -1)
{
return null;
}
if (moveCursor)
{
moveCaret(editor, context, end);
}
// If we are a linewise motion we need to normalize the start and stop then move the start to the beginning
// of the line and move the end to the end of the line.
int flags = cmd.getFlags();
if ((flags & Command.FLAG_MOT_LINEWISE) != 0)
{
if (start > end)
{
int t = start;
start = end;
end = t;
}
start = EditorHelper.getLineStartForOffset(editor, start);
end = Math.min(EditorHelper.getLineEndForOffset(editor, end) + (incNewline ? 1 : 0),
EditorHelper.getFileSize(editor));
}
// If characterwise and inclusive, add the last character to the range
else if ((flags & Command.FLAG_MOT_INCLUSIVE) != 0)
{
end = end + (start <= end ? 1 : -1);
}
// Normalize the range
if (start > end)
{
int t = start;
start = end;
end = t;
}
return new TextRange(start, end);
}
public int moveCaretToNthCharacter(Editor editor, int count)
{
return Math.max(0, Math.min(count, EditorHelper.getFileSize(editor) - 1));
}
public int moveCaretToMarkLine(Editor editor, DataContext context, char ch)
{
Mark mark = CommandGroups.getInstance().getMark().getMark(editor, ch);
if (mark != null)
{
VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
int line = mark.getLogicalLine();
if (!mark.getFile().equals(vf))
{
editor = selectEditor(editor, mark.getFile());
moveCaret(editor, context, moveCaretToLineStartSkipLeading(editor, line));
return -2;
}
else
{
//saveJumpLocation(editor, context);
return moveCaretToLineStartSkipLeading(editor, line);
}
}
else
{
return -1;
}
}
public int moveCaretToFileMarkLine(Editor editor, DataContext context, char ch)
{
Mark mark = CommandGroups.getInstance().getMark().getFileMark(editor, ch);
if (mark != null)
{
int line = mark.getLogicalLine();
//saveJumpLocation(editor, context);
return moveCaretToLineStartSkipLeading(editor, line);
}
else
{
return -1;
}
}
public int moveCaretToMark(Editor editor, DataContext context, char ch)
{
Mark mark = CommandGroups.getInstance().getMark().getMark(editor, ch);
if (mark != null)
{
VirtualFile vf = EditorData.getVirtualFile(editor);
if (vf == null) return -1;
LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol());
if (!vf.equals(mark.getFile()))
{
editor = selectEditor(editor, mark.getFile());
moveCaret(editor, context, editor.logicalPositionToOffset(lp));
return -2;
}
else
{
//saveJumpLocation(editor, context);
return editor.logicalPositionToOffset(lp);
}
}
else
{
return -1;
}
}
public int moveCaretToFileMark(Editor editor, DataContext context, char ch)
{
Mark mark = CommandGroups.getInstance().getMark().getFileMark(editor, ch);
if (mark != null)
{
LogicalPosition lp = new LogicalPosition(mark.getLogicalLine(), mark.getCol());
//saveJumpLocation(editor, context);
return editor.logicalPositionToOffset(lp);
}
else
{
return -1;
}
}
private Editor selectEditor(Editor editor, VirtualFile file)
{
Project proj = EditorData.getProject(editor);
FileEditorManager fMgr = FileEditorManager.getInstance(proj);
//return fMgr.openFile(new OpenFileDescriptor(file), ScrollType.RELATIVE, true);
return fMgr.openTextEditor(new OpenFileDescriptor(file), true);
}
public int moveCaretToMatchingPair(Editor editor, DataContext context)
{
int pos = SearchHelper.findMatchingPairOnCurrentLine(editor);
if (pos >= 0)
{
//saveJumpLocation(editor, context);
return pos;
}
else
{
return -1;
}
}
/**
* This moves the caret to the start of the next/previous camel word.
* @param count The number of words to skip
* @param editor The editor to move in
*/
public int moveCaretToNextCamel(Editor editor, int count)
{
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0))
{
return -1;
}
else
{
return SearchHelper.findNextCamelStart(editor, count);
}
}
/**
* This moves the caret to the start of the next/previous camel word.
* @param count The number of words to skip
* @param editor The editor to move in
*/
public int moveCaretToNextCamelEnd(Editor editor, int count)
{
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0))
{
return -1;
}
else
{
return SearchHelper.findNextCamelEnd(editor, count);
}
}
/**
* This moves the caret to the start of the next/previous word/WORD.
* @param count The number of words to skip
* @param skipPunc If true then find WORD, if false then find word
* @param editor The editor to move in
*/
public int moveCaretToNextWord(Editor editor, int count, boolean skipPunc)
{
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0))
{
return -1;
}
else
{
return SearchHelper.findNextWord(editor, count, skipPunc);
}
}
/**
* This moves the caret to the end of the next/previous word/WORD.
* @param count The number of words to skip
* @param skipPunc If true then find WORD, if false then find word
* @param editor The editor to move in
*/
public int moveCaretToNextWordEnd(Editor editor, int count, boolean skipPunc)
{
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0))
{
return -1;
}
// If we are doing this move as part of a change command (e.q. cw), we need to count the current end of
// word if the cursor happens to be on the end of a word already. If this is a normal move, we don't count
// the current word.
boolean stay = CommandState.getInstance().getCommand().getType() == Command.CHANGE;
int pos = SearchHelper.findNextWordEnd(editor, count, skipPunc, stay);
if (pos == -1)
{
if (count < 0)
{
return moveCaretToLineStart(editor, 0);
}
else
{
return moveCaretToLineEnd(editor, EditorHelper.getLineCount(editor) - 1, false);
}
}
else
{
return pos;
}
}
/**
* This moves the caret to the start of the next/previous paragraph.
* @param count The number of paragraphs to skip
* @param editor The editor to move in
*/
public int moveCaretToNextParagraph(Editor editor, int count)
{
if ((editor.getCaretModel().getOffset() == 0 && count < 0) ||
(editor.getCaretModel().getOffset() >= EditorHelper.getFileSize(editor) - 1 && count > 0))
{
return -1;
}
else
{
return EditorHelper.normalizeOffset(editor, SearchHelper.findNextParagraph(editor, count), false);
}
}
public void setLastFTCmd(int lastFTCmd, char lastChar)
{
this.lastFTCmd = lastFTCmd;
this.lastFTChar = lastChar;
}
public int repeatLastMatchChar(Editor editor, int count)
{
int res = -1;
switch (lastFTCmd)
{
case LAST_F:
res = moveCaretToNextCharacterOnLine(editor, -count, lastFTChar);
break;
case LAST_f:
res = moveCaretToNextCharacterOnLine(editor, count, lastFTChar);
break;
case LAST_T:
res = moveCaretToBeforeNextCharacterOnLine(editor, -count, lastFTChar);
break;
case LAST_t:
res = moveCaretToBeforeNextCharacterOnLine(editor, count, lastFTChar);
break;
}
return res;
}
/**
* This moves the caret to the next/previous matching character on the current line
* @param count The number of occurences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToNextCharacterOnLine(Editor editor, int count, char ch)
{
int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch);
if (pos >= 0)
{
return pos;
}
else
{
return -1;
}
}
/**
* This moves the caret next to the next/previous matching character on the current line
* @param count The number of occurences to move to
* @param ch The character to search for
* @param editor The editor to search in
* @return True if [count] character matches were found, false if not
*/
public int moveCaretToBeforeNextCharacterOnLine(Editor editor, int count, char ch)
{
int pos = SearchHelper.findNextCharacterOnLine(editor, count, ch);
if (pos >= 0)
{
int step = count >= 0 ? 1 : -1;
return pos - step;
}
else
{
return -1;
}
}
public boolean scrollLineToFirstScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start)
{
scrollLineToScreenLine(editor, context, 1, rawCount, count, start);
return true;
}
public boolean scrollLineToMiddleScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start)
{
scrollLineToScreenLine(editor, context, EditorHelper.getScreenHeight(editor) / 2, rawCount, count, start);
return true;
}
public boolean scrollLineToLastScreenLine(Editor editor, DataContext context, int rawCount, int count,
boolean start)
{
scrollLineToScreenLine(editor, context, EditorHelper.getScreenHeight(editor), rawCount, count, start);
return true;
}
private void scrollLineToScreenLine(Editor editor, DataContext context, int sline, int rawCount, int count,
boolean start)
{
int vline = rawCount == 0 ?
EditorHelper.getCurrentVisualLine(editor) : EditorHelper.logicalLineToVisualLine(editor, count - 1);
scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, vline - sline + 1));
if (vline != EditorHelper.getCurrentVisualLine(editor) || start)
{
int offset;
if (start)
{
offset = moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, vline));
}
else
{
offset = moveCaretVertical(editor,
EditorHelper.visualLineToLogicalLine(editor, vline) - EditorHelper.getCurrentLogicalLine(editor));
}
moveCaret(editor, context, offset);
}
}
public int moveCaretToFirstScreenLine(Editor editor, DataContext context, int count)
{
return moveCaretToScreenLine(editor, count);
}
public int moveCaretToLastScreenLine(Editor editor, DataContext context, int count)
{
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count);
}
public int moveCaretToLastScreenLineEnd(Editor editor, DataContext context, int count)
{
int offset = moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) - count);
LogicalPosition lline = editor.offsetToLogicalPosition(offset);
return moveCaretToLineEnd(editor, lline.line, false);
}
public int moveCaretToMiddleScreenLine(Editor editor, DataContext context)
{
return moveCaretToScreenLine(editor, EditorHelper.getScreenHeight(editor) / 2);
}
private int moveCaretToScreenLine(Editor editor, int line)
{
//saveJumpLocation(editor, context);
int height = EditorHelper.getScreenHeight(editor);
if (line > height)
{
line = height;
}
else if (line < 1)
{
line = 1;
}
int top = getVisualLineAtTopOfScreen(editor);
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, top + line - 1));
}
public boolean scrollHalfPageDown(Editor editor, DataContext context, int count)
{
NumberOption scroll = (NumberOption)Options.getInstance().getOption("scroll");
if (count == 0)
{
count = scroll.value();
if (count == 0)
{
count = EditorHelper.getScreenHeight(editor) / 2;
}
}
else
{
scroll.set(count);
}
if (EditorHelper.getCurrentVisualLine(editor) == EditorHelper.getVisualLineCount(editor) - 1)
{
return false;
}
else
{
int tline = getVisualLineAtTopOfScreen(editor);
moveCaret(editor, context, moveCaretToLineStartSkipLeadingOffset(editor, count));
scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, tline + count));
return true;
}
}
public boolean scrollHalfPageUp(Editor editor, DataContext context, int count)
{
NumberOption scroll = (NumberOption)Options.getInstance().getOption("scroll");
if (count == 0)
{
count = scroll.value();
if (count == 0)
{
count = EditorHelper.getScreenHeight(editor) / 2;
}
}
else
{
scroll.set(count);
}
int tline = getVisualLineAtTopOfScreen(editor);
if (getVisualLineAtTopOfScreen(editor) == 0)
{
return false;
}
else
{
moveCaret(editor, context, moveCaretToLineStartSkipLeadingOffset(editor, -count));
scrollLineToTopOfScreen(editor, EditorHelper.normalizeVisualLine(editor, tline - count));
return true;
}
}
public boolean scrollLine(Editor editor, DataContext context, int lines)
{
logger.debug("lines="+lines);
int vline = getVisualLineAtTopOfScreen(editor);
int cline = EditorHelper.getCurrentVisualLine(editor);
vline = EditorHelper.normalizeVisualLine(editor, vline + lines);
logger.debug("vline=" + vline + ", cline=" + cline);
scrollLineToTopOfScreen(editor, vline);
if (cline < vline)
{
moveCaret(editor, context, moveCaretVertical(editor, vline - cline));
}
else if (cline > vline + EditorHelper.getScreenHeight(editor))
{
moveCaret(editor, context, moveCaretVertical(editor, vline + EditorHelper.getScreenHeight(editor) - cline));
}
return true;
}
public boolean scrollPage(Editor editor, DataContext context, int pages)
{
logger.debug("scrollPage(" + pages + ")");
int tline = getVisualLineAtTopOfScreen(editor);
int height = EditorHelper.getScreenHeight(editor) - 2;
if ((tline == 0 && pages < 0) || (tline == EditorHelper.getVisualLineCount(editor) - 1 && pages > 0))
{
return false;
}
int cline = tline;
if (pages > 0)
{
cline += pages * height;
}
else
{
cline += ((pages + 1) * height);
}
tline = EditorHelper.normalizeVisualLine(editor, tline + pages * height);
cline = EditorHelper.normalizeVisualLine(editor, cline);
logger.debug("cline = " + cline + ", height = " + height);
moveCaret(editor, context, moveCaretToLineStartSkipLeading(editor,
EditorHelper.visualLineToLogicalLine(editor, cline)));
scrollLineToTopOfScreen(editor, tline);
return true;
}
private int getVisualLineAtTopOfScreen(Editor editor)
{
int vline = editor.getScrollingModel().getVerticalScrollOffset() / editor.getLineHeight();
logger.debug("top = " + vline);
return vline;
}
private void scrollLineToTopOfScreen(Editor editor, int vline)
{
editor.getScrollingModel().scrollVertically(vline * editor.getLineHeight());
}
public int moveCaretToMiddleColumn(Editor editor)
{
int width = EditorHelper.getScreenWidth(editor) / 2;
int len = EditorHelper.getLineLength(editor);
return moveCaretToColumn(editor, Math.max(0, Math.min(len - 1, width)));
}
public int moveCaretToColumn(Editor editor, int count)
{
int line = EditorHelper.getCurrentLogicalLine(editor);
int pos = EditorHelper.normalizeColumn(editor, line, count);
return editor.logicalPositionToOffset(new LogicalPosition(line, pos));
}
public int moveCaretToLineStartSkipLeading(Editor editor)
{
int lline = EditorHelper.getCurrentLogicalLine(editor);
return moveCaretToLineStartSkipLeading(editor, lline);
}
public int moveCaretToLineStartSkipLeadingOffset(Editor editor, int offset)
{
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineStartSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineStartSkipLeading(Editor editor, int lline)
{
return EditorHelper.getLeadingCharacterOffset(editor, lline);
}
public int moveCaretToLineEndSkipLeadingOffset(Editor editor, int offset)
{
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineEndSkipLeading(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretToLineEndSkipLeading(Editor editor, int lline)
{
int start = EditorHelper.getLineStartOffset(editor, lline);
int end = EditorHelper.getLineEndOffset(editor, lline, true);
char[] chars = editor.getDocument().getChars();
int pos = start;
for (int offset = end; offset > start; offset
{
if (offset >= chars.length)
{
break;
}
if (!Character.isWhitespace(chars[offset]))
{
pos = offset;
break;
}
}
return pos;
}
public int moveCaretToLineEnd(Editor editor, boolean allowPastEnd)
{
return moveCaretToLineEnd(editor, EditorHelper.getCurrentLogicalLine(editor), allowPastEnd);
}
public int moveCaretToLineEnd(Editor editor, int lline, boolean allowPastEnd)
{
int offset = EditorHelper.normalizeOffset(editor, lline, EditorHelper.getLineEndOffset(editor, lline, allowPastEnd),
allowPastEnd);
return offset;
}
public int moveCaretToLineEndOffset(Editor editor, int cntForward, boolean allowPastEnd)
{
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + cntForward);
if (line <= 0)
{
return 0;
}
else
{
return moveCaretToLineEnd(editor, EditorHelper.visualLineToLogicalLine(editor, line), allowPastEnd);
}
}
public int moveCaretToLineStart(Editor editor)
{
int lline = EditorHelper.getCurrentLogicalLine(editor);
return moveCaretToLineStart(editor, lline);
}
public int moveCaretToLineStart(Editor editor, int lline)
{
if (lline >= EditorHelper.getLineCount(editor))
{
return EditorHelper.getFileSize(editor);
}
int start = EditorHelper.getLineStartOffset(editor, lline);
return start;
}
public int moveCaretToLineStartOffset(Editor editor, int offset)
{
int line = EditorHelper.normalizeVisualLine(editor, EditorHelper.getCurrentVisualLine(editor) + offset);
return moveCaretToLineStart(editor, EditorHelper.visualLineToLogicalLine(editor, line));
}
public int moveCaretHorizontalWrap(Editor editor, int count)
{
// FIX - allows cursor over newlines
int oldoffset = editor.getCaretModel().getOffset();
int offset = Math.min(Math.max(0, editor.getCaretModel().getOffset() + count), EditorHelper.getFileSize(editor));
if (offset == oldoffset)
{
return -1;
}
else
{
return offset;
}
}
public int moveCaretHorizontal(Editor editor, int count, boolean allowPastEnd)
{
int oldoffset = editor.getCaretModel().getOffset();
int offset = EditorHelper.normalizeOffset(editor, EditorHelper.getCurrentLogicalLine(editor), oldoffset + count,
allowPastEnd);
if (offset == oldoffset)
{
return -1;
}
else
{
return offset;
}
}
public int moveCaretVertical(Editor editor, int count)
{
VisualPosition pos = editor.getCaretModel().getVisualPosition();
if ((pos.line == 0 && count < 0) || (pos.line >= EditorHelper.getVisualLineCount(editor) - 1 && count > 0))
{
return -1;
}
else
{
int col = EditorData.getLastColumn(editor);
int line = EditorHelper.normalizeVisualLine(editor, pos.line + count);
VisualPosition newPos = new VisualPosition(line, EditorHelper.normalizeVisualColumn(editor, line, col,
CommandState.getInstance().getMode() == CommandState.MODE_INSERT ||
CommandState.getInstance().getMode() == CommandState.MODE_REPLACE));
return EditorHelper.visualPostionToOffset(editor, newPos);
}
}
public int moveCaretToLine(Editor editor, DataContext context, int lline)
{
int col = EditorData.getLastColumn(editor);
int line = lline;
if (lline < 0)
{
line = 0;
col = 0;
}
else if (lline >= EditorHelper.getLineCount(editor))
{
line = EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1);
col = EditorHelper.getLineLength(editor, line);
}
LogicalPosition newPos = new LogicalPosition(line, EditorHelper.normalizeColumn(editor, line, col));
return editor.logicalPositionToOffset(newPos);
}
public int moveCaretToLinePercent(Editor editor, DataContext context, int count)
{
if (count > 100) count = 100;
return moveCaretToLineStartSkipLeading(editor, EditorHelper.normalizeLine(
editor, (EditorHelper.getLineCount(editor) * count + 99) / 100 - 1));
}
public int moveCaretGotoLineLast(Editor editor, DataContext context, int rawCount, int lline)
{
return moveCaretToLineStartSkipLeading(editor, rawCount == 0 ?
EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : lline);
}
public int moveCaretGotoLineLastEnd(Editor editor, DataContext context, int rawCount, int lline, boolean pastEnd)
{
return moveCaretToLineEnd(editor, rawCount == 0 ?
EditorHelper.normalizeLine(editor, EditorHelper.getLineCount(editor) - 1) : lline, pastEnd);
}
public int moveCaretGotoLineFirst(Editor editor, DataContext context, int lline)
{
return moveCaretToLineStartSkipLeading(editor, lline);
}
public static void moveCaret(Editor editor, DataContext context, int offset)
{
if (offset >= 0 && offset <= editor.getDocument().getTextLength())
{
editor.getCaretModel().moveToOffset(offset);
EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandGroups.getInstance().getMotion().updateSelection(editor, context, offset);
}
else
{
editor.getSelectionModel().removeSelection();
}
}
}
public boolean selectPreviousVisualMode(Editor editor, DataContext context)
{
logger.debug("selectPreviousVisualMode");
VisualRange vr = EditorData.getLastVisualRange(editor);
if (vr == null)
{
return false;
}
logger.debug("vr=" + vr);
CommandState.getInstance().pushState(CommandState.MODE_VISUAL, vr.getType(), KeyParser.MAPPING_VISUAL);
visualStart = vr.getStart();
visualEnd = vr.getEnd();
visualOffset = vr.getOffset();
updateSelection(editor, context, visualEnd);
editor.getCaretModel().moveToOffset(visualOffset);
//EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
//MotionGroup.moveCaret(editor, context, vr.getOffset());
return true;
}
public boolean swapVisualSelections(Editor editor, DataContext context)
{
VisualRange vr = EditorData.getLastVisualRange(editor);
if (vr == null)
{
return false;
}
EditorData.setLastVisualRange(editor, new VisualRange(visualStart, visualEnd,
CommandState.getInstance().getSubMode(), visualOffset));
visualStart = vr.getStart();
visualEnd = vr.getEnd();
visualOffset = vr.getOffset();
CommandState.getInstance().setSubMode(vr.getType());
updateSelection(editor, context, visualEnd);
editor.getCaretModel().moveToOffset(visualOffset);
//EditorData.setLastColumn(editor, editor.getCaretModel().getVisualPosition().column);
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
//MotionGroup.moveCaret(editor, context, vr.getOffset());
return true;
}
public void setVisualMode(Editor editor, DataContext context, int mode)
{
logger.debug("setVisualMode");
int oldMode = CommandState.getInstance().getSubMode();
if (mode == 0)
{
int start = editor.getSelectionModel().getSelectionStart();
int end = editor.getSelectionModel().getSelectionEnd();
if (start != end)
{
int line = editor.offsetToLogicalPosition(start).line;
int lstart = EditorHelper.getLineStartOffset(editor, line);
int lend = EditorHelper.getLineEndOffset(editor, line, true);
logger.debug("start=" + start + ", end=" + end + ", lstart=" + lstart + ", lend=" + lend);
if (lstart == start && lend + 1 == end)
{
mode = Command.FLAG_MOT_LINEWISE;
}
else
{
mode = Command.FLAG_MOT_CHARACTERWISE;
}
}
}
if (oldMode == 0 && mode == 0)
{
editor.getSelectionModel().removeSelection();
return;
}
if (mode == 0)
{
exitVisual(editor);
}
else
{
CommandState.getInstance().pushState(CommandState.MODE_VISUAL, mode, KeyParser.MAPPING_VISUAL);
}
KeyHandler.getInstance().reset();
visualStart = editor.getSelectionModel().getSelectionStart();
visualEnd = editor.getSelectionModel().getSelectionEnd();
if (CommandState.getInstance().getSubMode() == Command.FLAG_MOT_CHARACTERWISE)
{
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive"))
{
adj = 0;
}
visualEnd -= adj;
}
visualOffset = editor.getCaretModel().getOffset();
logger.debug("visualStart=" + visualStart + ", visualEnd=" + visualEnd);
CommandGroups.getInstance().getMark().setMark(editor, context, '<', visualStart);
CommandGroups.getInstance().getMark().setMark(editor, context, '>', visualEnd);
}
public boolean toggleVisual(Editor editor, DataContext context, int count, int rawCount, int mode)
{
int currentMode = CommandState.getInstance().getSubMode();
if (CommandState.getInstance().getMode() != CommandState.MODE_VISUAL)
{
int start;
int end;
if (rawCount > 0)
{
VisualChange range = EditorData.getLastVisualOperatorRange(editor);
if (range == null)
{
return false;
}
mode = range.getType();
TextRange trange = calculateVisualRange(editor, context, range, count);
start = trange.getStartOffset();
end = trange.getEndOffset();
}
else
{
start = end = editor.getSelectionModel().getSelectionStart();
}
CommandState.getInstance().pushState(CommandState.MODE_VISUAL, mode, KeyParser.MAPPING_VISUAL);
visualStart = start;
updateSelection(editor, context, end);
MotionGroup.moveCaret(editor, context, visualEnd);
}
else if (mode == currentMode)
{
exitVisual(editor);
}
else
{
CommandState.getInstance().setSubMode(mode);
updateSelection(editor, context, visualEnd);
}
return true;
}
private TextRange calculateVisualRange(Editor editor, DataContext context, VisualChange range, int count)
{
int lines = range.getLines();
int chars = range.getColumns();
if (range.getType() == Command.FLAG_MOT_LINEWISE || lines > 1)
{
lines *= count;
}
else
{
chars *= count;
}
int start = editor.getSelectionModel().getSelectionStart();
LogicalPosition sp = editor.offsetToLogicalPosition(start);
int endLine = sp.line + lines - 1;
TextRange res;
if (range.getType() == Command.FLAG_MOT_LINEWISE)
{
res = new TextRange(start, moveCaretToLine(editor, context, endLine));
}
else
{
if (lines > 1)
{
res = new TextRange(start, moveCaretToLineStart(editor, endLine) +
Math.min(EditorHelper.getLineLength(editor, endLine), chars));
}
else
{
res = new TextRange(start, EditorHelper.normalizeOffset(editor, sp.line, start + chars - 1, false));
}
}
return res;
}
public void exitVisual(Editor editor)
{
resetVisual(editor);
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandState.getInstance().popState();
}
}
public void resetVisual(Editor editor)
{
logger.debug("resetVisual");
EditorData.setLastVisualRange(editor, new VisualRange(visualStart,
visualEnd, CommandState.getInstance().getSubMode(), visualOffset));
logger.debug("visualStart=" + visualStart + ", visualEnd=" + visualEnd);
editor.getSelectionModel().removeSelection();
CommandState.getInstance().setSubMode(0);
}
public VisualChange getVisualOperatorRange(Editor editor, int cmdFlags)
{
int start = visualStart;
int end = visualEnd;
if (start > end)
{
int t = start;
start = end;
end = t;
}
start = EditorHelper.normalizeOffset(editor, start, false);
end = EditorHelper.normalizeOffset(editor, end, false);
LogicalPosition sp = editor.offsetToLogicalPosition(start);
LogicalPosition ep = editor.offsetToLogicalPosition(end);
int lines = ep.line - sp.line + 1;
int chars = 0;
int type;
if (CommandState.getInstance().getSubMode() == Command.FLAG_MOT_LINEWISE ||
(cmdFlags & Command.FLAG_MOT_LINEWISE) != 0)
{
chars = ep.column;
type = Command.FLAG_MOT_LINEWISE;
}
else
{
type = Command.FLAG_MOT_CHARACTERWISE;
if (lines > 1)
{
chars = ep.column;
}
else
{
chars = ep.column - sp.column + 1;
}
}
return new VisualChange(lines, chars, type);
}
public TextRange getVisualRange(Editor editor)
{
return new TextRange(editor.getSelectionModel().getSelectionStart(),
editor.getSelectionModel().getSelectionEnd());
}
private void updateSelection(Editor editor, DataContext context, int offset)
{
logger.debug("updateSelection");
visualEnd = offset;
visualOffset = offset;
int start = visualStart;
int end = visualEnd;
if (start > end)
{
int t = start;
start = end;
end = t;
}
if (CommandState.getInstance().getSubMode() == Command.FLAG_MOT_CHARACTERWISE)
{
BoundStringOption opt = (BoundStringOption)Options.getInstance().getOption("selection");
int adj = 1;
if (opt.getValue().equals("exclusive"))
{
adj = 0;
}
end = Math.min(EditorHelper.getFileSize(editor), end + adj);
logger.debug("start=" + start + ", end=" + end);
editor.getSelectionModel().setSelection(start, end);
}
else
{
start = EditorHelper.getLineStartForOffset(editor, start);
end = EditorHelper.getLineEndForOffset(editor, end);
logger.debug("start=" + start + ", end=" + end);
editor.getSelectionModel().setSelection(start, end);
}
CommandGroups.getInstance().getMark().setMark(editor, context, '<', start);
CommandGroups.getInstance().getMark().setMark(editor, context, '>', end);
}
public boolean swapVisualEnds(Editor editor, DataContext context)
{
int t = visualEnd;
visualEnd = visualStart;
visualStart = t;
moveCaret(editor, context, visualEnd);
return true;
}
public void processEscape(Editor editor, DataContext context)
{
exitVisual(editor);
}
public static class MotionEditorChange extends FileEditorManagerAdapter
{
public void selectionChanged(FileEditorManagerEvent event)
{
if (CommandState.getInstance().getMode() == CommandState.MODE_VISUAL)
{
CommandGroups.getInstance().getMotion().exitVisual(
EditorHelper.getEditor(event.getManager(), event.getOldFile()));
}
}
}
private static class EditorSelectionHandler implements SelectionListener
{
public void selectionChanged(SelectionEvent selectionEvent)
{
if (makingChanges) return;
makingChanges = true;
Editor editor = selectionEvent.getEditor();
TextRange range = selectionEvent.getNewRange();
Editor[] editors = EditorFactory.getInstance().getEditors(editor.getDocument());
for (int i = 0; i < editors.length; i++)
{
if (editors[i].equals(editor))
{
continue;
}
editors[i].getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
editors[i].getCaretModel().moveToOffset(editor.getCaretModel().getOffset());
}
makingChanges = false;
}
private boolean makingChanges = false;
}
private static class EditorMouseHandler implements EditorMouseListener, EditorMouseMotionListener
{
public void mouseMoved(EditorMouseEvent event)
{
// no-op
}
public void mouseDragged(EditorMouseEvent event)
{
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA ||
event.getArea() == EditorMouseEventArea.LINE_NUMBERS_AREA)
{
dragEditor = event.getEditor();
}
}
public void mousePressed(EditorMouseEvent event)
{
// no-op
}
public void mouseClicked(EditorMouseEvent event)
{
if (!VimPlugin.isEnabled()) return;
if (event.getArea() == EditorMouseEventArea.EDITING_AREA)
{
CommandGroups.getInstance().getMotion().processMouseClick(event.getEditor(), event.getMouseEvent());
event.consume();
}
else if (event.getArea() == EditorMouseEventArea.LINE_NUMBERS_AREA)
{
CommandGroups.getInstance().getMotion().processLineSelection(
event.getEditor(), event.getMouseEvent().getButton() == MouseEvent.BUTTON3);
event.consume();
}
}
public void mouseReleased(EditorMouseEvent event)
{
if (!VimPlugin.isEnabled()) return;
if (event.getEditor().equals(dragEditor))
{
if (event.getArea() == EditorMouseEventArea.EDITING_AREA)
{
CommandGroups.getInstance().getMotion().processMouseDrag(event.getEditor());
}
else if (event.getArea() == EditorMouseEventArea.LINE_NUMBERS_AREA)
{
CommandGroups.getInstance().getMotion().processLineSelection(event.getEditor(), false);
}
event.consume();
dragEditor = null;
}
}
public void mouseEntered(EditorMouseEvent event)
{
// no-op
}
public void mouseExited(EditorMouseEvent event)
{
// no-op
}
private Editor dragEditor = null;
}
private int lastFTCmd = 0;
private char lastFTChar;
private int visualStart;
private int visualEnd;
private int visualOffset;
private EditorSelectionHandler selectionHandler = new EditorSelectionHandler();
private static Logger logger = Logger.getInstance(MotionGroup.class.getName());
}
|
package com.maddyhome.idea.vim.group;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
import com.intellij.openapi.fileEditor.impl.EditorWindow;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.maddyhome.idea.vim.VimPlugin;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class WindowGroup {
public WindowGroup() {
}
public void splitWindowHorizontal(@NotNull DataContext context, String filename) {
splitWindow(SwingConstants.HORIZONTAL, context, filename);
}
public void splitWindowVertical(@NotNull DataContext context, String filename) {
splitWindow(SwingConstants.VERTICAL, context, filename);
}
private void splitWindow(int orientation, @NotNull DataContext context, String filename) {
final Project project = PlatformDataKeys.PROJECT.getData(context);
final FileEditorManagerEx fileEditorManager = FileEditorManagerEx.getInstanceEx(project);
VirtualFile virtualFile = null;
if (filename != null && filename.length() > 0 && project != null) {
virtualFile = VimPlugin.getFile().findFile(filename, project);
if (virtualFile == null) {
VimPlugin.showMessage("Could not find file: " + filename);
return;
}
}
final EditorWindow editorWindow = fileEditorManager.getSplitters().getCurrentWindow();
if (editorWindow != null) {
editorWindow.split(orientation, true, virtualFile, true);
}
}
}
|
package com.mebigfatguy.fbcontrib.utils;
@PublicAPI("Used by fb-contrib-eclipse-quickfixes to determine type of fix to apply")
public final class FQMethod {
private String className;
private String methodName;
private String signature;
public FQMethod(String className, String methodName, String signature) {
this.className = className;
this.methodName = methodName;
this.signature = signature;
}
@Override
public int hashCode() {
return className.hashCode() ^ methodName.hashCode() ^ signature.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FQMethod)) {
return false;
}
FQMethod that = (FQMethod) o;
return className.equals(that.className) && methodName.equals(that.methodName) && signature.equals(that.signature);
}
@PublicAPI("Used by fb-contrib-eclipse-quickfixes to determine type of fix to apply")
@Override
public String toString() {
return className + "." + methodName + signature;
}
}
|
package com.nexters.vobble.activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.analytics.tracking.android.Fields;
import com.nexters.vobble.R;
import com.nexters.vobble.adapter.CustomFragmentPagerAdapter;
import com.nexters.vobble.core.AccountManager;
import com.nexters.vobble.core.App;
import com.nexters.vobble.fragment.BaseMainFragment;
import com.nexters.vobble.fragment.FriendsFragment;
import com.nexters.vobble.fragment.ShowVobblesFragment;
import com.nexters.vobble.fragment.ShowVobblesFragment.VOBBLE_FRAMGMENT_TYPE;
import com.nexters.vobble.listener.ImageViewTouchListener;
import com.nexters.vobble.network.APIResponseHandler;
import com.nexters.vobble.network.HttpUtil;
import com.nexters.vobble.network.URL;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends BaseFragmentActivity implements
OnClickListener, BaseMainFragment.OnFragmentListener {
private final int TAB_COUNT = 3;
private final int INDEX_ALL_VOBBLES = 0;
private final int INDEX_MY_VOBBLES = 1;
private final int INDEX_FRIENDS_VOBBLES = 2;
private Boolean[] hasNeedToLoad = new Boolean[] { false, true, false };
private BaseMainFragment[] fragments = new BaseMainFragment[TAB_COUNT];
private FrameLayout[] tabs = new FrameLayout[TAB_COUNT];
private String[] vobblesCnt = new String[TAB_COUNT];
private TextView mTvVobbleCnt;
private TextView mTvVobbleCntType;
private ImageView mIvReloadBtn;
private ImageView mIvEventBtn;
private ViewPager mViewPager;
private CustomFragmentPagerAdapter mCustomFragmentPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initResources();
initEvents();
initFragments();
initViewPager();
loadVobblesCount(INDEX_ALL_VOBBLES);
showTab(INDEX_ALL_VOBBLES);
App.getGaTracker().set(Fields.SCREEN_NAME, this.getClass().getSimpleName());
}
private void initResources() {
tabs[INDEX_ALL_VOBBLES] = (FrameLayout) findViewById(R.id.fl_all_voice_tab_button);
tabs[INDEX_MY_VOBBLES] = (FrameLayout) findViewById(R.id.fl_my_voice_tab_button);
tabs[INDEX_FRIENDS_VOBBLES] = (FrameLayout) findViewById(R.id.fl_friends_voice_tab_button);
mTvVobbleCnt = (TextView) findViewById(R.id.tv_vobble_cnt);
mTvVobbleCntType = (TextView) findViewById(R.id.tv_vobble_cnt_type);
mIvReloadBtn = (ImageView) findViewById(R.id.iv_reload_btn);
mIvEventBtn = (ImageView) findViewById(R.id.iv_event_btn);
}
private void initEvents() {
ImageViewTouchListener ivTouchListener = new ImageViewTouchListener();
tabs[INDEX_ALL_VOBBLES].setOnClickListener(this);
tabs[INDEX_MY_VOBBLES].setOnClickListener(this);
tabs[INDEX_FRIENDS_VOBBLES].setOnClickListener(this);
mIvReloadBtn.setOnTouchListener(ivTouchListener);
mIvReloadBtn.setOnClickListener(this);
mIvEventBtn.setOnTouchListener(ivTouchListener);
mIvEventBtn.setOnClickListener(this);
}
private void initFragments() {
fragments[INDEX_ALL_VOBBLES] = new ShowVobblesFragment("", VOBBLE_FRAMGMENT_TYPE.ALL);
fragments[INDEX_MY_VOBBLES] = new ShowVobblesFragment(AccountManager.getInstance().getUserId(this), VOBBLE_FRAMGMENT_TYPE.MY);
fragments[INDEX_FRIENDS_VOBBLES] = new FriendsFragment();
}
private void initViewPager() {
FragmentManager fm = getSupportFragmentManager();
mCustomFragmentPagerAdapter = new CustomFragmentPagerAdapter(fm, TAB_COUNT, fragments);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setAdapter(mCustomFragmentPagerAdapter);
mViewPager.setOffscreenPageLimit(TAB_COUNT);
mViewPager.setCurrentItem(INDEX_ALL_VOBBLES);
mViewPager.setOnPageChangeListener(onPageChangeListener);
}
private void loadVobblesCount(int index) {
if (vobblesCnt[index] == null) {
executeGetVobblesCount(index);
return;
}
mTvVobbleCnt.setText(vobblesCnt[index]);
if (index == INDEX_ALL_VOBBLES)
mTvVobbleCntType.setText("All vobbles");
else if (index == INDEX_MY_VOBBLES)
mTvVobbleCntType.setText("My vobbles");
}
private void executeGetVobblesCount(final int index) {
String url = "";
if (index == INDEX_ALL_VOBBLES) {
url = URL.VOBBLES_COUNT;
} else if (index == INDEX_MY_VOBBLES) {
url = String.format(URL.USER_VOBBLES_COUNT, AccountManager.getInstance().getUserId(this));
}
HttpUtil.get(url, null, null, new APIResponseHandler(this) {
@Override
public void onStart() {
super.onStart();
showLoading();
}
@Override
public void onFinish() {
super.onFinish();
hideLoading();
}
@Override
public void onSuccess(JSONObject response) {
try {
vobblesCnt[index] = response.getString("count");
loadVobblesCount(index);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable error, String response) {
super.onFailure(error, response);
}
});
}
private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == INDEX_ALL_VOBBLES) {
onClick(tabs[INDEX_ALL_VOBBLES]);
} else if (position == INDEX_MY_VOBBLES) {
onClick(tabs[INDEX_MY_VOBBLES]);
} else if (position == INDEX_FRIENDS_VOBBLES) {
onClick(tabs[INDEX_FRIENDS_VOBBLES]);
}
}
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageScrollStateChanged(int i) {
}
};
public void onClick(View view) {
switch (view.getId()) {
case R.id.fl_all_voice_tab_button:
showTab(INDEX_ALL_VOBBLES);
loadVobblesCount(INDEX_ALL_VOBBLES);
if (hasNeedToLoad[INDEX_ALL_VOBBLES])
loadTab(INDEX_ALL_VOBBLES);
break;
case R.id.fl_my_voice_tab_button:
showTab(INDEX_MY_VOBBLES);
loadVobblesCount(INDEX_MY_VOBBLES);
if (hasNeedToLoad[INDEX_MY_VOBBLES])
loadTab(INDEX_MY_VOBBLES);
break;
case R.id.fl_friends_voice_tab_button:
showTab(INDEX_FRIENDS_VOBBLES);
break;
case R.id.iv_reload_btn:
loadTab(mViewPager.getCurrentItem());
break;
case R.id.iv_event_btn:
Intent intent = new Intent(this, EventActivity.class);
startActivity(intent);
break;
}
}
private void showTab(int index) {
mViewPager.setCurrentItem(index, true);
for (int i = 0; i < TAB_COUNT; i++) {
if (i == index) {
tabs[i].setBackgroundColor(Color.argb(0, 1, 1, 1));
} else {
tabs[i].setBackgroundResource(R.drawable.tab_mask);
}
}
}
private void loadTab(int index) {
vobblesCnt[index] = null;
loadVobblesCount(index);
hasNeedToLoad[index] = false;
fragments[index].load();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_feedback:
sendToEmail();
break;
case R.id.action_sign_out:
AccountManager.getInstance().signOut(this);
Intent intent = new Intent(getApplicationContext(), StartActivity.class);
startActivity(intent);
finish();
break;
}
return false;
}
private void sendToEmail() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
String[] tos = { "nexters.vobble@gmail.com" };
intent.putExtra(Intent.EXTRA_EMAIL, tos);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
showShortToast(" .");
}
}
@Override
public void onRemovedVobble() {
hasNeedToLoad[INDEX_MY_VOBBLES] = true;
hasNeedToLoad[INDEX_ALL_VOBBLES] = true;
loadTab(INDEX_MY_VOBBLES);
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.finish);
builder.setMessage(R.string.confirm_finish_app);
builder.setNegativeButton(R.string.no, null);
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
builder.show();
}
@Override
public boolean onPrepareOptionsMenu (Menu menu){
menu.clear();
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onPrepareOptionsMenu(menu);
}
}
|
package com.syncleus.dann.math.counting;
import java.math.BigInteger;
import java.util.*;
public final class Counters
{
private Counters()
{
//this class can not be instantiated
}
public static <O> BigInteger everyCombinationCount(Collection<O> superCollection)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for(int currentSequenceLength = 1; currentSequenceLength <= superCollection.size(); currentSequenceLength++)
combinations.add(fixedLengthCombinationCount(superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthCombinationCount(Collection<O> superCollection, int length)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superCollection.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
Counter generator = new CombinationCounter(superCollection.size(), length);
return generator.getTotal();
}
public static <O> Set<List<O>> everyCombination(List<O> superList)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
final Set<List<O>> combinations = new HashSet<List<O>>();
for(int currentSequenceLength = 1; currentSequenceLength <= superList.size(); currentSequenceLength++)
combinations.addAll(fixedLengthCombinations(superList, currentSequenceLength));
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<Set<O>> everyCombination(Set<O> superSet)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
final Set<Set<O>> combinations = new HashSet<Set<O>>();
for(int currentSequenceLength = 1; currentSequenceLength <= superSet.size(); currentSequenceLength++)
combinations.addAll(fixedLengthCombinations(superSet, currentSequenceLength));
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<List<O>> fixedLengthCombinations(List<O> superList, int length)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superList.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
final Set<List<O>> combinations = new HashSet<List<O>>();
Counter generator = new CombinationCounter(superList.size(), length);
while(generator.hasMore())
{
List<O> combination = new ArrayList<O>();
int[] combinationIndexes = generator.getNext();
for(int combinationIndex:combinationIndexes)
combination.add(superList.get(combinationIndex));
combinations.add(Collections.unmodifiableList(combination));
}
return Collections.unmodifiableSet(combinations);
}
public static <O> Set<Set<O>> fixedLengthCombinations(Set<O> superSet, int length)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superSet.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
List<O> superSetList = new ArrayList<O>(superSet);
final Set<Set<O>> combinations = new HashSet<Set<O>>();
Counter generator = new CombinationCounter(superSet.size(), length);
while(generator.hasMore())
{
Set<O> combination = new HashSet<O>();
int[] combinationIndexes = generator.getNext();
for(int combinationIndex:combinationIndexes)
combination.add(superSetList.get(combinationIndex));
combinations.add(Collections.unmodifiableSet(combination));
}
return Collections.unmodifiableSet(combinations);
}
private static <O> Set<List<O>> sameLengthPermutations(List<O> superList)
{
final Set<List<O>> permutations = new HashSet<List<O>>();
Counter generator = new PermutationCounter(superList.size());
while(generator.hasMore())
{
List<O> permutation = new ArrayList<O>();
int[] permutationIndexes = generator.getNext();
for(int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyPermutationCount(Collection<O> superCollection)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for(int currentSequenceLength = 1; currentSequenceLength <= superCollection.size(); currentSequenceLength++)
combinations.add(fixedLengthPermutationCount(superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthPermutationCount(Collection<O> superCollection, int length)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superCollection.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
Counter permutator = new PermutationCounter(length);
Counter combinator = new CombinationCounter(superCollection.size(), length);
BigInteger combinationCount = combinator.getTotal();
BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyPermutation(List<O> superList)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = everyCombination(superList);
for(List<O> combination : combinations)
permutations.addAll(sameLengthPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyPermutation(Set<O> superSet)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyPermutation(new ArrayList<O>(superSet));
}
public static <O> Set<List<O>> fixedLengthPermutations(List<O> superList, int length)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superList.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = fixedLengthCombinations(superList, length);
for(List<O> combination : combinations)
permutations.addAll(sameLengthPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthPermutations(Set<O> superSet, int length)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superSet.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
return fixedLengthPermutations(new ArrayList<O>(superSet), length);
}
private static <O> Set<List<O>> sameLengthLexicographicPermutations(List<O> superList)
{
final Set<List<O>> permutations = new HashSet<List<O>>();
Counter generator = new LexicographicPermutationCounter(superList.size());
while(generator.hasMore())
{
List<O> permutation = new ArrayList<O>();
int[] permutationIndexes = generator.getNext();
for(int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyLexicographicPermutationCount(Collection<O> superCollection)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for(int currentSequenceLength = 1; currentSequenceLength <= superCollection.size(); currentSequenceLength++)
combinations.add(fixedLengthLexicographicPermutationCount(superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthLexicographicPermutationCount(Collection<O> superCollection, int length)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superCollection.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
Counter permutator = new LexicographicPermutationCounter(length);
Counter combinator = new CombinationCounter(superCollection.size(), length);
BigInteger combinationCount = combinator.getTotal();
BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyLexicographicPermutation(List<O> superList)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = everyCombination(superList);
for(List<O> combination : combinations)
permutations.addAll(sameLengthLexicographicPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyLexicographicPermutation(Set<O> superSet)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyLexicographicPermutation(new ArrayList<O>(superSet));
}
public static <O> Set<List<O>> fixedLengthLexicographicPermutations(List<O> superList, int length)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superList.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = fixedLengthCombinations(superList, length);
for(List<O> combination : combinations)
permutations.addAll(sameLengthLexicographicPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthLexicographicPermutations(Set<O> superSet, int length)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superSet.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
return fixedLengthLexicographicPermutations(new ArrayList<O>(superSet), length);
}
private static <O> Set<List<O>> sameLengthJohnsonTrotterPermutations(List<O> superList)
{
final Set<List<O>> permutations = new HashSet<List<O>>();
Counter generator = new JohnsonTrotterPermutationCounter(superList.size());
while(generator.hasMore())
{
List<O> permutation = new ArrayList<O>();
int[] permutationIndexes = generator.getNext();
for(int permutationIndex : permutationIndexes)
permutation.add(superList.get(permutationIndex));
permutations.add(Collections.unmodifiableList(permutation));
}
return Collections.unmodifiableSet(permutations);
}
public static <O> BigInteger everyJohnsonTrotterPermutationCount(Collection<O> superCollection)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
BigInteger combinations = BigInteger.ZERO;
for(int currentSequenceLength = 1; currentSequenceLength <= superCollection.size(); currentSequenceLength++)
combinations.add(fixedLengthJohnsonTrotterPermutationCount(superCollection, currentSequenceLength));
return combinations;
}
public static <O> BigInteger fixedLengthJohnsonTrotterPermutationCount(Collection<O> superCollection, int length)
{
if(superCollection == null)
throw new IllegalArgumentException("superCollection can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superCollection.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
Counter permutator = new JohnsonTrotterPermutationCounter(length);
Counter combinator = new CombinationCounter(superCollection.size(), length);
BigInteger combinationCount = combinator.getTotal();
BigInteger permutationsPerCount = permutator.getTotal();
return combinationCount.multiply(permutationsPerCount);
}
public static <O> Set<List<O>> everyJohnsonTrotterPermutation(List<O> superList)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = everyCombination(superList);
for(List<O> combination : combinations)
permutations.addAll(sameLengthJohnsonTrotterPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> everyJohnsonTrotterPermutation(Set<O> superSet)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
return everyJohnsonTrotterPermutation(new ArrayList<O>(superSet));
}
public static <O> Set<List<O>> fixedLengthJohnsonTrotterPermutations(List<O> superList, int length)
{
if(superList == null)
throw new IllegalArgumentException("superList can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superList.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
//get every combination then permutate it
Set<List<O>> permutations = new HashSet<List<O>>();
Set<List<O>> combinations = fixedLengthCombinations(superList, length);
for(List<O> combination : combinations)
permutations.addAll(sameLengthJohnsonTrotterPermutations(combination));
return Collections.unmodifiableSet(permutations);
}
public static <O> Set<List<O>> fixedLengthJohnsonTrotterPermutations(Set<O> superSet, int length)
{
if(superSet == null)
throw new IllegalArgumentException("superSet can not be null");
if(length < 0)
throw new IllegalArgumentException("length must be >= 0");
if(length > superSet.size())
throw new IllegalArgumentException("length can not be larger than the collection size");
return fixedLengthJohnsonTrotterPermutations(new ArrayList<O>(superSet), length);
}
}
|
package fr.treeptik.cloudunit.deployments;
import static fr.treeptik.cloudunit.utils.TestUtils.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.Filter;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import fr.treeptik.cloudunit.exception.ServiceException;
import fr.treeptik.cloudunit.initializer.CloudUnitApplicationContext;
import fr.treeptik.cloudunit.model.User;
import fr.treeptik.cloudunit.service.UserService;
@RunWith( SpringJUnit4ClassRunner.class )
@WebAppConfiguration
@ContextConfiguration( classes = { CloudUnitApplicationContext.class, MockServletContext.class } )
@ActiveProfiles( "integration" )
public abstract class AbstractTomcatDeploymentControllerTestIT
{
private static String applicationName;
private final Logger logger = LoggerFactory.getLogger( AbstractTomcatDeploymentControllerTestIT.class );
protected String release;
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Inject
private AuthenticationManager authenticationManager;
@Autowired
private Filter springSecurityFilterChain;
@Inject
private UserService userService;
private MockHttpSession session;
@Value("${suffix.cloudunit.io}")
private String domainSuffix;
@Value("#{systemEnvironment['CU_SUB_DOMAIN']}")
private String subdomain;
private String domain;
@PostConstruct
public void init () {
if (subdomain != null) {
domain = subdomain + domainSuffix;
} else {
domain = domainSuffix;
}
}
@BeforeClass
public static void initEnv()
{
applicationName = "App" + new Random().nextInt(100000);
}
@Before
public void setup()
{
logger.info( "setup" );
this.mockMvc = MockMvcBuilders.webAppContextSetup( context ).addFilters( springSecurityFilterChain ).build();
User user = null;
try {
user = userService.findByLogin( "johndoe" );
}
catch ( ServiceException e ){
logger.error( e.getLocalizedMessage() );
}
Authentication authentication = null;
if (user != null) {
authentication = new UsernamePasswordAuthenticationToken( user.getLogin(), user.getPassword() );
}
Authentication result = authenticationManager.authenticate( authentication );
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication( result );
session = new MockHttpSession();
session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext );
}
@After
public void teardown() throws Exception {
logger.info("teardown");
SecurityContextHolder.clearContext();
session.invalidate();
}
@Test
public void test_deploySimpleApplicationTest()
throws Exception {
createApplication();
logger.info( "Deploy an helloworld application" );
deployArchive(
"helloworld.war",
"https://github.com/Treeptik/CloudUnit/releases/download/1.0/helloworld.war");
String urlToCall = String.format("http://%s-johndoe-admin%s/helloworld",
applicationName.toLowerCase(),
domain);
String content = getUrlContentPage(urlToCall);
assertThat(content, containsString("CloudUnit PaaS"));
deleteApplication();
}
@Test
public void test_deployMysql55_BasedApplicationTest()
throws Exception {
deployApplicationWithModule( "mysql-5-5", "pizzashop-mysql", "Pizzas" );
}
@Test
public void test_deployMysql56_BasedApplicationTest()
throws Exception
{
deployApplicationWithModule( "mysql-5-6", "pizzashop-mysql", "Pizzas" );
}
@Test
public void test_deployMysql57_BasedApplicationTest()
throws Exception
{
deployApplicationWithModule( "mysql-5-7", "pizzashop-mysql", "Pizzas" );
}
@Test
public void test_deployPostGres93BasedApplicationTest()
throws Exception
{
deployApplicationWithModule( "postgresql-9-3", "pizzashop-postgres", "Pizzas" );
}
@Test
public void test_deployPostGres94BasedApplicationTest()
throws Exception
{
deployApplicationWithModule( "postgresql-9-4", "pizzashop-postgres", "Pizzas" );
}
@Test
public void test_deployPostGres95BasedApplicationTest()
throws Exception
{
deployApplicationWithModule( "postgresql-9-5", "pizzashop-postgres", "Pizzas" );
}
private void deployApplicationWithModule(String module, String appName, String keywordInPage)
throws Exception
{
createApplication();
// add the module before deploying war
String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"imageName\":\"" + module + "\"}";
ResultActions resultats =
mockMvc.perform( post( "/module" ).session( session ).contentType( MediaType.APPLICATION_JSON ).content( jsonString ) ).andDo( print() );
resultats.andExpect( status().isOk() );
// deploy the war
logger.info( "Deploy an " + module + " based application" );
resultats =
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/application/" + applicationName + "/deploy")
.file(downloadAndPrepareFileToDeploy(appName + ".war", "https://github.com/Treeptik/CloudUnit/releases/download/1.0/" + appName + ".war"))
.session(session).contentType(MediaType.MULTIPART_FORM_DATA))
.andDo(print());
// test the application content page
resultats.andExpect( status().is2xxSuccessful() );
String urlToCall = "http://" + applicationName.toLowerCase() + "-johndoe-admin" + domain;
String contentPage = getUrlContentPage(urlToCall);
System.out.println(contentPage);
Assert.assertTrue(contentPage.contains(keywordInPage));
// remove the module
resultats =
mockMvc.perform( delete( "/module/" + applicationName + "/" + module).session( session ).contentType( MediaType.APPLICATION_JSON ) ).andDo( print() );
resultats.andExpect( status().isOk() );
deleteApplication();
}
private void createApplication() throws Exception {
logger.info( "Create Tomcat server" );
String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + release + "\"}";
ResultActions resultats =
mockMvc.perform( post( "/application" ).session( session ).contentType( MediaType.APPLICATION_JSON ).content( jsonString ) );
resultats.andExpect( status().isOk() );
}
private ResultActions deployArchive(String nameArchive, String urlArchive) throws Exception {
ResultActions resultats =
mockMvc.perform( MockMvcRequestBuilders.fileUpload( "/application/" + applicationName + "/deploy" )
.file( downloadAndPrepareFileToDeploy(nameArchive,urlArchive) ).
session( session ).contentType( MediaType.MULTIPART_FORM_DATA ) ).andDo( print() );
resultats.andExpect( status().is2xxSuccessful() );
return resultats;
}
private void deleteApplication()
throws Exception
{
logger.info( "Delete application : " + applicationName );
ResultActions resultats =
mockMvc.perform( delete( "/application/" + applicationName ).session( session ).contentType( MediaType.APPLICATION_JSON ) );
resultats.andExpect( status().isOk() );
}
}
|
package com.vinsol.expensetracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.flurry.android.FlurryAgent;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.vinsol.expensetracker.helpers.ConvertCursorToListString;
import com.vinsol.expensetracker.helpers.CustomDatePickerDialog;
import com.vinsol.expensetracker.helpers.DisplayDate;
import com.vinsol.expensetracker.helpers.StringProcessing;
import com.vinsol.expensetracker.models.Entry;
import com.vinsol.expensetracker.utils.Log;
public class GenerateReport extends BaseActivity implements OnClickListener,OnItemSelectedListener{
private Spinner period;
private int mStartYear;
private int mStartMonth;
private int mStartDay;
private int mEndYear;
private int mEndMonth;
private int mEndDay;
private TextView customStartDateTextView;
private TextView customEndDateTextView;
private Calendar endCalendar;
private Calendar startCalendar;
private AsyncTask<Void, Void, Void> exportPDF;
private AsyncTask<Void, Void, Void> exportCSV;
private File fileLocation;
private String dateRange;
private List<Entry> mEntryList;
private final int REQUEST_CODE = 1055;
@Override
protected void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, getString(R.string.flurry_key));
}
@Override
protected void onStop() {
super.onStop();
FlurryAgent.onEndSession(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.generate_report);
((Button)findViewById(R.id.export_button)).setOnClickListener(this);
customStartDateTextView = (TextView)findViewById(R.id.custom_start_date);
customStartDateTextView.setOnClickListener(this);
customEndDateTextView = (TextView)findViewById(R.id.custom_end_date);
customEndDateTextView.setOnClickListener(this);
period = (Spinner) findViewById(R.id.period_spinner);
period.setOnItemSelectedListener(this);
FlurryAgent.onEvent(getString(R.string.generate_report)+" "+"Activity");
//set default end day values
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
calendar.setFirstDayOfWeek(Calendar.MONDAY);
mEndYear = calendar.get(Calendar.YEAR);
mEndMonth = calendar.get(Calendar.MONTH);
mEndDay = calendar.get(Calendar.DAY_OF_MONTH);
mEntryList = new ConvertCursorToListString(GenerateReport.this).getEntryList(true, "");
if(mEntryList.size() == 0) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setCancelable(false)
.setMessage("No Record to Generate Report, Please add some")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.export_button:
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
if(mEntryList.size() <= 5000) {
if(setStartEndDate()) {
Log.d("**************Exporting Range****************");
Log.d("Start Date "+mStartDay+" "+(mStartMonth+1)+" "+mStartYear);
Log.d("End Date "+mEndDay+" "+(mEndMonth+1)+" "+mEndYear);
Log.d("******************************");
switch ((int)((Spinner) findViewById(R.id.type_spinner)).getSelectedItemId()) {
//case if Exporting to PDF
case 0:
exportToPDF();
break;
//case if Exporting to CSV
case 1:
exportToCSV();
break;
default:
break;
}
}
} else {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Too many Records, Please select fewer")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(getString(R.string.ok), (DialogInterface.OnClickListener)null)
.show();
}
} else {
Toast.makeText(this, "sdcard not available", Toast.LENGTH_LONG).show();
}
break;
case R.id.custom_start_date:
new CustomDatePickerDialog(this, mStartDateSetListener, customStartDateTextView).show();
break;
case R.id.custom_end_date:
new CustomDatePickerDialog(this, mEndDateSetListener, customEndDateTextView).show();
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE) {
finish();
}
}
private void exportToCSV() {
exportCSV = new ExportToCSV().execute();
}
private abstract class Export extends AsyncTask<Void, Void, Void> {
protected ProgressDialog progressDialog;
protected Double totalAmount = 0.0;
protected boolean isAmountNotEntered = false;
protected boolean isRecordAdded = false;
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(GenerateReport.this);
progressDialog.setCancelable(false);
progressDialog.setTitle("Exporting Report");
progressDialog.setMessage("Please Wait...");
progressDialog.show();
}
@Override
protected void onPostExecute(Void result) {
progressDialog.cancel();
if(!isRecordAdded) {
fileLocation.delete();
new AlertDialog.Builder(GenerateReport.this)
.setTitle("Error")
.setMessage("No Record within range to generate report")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(getString(R.string.ok), (DialogInterface.OnClickListener)null)
.show();
} else {
final PackageManager packageManager = getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(fileLocation));
List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo.size() > 0) {
Toast.makeText(GenerateReport.this, "Report Exported to - "+getShowLocation(), Toast.LENGTH_LONG).show();
startActivityForResult(intent, REQUEST_CODE);
} else {
new AlertDialog.Builder(GenerateReport.this)
.setMessage(getType()+" Viewer not found, Generated report saved at "+getShowLocation())
.setTitle("Report Generated")
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_info)
.show();
}
}
}
protected void addFlurryEvent(int srNo) {
Map<String, String> recordType = new HashMap<String, String>();
recordType.put("Total Records", +srNo+"");
recordType.put("Type Spinner", getType());
recordType.put("Date Range",dateRange);
recordType.put("Period Spinner", period.getSelectedItem()+"");
FlurryAgent.onEvent(getString(R.string.generate_report), recordType);
}
protected String getShowLocation(){
return fileLocation.toString().replaceAll("/mnt", "");
}
protected abstract String getType();
protected void setFile() {
File dir = new File(Environment.getExternalStorageDirectory()+"/ExpenseTracker");
if(!dir.exists()) {dir.mkdirs();}
fileLocation = new File(dir, getFileName());
}
protected String getFileName() {
return (dateRange+"("+Calendar.getInstance().getTimeInMillis()+")").replaceAll(" ", "");
}
protected boolean isDateValid(Long timeInMillis) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(timeInMillis);
mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
Calendar startCalendar = Calendar.getInstance();
startCalendar.set(mStartYear, mStartMonth, mStartDay, 0, 0, 0);
startCalendar.setFirstDayOfWeek(Calendar.MONDAY);
Calendar endCalendar = Calendar.getInstance();
endCalendar.set(mEndYear, mEndMonth, mEndDay, 0, 0, 0);
endCalendar.setFirstDayOfWeek(Calendar.MONDAY);
if(mStartDay == mCalendar.get(Calendar.DAY_OF_MONTH) && mStartMonth == mCalendar.get(Calendar.MONTH) && mStartYear == mCalendar.get(Calendar.YEAR)) {return true;}
if(mEndDay == mCalendar.get(Calendar.DAY_OF_MONTH) && mEndMonth == mCalendar.get(Calendar.MONTH) && mEndYear == mCalendar.get(Calendar.YEAR)) {return true;}
if(mCalendar.after(startCalendar) && mCalendar.before(endCalendar)) {return true;}
return false;
}
protected String getDescriptionIfNotPresent(String type) {
if(type.equals(getString(R.string.unknown))) {
return getString(R.string.unknown_entry);
} else if(type.equals(getString(R.string.text))) {
return getString(R.string.finished_textentry);
} else if(type.equals(getString(R.string.voice))) {
return getString(R.string.finished_voiceentry);
} else if(type.equals(getString(R.string.camera))) {
return getString(R.string.finished_cameraentry);
}
return "";
}
}
private class ExportToCSV extends Export {
private Writer writer;
@Override
protected Void doInBackground(Void... params) {
setFile();
try {
writer = new BufferedWriter(new FileWriter(fileLocation));
addContent();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected String getFileName() {
return super.getFileName()+".csv";
}
private void addContent() throws IOException {
writer.write("Sr. No.,");
writer.write("Date,");
writer.write("Location,");
writer.write("Description,");
writer.write("Amount\n");
addDataToTable();
}
private void addDataToTable() throws IOException{
int srNo = 0;
for(int i=0 ; i < mEntryList.size() ; i++) {
Entry entry = mEntryList.get(i);
if(!isDateValid(entry.timeInMillis)) {continue;}
// Adding Serial Number
srNo++;
writer.write((srNo)+",");
// Adding date
writer.write(new DisplayDate().getDisplayDateReport(entry.timeInMillis).replaceAll(",", " ")+",");
// Adding location
if(entry.location != null && !entry.location.equals("")) {
writer.write(entry.location.replaceAll(",", " ")+",");
} else {
writer.write(getString(R.string.unknown_location).replaceAll(",", " ")+",");
}
// Adding description
if(entry.description != null && !entry.description.equals("")) {
writer.write(entry.description.replaceAll(",", " ")+",");
} else {
writer.write(getDescriptionIfNotPresent(entry.type).replaceAll(",", " ")+",");
}
// Adding Amount
if(entry.amount != null && !entry.amount.equals("") && !entry.amount.contains("?")) {
totalAmount = totalAmount + Double.parseDouble(entry.amount);
writer.write(new StringProcessing().getStringDoubleDecimal(entry.amount).replaceAll(",", " ")+"\n");
} else {
isAmountNotEntered = true;
writer.write("?"+"\n");
}
isRecordAdded = true;
}
addFlurryEvent(srNo);
addTotalAmountRow();
}
private void addTotalAmountRow() throws IOException{
// Adding Serial Number
writer.write(",");
// Adding date
writer.write(",");
// Adding location
writer.write(",");
// Adding description
writer.write("Total Amount,");
// Adding Amount
if(isAmountNotEntered) {
writer.write(new StringProcessing().getStringDoubleDecimal(totalAmount+"").replaceAll(",", " ")+" ?\n");
} else {
writer.write(new StringProcessing().getStringDoubleDecimal(totalAmount+"").replaceAll(",", " ")+"\n");
}
}
@Override
protected String getType() {
return "CSV";
}
}
private void exportToPDF() {
exportPDF = new ExportPDF().execute();
}
private class ExportPDF extends Export {
private Font catFont;
private Font subFont;
private Font tableHeader;
private Font small;
private PdfWriter writer;
@Override
protected Void doInBackground(Void... params) {
catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.NORMAL);
tableHeader = new Font();
tableHeader.setStyle(Font.BOLD);
small = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
Document document = new Document();
setFile();
try {
writer = PdfWriter.getInstance(document, new FileOutputStream(fileLocation));
writer.setPageEvent(new HeaderAndFooter());
document.open();
addMetaData(document);
addContent(document);
document.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
@Override
protected String getFileName() {
return super.getFileName()+".pdf";
}
private void addTable(Document document) throws DocumentException {
PdfPTable table = new PdfPTable(5);
table.setWidthPercentage(90);
table.getDefaultCell().setPadding(5.0F);
float totalWidth = ((table.getWidthPercentage()*writer.getPageSize().getWidth())/100);
float widths[] = {totalWidth/10,totalWidth/5,totalWidth/5,(3*totalWidth)/10,totalWidth/5};
table.setWidths(widths);
PdfPCell c1 = new PdfPCell(new Phrase("Sr. No.",tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Date",tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Location",tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Description",tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Amount",tableHeader));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.setSplitRows(true);
addDataToTable(table,document);
}
private void addTitle(Document document) throws DocumentException{
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.setAlignment(Element.ALIGN_CENTER);
preface.add(new Paragraph("Expenses Report", catFont));
addEmptyLine(preface, 1);
document.add(preface);
}
private void addContent(Document document) throws DocumentException {
addTitle(document);
addDateRange(document);
addTable(document);
}
private void addDateRange(Document document) throws DocumentException {
Paragraph preface = new Paragraph();
preface.setAlignment(Element.ALIGN_CENTER);
preface.add(new Paragraph(dateRange, subFont));
addEmptyLine(preface, 2);
document.add(preface);
}
// add metadata to the PDF which can be viewed in your Adobe Reader
// under File -> Properties
private void addMetaData(Document document) {
document.addTitle("Expenses Report using Expense Tracker (Vinsol)");
document.addSubject("PDF created using android app \"Expense Tracker (Vinsol)\"");
document.addKeywords("Android, PDF, Vinsol, Expense, Tracker, Expense Tracker");
document.addAuthor("Vinsol");
document.addCreator("Vinsol");
}
private void addDataToTable(PdfPTable table, Document document) throws DocumentException{
int srNo = 0;
for(int i=0 ; i < mEntryList.size() ; i++) {
Entry entry = mEntryList.get(i);
if(!isDateValid(entry.timeInMillis)) {continue;}
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
// Adding Serial Number
srNo++;
table.addCell((srNo)+"");
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
// Adding date
table.addCell(new DisplayDate().getDisplayDateReport(entry.timeInMillis));
// Adding location
if(entry.location != null && !entry.location.equals("")) {
table.addCell(entry.location);
} else {
table.addCell(getString(R.string.unknown_location));
}
// Adding description
if(entry.description != null && !entry.description.equals("")) {
table.addCell(entry.description);
} else {
table.addCell(getDescriptionIfNotPresent(entry.type));
}
// Adding Amount
if(entry.amount != null && !entry.amount.equals("") && !entry.amount.contains("?")) {
totalAmount = totalAmount + Double.parseDouble(entry.amount);
table.addCell(new StringProcessing().getStringDoubleDecimal(entry.amount));
} else {
isAmountNotEntered = true;
table.addCell("?");
}
isRecordAdded = true;
if((i+1) % 500 == 0) {
document.add(table);
table.flushContent();
}
}
addFlurryEvent(srNo);
addTotalAmountRow(table);
document.add(table);
table.flushContent();
}
private void addTotalAmountRow(PdfPTable table) {
// Adding Serial Number
table.addCell("");
// Adding date
table.addCell("");
// Adding location
table.addCell("");
// Adding description
table.addCell("Total Amount");
// Adding Amount
if(isAmountNotEntered) {
table.addCell(new StringProcessing().getStringDoubleDecimal(totalAmount+"")+" ?");
} else {
table.addCell(new StringProcessing().getStringDoubleDecimal(totalAmount+"")+"");
}
}
private void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
public class HeaderAndFooter extends PdfPageEventHelper {
protected PdfPTable footer;
public HeaderAndFooter() {
footer = new PdfPTable(1);
footer.setTotalWidth(220);
footer.getDefaultCell().setBorderWidth(0);
footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
Chunk chunk = new Chunk("Report Generated Using - Expense Tracker (Vinsol)");
chunk.setAction(new PdfAction(PdfAction.FIRSTPAGE));
chunk.setFont(small);
footer.addCell(new Phrase(chunk));
}
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
footer.writeSelectedRows(0, -1,(document.right() - document.left() - 200)+ document.leftMargin(), document.bottom() - 10, cb);
}
}
@Override
protected String getType() {
return "PDF";
}
}
private boolean setStartEndDate() {
endCalendar = Calendar.getInstance();
endCalendar.set(endCalendar.get(Calendar.YEAR), endCalendar.get(Calendar.MONTH), endCalendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
endCalendar.setFirstDayOfWeek(Calendar.MONDAY);
startCalendar = (Calendar) endCalendar.clone();
switch ((int)period.getSelectedItemId()) {
//case if period is 1 Month
case 0:
startCalendar.add(Calendar.MONTH, -1);
setDateParameters(startCalendar,endCalendar);
return true;
//case if period is 1 Quarter
case 1:
startCalendar.add(Calendar.MONTH, -3);
setDateParameters(startCalendar,endCalendar);
return true;
//case if period is Half Year
case 2:
startCalendar.add(Calendar.MONTH, -6);
setDateParameters(startCalendar,endCalendar);
return true;
//case if period is 1 Year
case 3:
startCalendar.add(Calendar.YEAR, -1);
setDateParameters(startCalendar,endCalendar);
return true;
//case if period is Custom
case 4:
return checkStartEndDate(true);
default:
return false;
}
}
private void setDateParameters(Calendar startCalendar, Calendar endCalendar) {
mEndYear = endCalendar.get(Calendar.YEAR);
mEndMonth = endCalendar.get(Calendar.MONTH);
mEndDay = endCalendar.get(Calendar.DAY_OF_MONTH);
mStartYear = startCalendar.get(Calendar.YEAR);
mStartMonth = startCalendar.get(Calendar.MONTH);
mStartDay = startCalendar.get(Calendar.DAY_OF_MONTH);
dateRange = new DisplayDate().getDisplayDateReport(startCalendar)+" - "+new DisplayDate().getDisplayDateReport(endCalendar);
}
@Override
public void onItemSelected(AdapterView<?> adapter, View v, int position,long id) {
if(id == 4) {
((LinearLayout)findViewById(R.id.custom_date_layout)).setVisibility(View.VISIBLE);
} else {
((LinearLayout)findViewById(R.id.custom_date_layout)).setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> adapter) {
// do nothing
}
private CustomDatePickerDialog.OnDateSetListener mStartDateSetListener = new CustomDatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
mStartYear = year;
mStartMonth = monthOfYear;
mStartDay = dayOfMonth;
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(year, monthOfYear, dayOfMonth, 0, 0, 0);
mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
((TextView)findViewById(R.id.custom_start_date)).setText(new DisplayDate(mCalendar).getDisplayDate());
checkStartEndDate(false);
}
};
private CustomDatePickerDialog.OnDateSetListener mEndDateSetListener = new CustomDatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
mEndYear = year;
mEndMonth = monthOfYear;
mEndDay = dayOfMonth;
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(year, monthOfYear, dayOfMonth, 0, 0, 0);
mCalendar.setFirstDayOfWeek(Calendar.MONDAY);
((TextView)findViewById(R.id.custom_end_date)).setText(new DisplayDate(mCalendar).getDisplayDate());
checkStartEndDate(false);
}
};
private boolean checkStartEndDate(boolean isToShowToast) {
if(customEndDateTextView.getText().toString().equals("") || customStartDateTextView.getText().toString().equals("")) {
if(isToShowToast) {
new AlertDialog.Builder(GenerateReport.this)
.setTitle("Error")
.setMessage("Set Start Date and End Date before exporting")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(getString(R.string.ok), (DialogInterface.OnClickListener)null)
.show();
}
return false;
}
if(!isCombinationCorrect()) {
new AlertDialog.Builder(GenerateReport.this)
.setTitle("Error")
.setMessage("End Date must be greater than Start Date")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(getString(R.string.ok), (DialogInterface.OnClickListener)null)
.show();
return false;
}
dateRange = new DisplayDate().getReportDateRange(mStartDay, mStartMonth, mStartYear, mEndDay, mEndMonth, mEndYear);
return true;
}
private boolean isCombinationCorrect() {
if(mStartDay == mEndDay && mStartMonth == mEndMonth && mEndYear == mStartYear) {return true;}
if(mStartYear > mEndYear) {return false;}
if(mStartYear == mEndYear && mStartMonth > mEndMonth) {return false;}
if(mStartYear == mEndYear && mStartMonth == mEndMonth && mStartDay > mEndDay) {return false;}
return true;
}
@Override
protected void onPause() {
if(exportPDF != null && (exportPDF.getStatus().equals(AsyncTask.Status.RUNNING) || exportPDF.getStatus().equals(AsyncTask.Status.PENDING))) {
exportPDF.cancel(true);
Toast.makeText(this, "PDF Report Exporting Cancelled", Toast.LENGTH_LONG).show();
}
if(exportCSV != null && (exportCSV.getStatus().equals(AsyncTask.Status.RUNNING) || exportCSV.getStatus().equals(AsyncTask.Status.PENDING))) {
exportCSV.cancel(true);
Toast.makeText(this, "CSV Report Exporting Cancelled", Toast.LENGTH_LONG).show();
}
super.onPause();
}
}
|
package com.netflix.curator.framework.recipes.locks;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.framework.recipes.BaseClassForTests;
import com.netflix.curator.retry.RetryOneTime;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
@SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter"})
public class TestInterProcessSemaphore extends BaseClassForTests
{
private static class Counter
{
int currentCount = 0;
int maxCount = 0;
}
private static class Stepper
{
private int available = 0;
synchronized void await() throws InterruptedException
{
while ( available == 0 )
{
wait();
}
--available;
}
synchronized void countDown(int qty)
{
available += qty;
notifyAll();
}
}
@Test
public void testReleaseInChunks() throws Exception
{
final int MAX_LEASES = 11;
final int THREADS = 100;
final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
client.start();
try
{
final Stepper latch = new Stepper();
final Random random = new Random();
final Counter counter = new Counter();
ExecutorService service = Executors.newCachedThreadPool();
for ( int i = 0; i < THREADS; ++i )
{
service.submit
(
new Callable<Object>()
{
@Override
public Object call() throws Exception
{
InterProcessSemaphore semaphore = new InterProcessSemaphore(client, "/test", MAX_LEASES);
semaphore.acquire();
try
{
synchronized(counter)
{
++counter.currentCount;
if ( counter.currentCount > counter.maxCount )
{
counter.maxCount = counter.currentCount;
}
}
latch.await();
}
finally
{
synchronized(counter)
{
--counter.currentCount;
}
semaphore.release();
}
return null;
}
}
);
}
int remaining = THREADS;
while ( remaining > 0 )
{
int times = Math.min(random.nextInt(5) + 1, remaining);
latch.countDown(times);
remaining -= times;
Thread.sleep(random.nextInt(100) + 1);
}
Thread.sleep(1000);
synchronized(counter)
{
Assert.assertTrue(counter.currentCount == 0);
Assert.assertTrue(counter.maxCount > 0);
Assert.assertTrue(counter.maxCount <= MAX_LEASES);
System.out.println(counter.maxCount);
}
}
finally
{
client.close();
}
}
@Test
public void testRelease1AtATime() throws Exception
{
final int MAX_LEASES = 10;
final int THREADS = 100;
final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
client.start();
try
{
final CountDownLatch latch = new CountDownLatch(THREADS);
final Random random = new Random();
final Counter counter = new Counter();
ExecutorService service = Executors.newCachedThreadPool();
for ( int i = 0; i < THREADS; ++i )
{
service.submit
(
new Callable<Object>()
{
@Override
public Object call() throws Exception
{
InterProcessSemaphore semaphore = new InterProcessSemaphore(client, "/test", MAX_LEASES);
semaphore.acquire();
try
{
synchronized(counter)
{
++counter.currentCount;
if ( counter.currentCount > counter.maxCount )
{
counter.maxCount = counter.currentCount;
}
}
latch.await();
}
finally
{
synchronized(counter)
{
--counter.currentCount;
}
semaphore.release();
}
return null;
}
}
);
}
for ( int i = 0; i < THREADS; ++i )
{
Thread.sleep(random.nextInt(10) + 1);
latch.countDown();
}
Thread.sleep(1000);
synchronized(counter)
{
Assert.assertTrue(counter.currentCount == 0);
Assert.assertEquals(counter.maxCount, MAX_LEASES);
}
}
finally
{
client.close();
}
}
@Test
public void testSimple() throws Exception
{
final int MAX_LEASES = 3;
CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
client.start();
try
{
List<InterProcessSemaphore> leases = Lists.newArrayList();
for ( int i = 0; i < MAX_LEASES; ++i )
{
InterProcessSemaphore semaphore = new InterProcessSemaphore(client, "/test", MAX_LEASES);
Assert.assertTrue(semaphore.acquire(3, TimeUnit.SECONDS));
leases.add(semaphore);
}
InterProcessSemaphore semaphore = new InterProcessSemaphore(client, "/test", MAX_LEASES);
Assert.assertFalse(semaphore.acquire(1, TimeUnit.SECONDS));
leases.remove(0).release();
Assert.assertNotNull(semaphore.acquire(3, TimeUnit.SECONDS));
}
finally
{
client.close();
}
}
}
|
package org.eclipse.birt.data.engine.olap.query.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IBinding;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IFilterDefinition;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.api.ISortDefinition;
import org.eclipse.birt.data.engine.api.aggregation.IBuildInAggregation;
import org.eclipse.birt.data.engine.api.querydefn.FilterDefinition;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IDimensionDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IEdgeDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IHierarchyDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ILevelDefinition;
import org.eclipse.birt.data.engine.olap.api.query.IMeasureDefinition;
import org.eclipse.birt.data.engine.olap.data.api.DimLevel;
import org.eclipse.birt.data.engine.olap.impl.query.LevelDefiniton;
import org.eclipse.birt.data.engine.olap.impl.query.MeasureDefinition;
import org.eclipse.birt.data.engine.olap.util.ICubeAggrDefn;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionCompiler;
import org.eclipse.birt.data.engine.olap.util.OlapExpressionUtil;
import org.eclipse.birt.data.engine.olap.util.filter.IJSMeasureFilterEvalHelper;
import org.eclipse.birt.data.engine.olap.util.filter.JSMeasureFilterEvalHelper;
import org.mozilla.javascript.Scriptable;
/**
* Utility class
*
*/
class CubeQueryDefinitionUtil
{
/**
* Populate all aggregation member in CubeQueryDefinition. For initial
* implementation: we only consider IMeasureDefintion we will take into
* consider to handle the aggregation definition in binding expression;
*
* @param queryDefn
* @return
* @throws DataException
*/
static CalculatedMember[] getCalculatedMembers(
ICubeQueryDefinition queryDefn, Scriptable scope ) throws DataException
{
List measureList = queryDefn.getMeasures( );
ICubeAggrDefn[] cubeAggrs = OlapExpressionUtil.getAggrDefns( queryDefn.getBindings( ) );
List cubeAggrBindingList = new ArrayList();
for( int i=0; i< cubeAggrs.length; i++ )
{
if( cubeAggrs[i].getAggrName( ) != null )
cubeAggrBindingList.add( cubeAggrs[i] );
}
populateMeasureFromBinding( queryDefn );
populateMeasureFromFilter( queryDefn );
populateMeasureFromSort( queryDefn );
if ( measureList == null )
return new CalculatedMember[0];
CalculatedMember[] calculatedMember = new CalculatedMember[measureList.size( )
+ cubeAggrBindingList.size( )];
int index = 0;
List calculatedMemberList = new ArrayList();
if ( !measureList.isEmpty( ) )
{
List levelList = populateMeasureAggrOns( queryDefn );
Iterator measureIter = measureList.iterator( );
while ( measureIter.hasNext( ) )
{
MeasureDefinition measureDefn = (MeasureDefinition) measureIter.next( );
calculatedMember[index] = new CalculatedMember( measureDefn.getName( ),
measureDefn.getName( ),
levelList,
measureDefn.getAggrFunction( ) == null
? IBuildInAggregation.TOTAL_SUM_FUNC
: measureDefn.getAggrFunction( ),
0 );
calculatedMemberList.add( calculatedMember[index] );
index++;
}
}
if ( !cubeAggrBindingList.isEmpty( ) )
{
int rsID = 1;
for ( int i = 0; i < cubeAggrBindingList.size( ); i++ )
{
int id = getResultSetIndex( calculatedMemberList,
( (ICubeAggrDefn) cubeAggrBindingList.get( i ) ).getAggrLevels( ) );
if ( id == -1 )
{
calculatedMember[index] = new CalculatedMember( (ICubeAggrDefn) cubeAggrBindingList.get( i ),
rsID );
calculatedMemberList.add( calculatedMember[index] );
rsID++;
}
else
{
calculatedMember[index] = new CalculatedMember( (ICubeAggrDefn) cubeAggrBindingList.get( i ),
id );
}
if ( ( (ICubeAggrDefn) cubeAggrBindingList.get( i ) ).getFilter( ) != null )
{
IJSMeasureFilterEvalHelper filterEvalHelper = new JSMeasureFilterEvalHelper( scope,
new FilterDefinition( ( (ICubeAggrDefn) cubeAggrBindingList.get( i ) ).getFilter( ) ) );
calculatedMember[index].setFilterEvalHelper( filterEvalHelper );
}
index++;
}
}
return calculatedMember;
}
/**
* To populate the relational measures from Sort list of queryDefn
*
* @param queryDefn
*/
private static void populateMeasureFromSort( ICubeQueryDefinition queryDefn )
throws DataException
{
for ( int i = 0; i < queryDefn.getSorts( ).size( ); i++ )
{
createRelationalMeasures( queryDefn,
(IBaseExpression) ( (ISortDefinition) queryDefn.getSorts( )
.get( i ) ).getExpression( ) );
}
}
/**
* To populate the relational measures from filter list of queryDefn
*
* @param queryDefn
*/
private static void populateMeasureFromFilter(
ICubeQueryDefinition queryDefn ) throws DataException
{
for ( int i = 0; i < queryDefn.getFilters( ).size( ); i++ )
{
createRelationalMeasures( queryDefn,
(IBaseExpression) ( (IFilterDefinition) queryDefn.getFilters( )
.get( i ) ).getExpression( ) );
}
}
/**
* To populate the relational measures from binding list of queryDefn
*
* @param queryDefn
*/
private static void populateMeasureFromBinding(
ICubeQueryDefinition queryDefn ) throws DataException
{
for ( int i = 0; i < queryDefn.getBindings( ).size( ); i++ )
{
createRelationalMeasures( queryDefn,
(IBaseExpression) ( (IBinding) queryDefn.getBindings( )
.get( i ) ).getExpression( ) );
}
}
/**
* To create all the rational measures for CubeQueryDefinition according to the expression
*
* @param queryDefn, expression
* @return List
* @throws DataException
*/
private static List createRelationalMeasures(
ICubeQueryDefinition queryDefn, IBaseExpression expression )
throws DataException
{
List measures = new ArrayList( );
List exprTextList = getExprTextList( expression );
for ( int i = 0; i < exprTextList.size( ); i++ )
{
String exprText = (String) exprTextList.get( i );
String measureName = OlapExpressionCompiler.getReferencedScriptObject( exprText,
"measure" );
if ( measureName != null && measureName.trim( ).length( ) > 0 )
{
//if current measure list doesn't contain this measure, then add it to the list
List existMeasures = queryDefn.getMeasures( );
boolean exist = false;
for ( int j = 0; j < existMeasures.size( ); j++ )
{
if ( ( (IMeasureDefinition) existMeasures.get( j ) ).getName( )
.equals( measureName ) )
{
exist = true;
break;
}
}
if ( !exist )
{
measures.add( queryDefn.createMeasure( measureName ) );
}
}
}
return measures;
}
/**
* To get all the sub expressions' text list of the given expression
*
* @param queryDefn, expression
* @return List
*/
private static List getExprTextList( IBaseExpression expression )
{
List textList = new ArrayList( );
if ( expression instanceof IScriptExpression )
{
textList.add( ( (IScriptExpression) expression ).getText( ) );
}
else if ( expression instanceof IExpressionCollection )
{
List exprList = (List) ( (IExpressionCollection) expression ).getExpressions( );
for ( int i = 0; i < exprList.size( ); i++ )
{
IBaseExpression baseExpr = (IBaseExpression) exprList.get( i );
textList.addAll( getExprTextList( expression ) );
}
}
else if ( expression instanceof IConditionalExpression )
{
textList.add( ( (IScriptExpression) ( (IConditionalExpression) expression ).getExpression( ) ).getText( ) );
textList.addAll( getExprTextList( ( (IConditionalExpression) expression ).getOperand1( ) ) );
textList.addAll( getExprTextList( ( (IConditionalExpression) expression ).getOperand2( ) ) );
}
return textList;
}
/**
* Populate the list of measure aggregation ons.
* @param queryDefn
* @return
*/
public static List populateMeasureAggrOns( ICubeQueryDefinition queryDefn )
{
List levelList = new ArrayList( );
ILevelDefinition[] rowLevels = getLevelsOnEdge( queryDefn.getEdge( ICubeQueryDefinition.ROW_EDGE ) );
ILevelDefinition[] columnLevels = getLevelsOnEdge( queryDefn.getEdge( ICubeQueryDefinition.COLUMN_EDGE ) );
for ( int i = 0; i < rowLevels.length; i++ )
{
levelList.add( new DimLevel( rowLevels[i] ) );
}
for ( int i = 0; i < columnLevels.length; i++ )
{
levelList.add( new DimLevel( columnLevels[i] ) );
}
return levelList;
}
/**
*
* @param aggrList
* @param levelList
* @return
*/
private static int getResultSetIndex( List aggrList, List levelList )
{
for ( int i = 0; i < aggrList.size( ); i++ )
{
CalculatedMember member = (CalculatedMember) aggrList.get( i );
if ( member.getAggrOnList( ).equals( levelList ) )
{
return member.getRsID( );
}
}
return -1;
}
/**
* get all ILevelDefinition from certain IEdgeDefinition
*
* @param edgeDefn
* @return
*/
static ILevelDefinition[] getLevelsOnEdge( IEdgeDefinition edgeDefn )
{
if ( edgeDefn == null )
return new ILevelDefinition[0];
List levelList = new ArrayList( );
Iterator dimIter = edgeDefn.getDimensions( ).iterator( );
while ( dimIter.hasNext( ) )
{
IDimensionDefinition dimDefn = (IDimensionDefinition) dimIter.next( );
Iterator hierarchyIter = dimDefn.getHierarchy( ).iterator( );
while ( hierarchyIter.hasNext( ) )
{
IHierarchyDefinition hierarchyDefn = (IHierarchyDefinition) hierarchyIter.next( );
levelList.addAll( hierarchyDefn.getLevels( ) );
}
}
ILevelDefinition[] levelDefn = new LevelDefiniton[levelList.size( )];
for ( int i = 0; i < levelList.size( ); i++ )
{
levelDefn[i] = (ILevelDefinition) levelList.get( i );
}
return levelDefn;
}
/**
* Get related level's info for all measure.
*
* @param queryDefn
* @return
* @throws DataException
*/
public static Map getRelationWithMeasure( ICubeQueryDefinition queryDefn ) throws DataException
{
Map measureRelationMap = new HashMap( );
List rowLevelList = new ArrayList( );
List columnLevelList = new ArrayList( );
if ( queryDefn.getEdge( ICubeQueryDefinition.COLUMN_EDGE ) != null )
{
ILevelDefinition[] levels = getLevelsOnEdge( queryDefn.getEdge( ICubeQueryDefinition.COLUMN_EDGE ) );
for ( int i = 0; i < levels.length; i++ )
{
columnLevelList.add( new DimLevel( levels[i] ) );
}
}
if ( queryDefn.getEdge( ICubeQueryDefinition.ROW_EDGE ) != null )
{
ILevelDefinition[] levels = getLevelsOnEdge( queryDefn.getEdge( ICubeQueryDefinition.ROW_EDGE ) );
for ( int i = 0; i < levels.length; i++ )
{
rowLevelList.add( new DimLevel( levels[i] ) );
}
}
if ( queryDefn.getMeasures( ) != null
&& !queryDefn.getMeasures( ).isEmpty( ) )
{
Iterator measureIter = queryDefn.getMeasures( ).iterator( );
while ( measureIter.hasNext( ) )
{
IMeasureDefinition measure = (MeasureDefinition) measureIter.next( );
measureRelationMap.put( measure.getName( ),
new RelationShip( rowLevelList, columnLevelList ) );
}
}
ICubeAggrDefn[] cubeAggrs = OlapExpressionUtil.getAggrDefns( queryDefn.getBindings( ) );
if ( cubeAggrs != null && cubeAggrs.length > 0 )
{
for ( int i = 0; i < cubeAggrs.length; i++ )
{
if ( cubeAggrs[i].getAggrName( ) == null )
continue;
List aggrOns = cubeAggrs[i].getAggrLevels( );
List usedLevelOnRow = new ArrayList( );
List usedLevelOnColumn = new ArrayList( );
for ( int j = 0; j < aggrOns.size( ); j++ )
{
if ( rowLevelList.contains( aggrOns.get( j ) ) )
usedLevelOnRow.add( aggrOns.get( j ) );
else if ( columnLevelList.contains( aggrOns.get( j ) ) )
usedLevelOnColumn.add( aggrOns.get( j ) );
}
measureRelationMap.put( cubeAggrs[i].getName( ),
new RelationShip( usedLevelOnRow, usedLevelOnColumn ) );
}
}
return measureRelationMap;
}
}
|
package com.linkedin.datahub.graphql.types.dataplatform;
import com.linkedin.common.urn.DataPlatformUrn;
import com.linkedin.datahub.graphql.QueryContext;
import com.linkedin.datahub.graphql.types.EntityType;
import com.linkedin.datahub.graphql.generated.DataPlatform;
import com.linkedin.datahub.graphql.types.mappers.DataPlatformMapper;
import com.linkedin.dataplatform.client.DataPlatforms;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DataPlatformType implements EntityType<DataPlatform> {
private final DataPlatforms _dataPlatformsClient;
private Map<String, DataPlatform> _urnToPlatform;
public DataPlatformType(final DataPlatforms dataPlatformsClient) {
_dataPlatformsClient = dataPlatformsClient;
}
@Override
public Class<DataPlatform> objectClass() {
return DataPlatform.class;
}
@Override
public List<DataPlatform> batchLoad(final List<String> urns, final QueryContext context) {
try {
if (_urnToPlatform == null) {
_urnToPlatform = _dataPlatformsClient.getAllPlatforms().stream()
.map(DataPlatformMapper::map)
.collect(Collectors.toMap(DataPlatform::getUrn, platform -> platform));
}
return urns.stream()
.map(key -> _urnToPlatform.containsKey(key) ? _urnToPlatform.get(key) : getUnknownDataPlatform(key))
.collect(Collectors.toList());
} catch (Exception e) {
throw new RuntimeException("Failed to batch load DataPlatforms", e);
}
}
@Override
public com.linkedin.datahub.graphql.generated.EntityType type() {
return com.linkedin.datahub.graphql.generated.EntityType.DATA_PLATFORM;
}
private DataPlatform getUnknownDataPlatform(final String urnStr) {
try {
final com.linkedin.dataPlatforms.DataPlatform platform = new com.linkedin.dataPlatforms.DataPlatform()
.setName(DataPlatformUrn.createFromString(urnStr).getPlatformNameEntity());
return DataPlatformMapper.map(platform);
} catch (URISyntaxException e) {
throw new RuntimeException(String.format("Invalid DataPlatformUrn %s provided", urnStr), e);
}
}
}
|
package org.hisp.dhis.dxf2.events.event;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectReader;
import com.google.common.collect.ImmutableMap;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.api.util.DateUtils;
import org.hisp.dhis.common.IdSchemes;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.QueryFilter;
import org.hisp.dhis.common.QueryItem;
import org.hisp.dhis.common.QueryOperator;
import org.hisp.dhis.common.ValueType;
import org.hisp.dhis.commons.util.SqlHelper;
import org.hisp.dhis.commons.util.TextUtils;
import org.hisp.dhis.dxf2.events.enrollment.EnrollmentStatus;
import org.hisp.dhis.dxf2.events.report.EventRow;
import org.hisp.dhis.dxf2.events.trackedentity.Attribute;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.eventdatavalue.EventDataValue;
import org.hisp.dhis.hibernate.jsonb.type.JsonEventDataValueSetBinaryType;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStatus;
import org.hisp.dhis.program.ProgramType;
import org.hisp.dhis.query.Order;
import org.hisp.dhis.security.acl.AccessStringHelper;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.util.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hisp.dhis.api.util.DateUtils.getDateAfterAddition;
import static org.hisp.dhis.api.util.DateUtils.getMediumDateString;
import static org.hisp.dhis.common.IdentifiableObjectUtils.getIdentifiers;
import static org.hisp.dhis.commons.util.TextUtils.*;
import static org.hisp.dhis.dxf2.events.event.AbstractEventService.STATIC_EVENT_COLUMNS;
import static org.hisp.dhis.dxf2.events.event.EventSearchParams.*;
/**
* @author Morten Olav Hansen <mortenoh@gmail.com>
*/
public class JdbcEventStore
implements EventStore
{
private static final Log log = LogFactory.getLog( JdbcEventStore.class );
private static final Map<String, String> QUERY_PARAM_COL_MAP = ImmutableMap.<String, String>builder()
.put( "event", "psi_uid" ).put( "program", "p_uid" ).put( "programStage", "ps_uid" )
.put( "enrollment", "pi_uid" ).put( "enrollmentStatus", "pi_status" ).put( "orgUnit", "ou_uid" )
.put( "orgUnitName", "ou_name" ).put( "trackedEntityInstance", "tei_uid" )
.put( "eventDate", "psi_executiondate" ).put( "followup", "pi_followup" ).put( "status", "psi_status" )
.put( "dueDate", "psi_duedate" ).put( "storedBy", "psi_storedby" ).put( "created", "psi_created" )
.put( "lastUpdated", "psi_lastupdated" ).put( "completedBy", "psi_completedby" )
.put( "attributeOptionCombo", "psi_aoc" ).put( "completedDate", "psi_completeddate" )
.put( "deleted", "psi_deleted" ).build();
// Dependencies
@Autowired
private StatementBuilder statementBuilder;
@Resource( name = "readOnlyJdbcTemplate" )
private JdbcTemplate jdbcTemplate;
@Autowired
private CurrentUserService currentUserService;
@Autowired
private IdentifiableObjectManager manager;
//Cannot use DefaultRenderService mapper. Does not work properly - DHIS2-6102
private static final ObjectReader eventDataValueJsonReader =
JsonEventDataValueSetBinaryType.MAPPER.readerFor( new TypeReference<Map<String, EventDataValue>>() {} );
// EventStore implementation
@SuppressWarnings( "unchecked" )
@Override
public List<Event> getEvents( EventSearchParams params, List<OrganisationUnit> organisationUnits, Map<String, Set<String>> psdesWithSkipSyncTrue )
{
User user = currentUserService.getCurrentUser();
boolean isSuperUser = isSuper( user );
if ( !isSuperUser )
{
params.setAccessiblePrograms( manager.getDataReadAll( Program.class )
.stream().map( Program::getUid ).collect( Collectors.toSet() ) );
params.setAccessibleProgramStages( manager.getDataReadAll( ProgramStage.class )
.stream().map( ProgramStage::getUid ).collect( Collectors.toSet() ) );
}
List<Event> events = new ArrayList<>();
String sql = buildSql( params, organisationUnits, user );
SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );
log.debug( "Event query SQL: " + sql );
Event event = new Event();
event.setEvent( "not_valid" );
Set<String> notes = new HashSet<>();
IdSchemes idSchemes = ObjectUtils.firstNonNull( params.getIdSchemes(), new IdSchemes() );
while ( rowSet.next() )
{
if ( rowSet.getString( "psi_uid" ) == null || (params.getCategoryOptionCombo() == null && !isSuperUser && !userHasAccess( rowSet )) )
{
continue;
}
if ( event.getUid() == null || !event.getUid().equals( rowSet.getString( "psi_uid" ) ) )
{
event = new Event();
event.setUid( rowSet.getString( "psi_uid" ) );
event.setEvent( IdSchemes.getValue( rowSet.getString( "psi_uid" ), rowSet.getString( "psi_code" ),
idSchemes.getProgramStageInstanceIdScheme() ) );
event.setTrackedEntityInstance( rowSet.getString( "tei_uid" ) );
event.setStatus( EventStatus.valueOf( rowSet.getString( "psi_status" ) ) );
event.setProgram( IdSchemes.getValue( rowSet.getString( "p_uid" ), rowSet.getString( "p_code" ),
idSchemes.getProgramIdScheme() ) );
event.setProgramStage( IdSchemes.getValue( rowSet.getString( "ps_uid" ), rowSet.getString( "ps_code" ),
idSchemes.getProgramStageIdScheme() ) );
event.setOrgUnit( IdSchemes.getValue( rowSet.getString( "ou_uid" ), rowSet.getString( "ou_code" ),
idSchemes.getOrgUnitIdScheme() ) );
event.setDeleted( rowSet.getBoolean( "psi_deleted" ) );
ProgramType programType = ProgramType.fromValue( rowSet.getString( "p_type" ) );
if ( programType != ProgramType.WITHOUT_REGISTRATION )
{
event.setEnrollment( rowSet.getString( "pi_uid" ) );
event.setEnrollmentStatus( EnrollmentStatus
.fromProgramStatus( ProgramStatus.valueOf( rowSet.getString( "pi_status" ) ) ) );
event.setFollowup( rowSet.getBoolean( "pi_followup" ) );
}
if ( params.getCategoryOptionCombo() == null && !isSuper( user ) )
{
event.setOptionSize( rowSet.getInt( "option_size" ) );
}
event.setAttributeOptionCombo( rowSet.getString( "coc_categoryoptioncombouid" ) );
event.setAttributeCategoryOptions( rowSet.getString( "deco_uid" ) );
event.setTrackedEntityInstance( rowSet.getString( "tei_uid" ) );
event.setStoredBy( rowSet.getString( "psi_storedby" ) );
event.setOrgUnitName( rowSet.getString( "ou_name" ) );
event.setDueDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_duedate" ) ) );
event.setEventDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_executiondate" ) ) );
event.setCreated( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_created" ) ) );
event.setLastUpdated( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_lastupdated" ) ) );
event.setCompletedBy( rowSet.getString( "psi_completedby" ) );
event.setCompletedDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_completeddate" ) ) );
if ( rowSet.getObject( "psi_geometry" ) != null )
{
try
{
Geometry geom = new WKTReader().read( rowSet.getString( "psi_geometry" ) );
event.setGeometry( geom );
event.setCoordinate( new Coordinate( geom.getCoordinate().x, geom.getCoordinate().y ) );
}
catch ( ParseException e )
{
log.error( "Unable to read geometry for event '" + event.getUid() + "': ", e );
}
}
events.add( event );
}
else
{
String attributeCategoryCombination = event.getAttributeCategoryOptions();
String currentAttributeCategoryCombination = rowSet.getString( "deco_uid" );
if ( !attributeCategoryCombination.contains( currentAttributeCategoryCombination ) )
{
event.setAttributeCategoryOptions(
attributeCategoryCombination + ";" + currentAttributeCategoryCombination );
}
}
if ( !org.springframework.util.StringUtils.isEmpty( rowSet.getString( "psi_eventdatavalues" ) ) )
{
Set<EventDataValue> eventDataValues = convertEventDataValueJsonIntoSet( rowSet.getString( "psi_eventdatavalues" ) );
for( EventDataValue dv : eventDataValues )
{
DataValue dataValue = convertEventDataValueIntoDtoDataValue( dv );
if ( params.isSynchronizationQuery() )
{
if (psdesWithSkipSyncTrue.containsKey( rowSet.getString( "ps_uid" ) ) &&
psdesWithSkipSyncTrue.get( rowSet.getString( "ps_uid" ) ).contains( dv.getDataElement() ) )
{
dataValue.setSkipSynchronization( true );
}
else
{
dataValue.setSkipSynchronization( false );
}
}
event.getDataValues().add( dataValue );
}
}
if ( rowSet.getString( "psinote_value" ) != null && !notes.contains( rowSet.getString( "psinote_id" ) ) )
{
Note note = new Note();
note.setNote( rowSet.getString( "psinote_uid" ) );
note.setValue( rowSet.getString( "psinote_value" ) );
note.setStoredDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psinote_storeddate" ) ) );
note.setStoredBy( rowSet.getString( "psinote_storedby" ) );
event.getNotes().add( note );
notes.add( rowSet.getString( "psinote_id" ) );
}
}
if ( params.getCategoryOptionCombo() == null && !isSuper( user ) )
{
return events.stream().filter( ev -> ev.getAttributeCategoryOptions() != null && splitToArray( ev.getAttributeCategoryOptions(), TextUtils.SEMICOLON ).size() == ev.getOptionSize() ).collect( Collectors.toList() );
}
return events;
}
@Override
public List<Map<String, String>> getEventsGrid( EventSearchParams params, List<OrganisationUnit> organisationUnits )
{
String sql = buildGridSql( params, organisationUnits );
SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );
log.debug( "Event query SQL: " + sql );
List<Map<String, String>> list = new ArrayList<>();
while ( rowSet.next() )
{
final Map<String, String> map = new HashMap<>();
for ( String col : STATIC_EVENT_COLUMNS )
{
map.put( col, rowSet.getString( col ) );
}
for ( QueryItem item : params.getDataElements() )
{
map.put( item.getItemId(), rowSet.getString( item.getItemId() ) );
}
list.add( map );
}
return list;
}
@SuppressWarnings( "unchecked" )
@Override
public List<EventRow> getEventRows( EventSearchParams params, List<OrganisationUnit> organisationUnits )
{
User user = currentUserService.getCurrentUser();
boolean isSuperUser = isSuper( user );
if ( !isSuperUser )
{
params.setAccessiblePrograms( manager.getDataReadAll( Program.class )
.stream().map( Program::getUid ).collect( Collectors.toSet() ) );
params.setAccessibleProgramStages( manager.getDataReadAll( ProgramStage.class )
.stream().map( ProgramStage::getUid ).collect( Collectors.toSet() ) );
}
List<EventRow> eventRows = new ArrayList<>();
String sql = buildSql( params, organisationUnits, user );
SqlRowSet rowSet = jdbcTemplate.queryForRowSet( sql );
log.debug( "Event query SQL: " + sql );
EventRow eventRow = new EventRow();
eventRow.setEvent( "not_valid" );
Set<String> notes = new HashSet<>();
IdSchemes idSchemes = ObjectUtils.firstNonNull( params.getIdSchemes(), new IdSchemes() );
while ( rowSet.next() )
{
if ( rowSet.getString( "psi_uid" ) == null || ( params.getCategoryOptionCombo() == null && !isSuperUser && !userHasAccess( rowSet ) ) )
{
continue;
}
if ( eventRow.getUid() == null || !eventRow.getUid().equals( rowSet.getString( "psi_uid" ) ) )
{
eventRow = new EventRow();
eventRow.setUid( rowSet.getString( "psi_uid" ) );
eventRow.setEvent( IdSchemes.getValue( rowSet.getString( "psi_uid" ), rowSet.getString( "psi_code" ), idSchemes.getProgramStageInstanceIdScheme() ) );
eventRow.setTrackedEntityInstance( rowSet.getString( "tei_uid" ) );
eventRow.setTrackedEntityInstanceOrgUnit( rowSet.getString( "tei_ou" ) );
eventRow.setTrackedEntityInstanceOrgUnitName( rowSet.getString( "tei_ou_name" ) );
eventRow.setTrackedEntityInstanceCreated( rowSet.getString( "tei_created" ) );
eventRow.setTrackedEntityInstanceInactive( rowSet.getBoolean( "tei_inactive" ) );
eventRow.setDeleted( rowSet.getBoolean( "psi_deleted" ) );
eventRow.setProgram( IdSchemes.getValue( rowSet.getString( "p_uid" ), rowSet.getString( "p_code" ),
idSchemes.getProgramIdScheme() ) );
eventRow.setProgramStage( IdSchemes.getValue( rowSet.getString( "ps_uid" ),
rowSet.getString( "ps_code" ), idSchemes.getProgramStageIdScheme() ) );
eventRow.setOrgUnit( IdSchemes.getValue( rowSet.getString( "ou_uid" ), rowSet.getString( "ou_code" ),
idSchemes.getOrgUnitIdScheme() ) );
ProgramType programType = ProgramType.fromValue( rowSet.getString( "p_type" ) );
if ( programType == ProgramType.WITHOUT_REGISTRATION )
{
eventRow.setEnrollment( rowSet.getString( "pi_uid" ) );
eventRow.setFollowup( rowSet.getBoolean( "pi_followup" ) );
}
eventRow.setTrackedEntityInstance( rowSet.getString( "tei_uid" ) );
eventRow.setOrgUnitName( rowSet.getString( "ou_name" ) );
eventRow.setDueDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_duedate" ) ) );
eventRow.setEventDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psi_executiondate" ) ) );
eventRows.add( eventRow );
}
if ( rowSet.getString( "pav_value" ) != null && rowSet.getString( "ta_uid" ) != null )
{
String valueType = rowSet.getString( "ta_valuetype" );
Attribute attribute = new Attribute();
attribute.setCreated( DateUtils.getIso8601NoTz( rowSet.getDate( "pav_created" ) ) );
attribute.setLastUpdated( DateUtils.getIso8601NoTz( rowSet.getDate( "pav_lastupdated" ) ) );
attribute.setValue( rowSet.getString( "pav_value" ) );
attribute.setDisplayName( rowSet.getString( "ta_name" ) );
attribute.setValueType( valueType != null ? ValueType.valueOf( valueType.toUpperCase() ) : null );
attribute.setAttribute( rowSet.getString( "ta_uid" ) );
eventRow.getAttributes().add( attribute );
}
if ( !org.springframework.util.StringUtils.isEmpty( rowSet.getString( "psi_eventdatavalues" ) ) )
{
Set<EventDataValue> eventDataValues = convertEventDataValueJsonIntoSet( rowSet.getString( "psi_eventdatavalues" ) );
for( EventDataValue dv : eventDataValues )
{
DataValue dataValue = convertEventDataValueIntoDtoDataValue( dv );
eventRow.getDataValues().add( dataValue );
}
}
if ( rowSet.getString( "psinote_value" ) != null && !notes.contains( rowSet.getString( "psinote_id" ) ) )
{
Note note = new Note();
note.setNote( rowSet.getString( "psinote_uid" ) );
note.setValue( rowSet.getString( "psinote_value" ) );
note.setStoredDate( DateUtils.getIso8601NoTz( rowSet.getDate( "psinote_storeddate" ) ) );
note.setStoredBy( rowSet.getString( "psinote_storedby" ) );
eventRow.getNotes().add( note );
notes.add( rowSet.getString( "psinote_id" ) );
}
}
return eventRows;
}
@Override
public int getEventCount( EventSearchParams params, List<OrganisationUnit> organisationUnits )
{
User user = currentUserService.getCurrentUser();
boolean isSuperUser = isSuper( user );
if ( !isSuperUser )
{
params.setAccessiblePrograms( manager.getDataReadAll( Program.class )
.stream().map( Program::getUid ).collect( Collectors.toSet() ) );
params.setAccessibleProgramStages( manager.getDataReadAll( ProgramStage.class )
.stream().map( ProgramStage::getUid ).collect( Collectors.toSet() ) );
}
String sql;
if ( params.hasFilters() )
{
sql = buildGridSql( params, organisationUnits );
}
else
{
sql = getEventSelectQuery( params, organisationUnits, user );
}
sql = sql.replaceFirst( "select .*? from", "select count(*) from" );
sql = sql.replaceFirst( "order .*? (desc|asc)", "" );
sql = sql.replaceFirst( "limit \\d+ offset \\d+", "" );
log.debug( "Event query count SQL: " + sql );
return jdbcTemplate.queryForObject( sql, Integer.class );
}
private DataValue convertEventDataValueIntoDtoDataValue( EventDataValue eventDataValue ) {
DataValue dataValue = new DataValue();
dataValue.setCreated( DateUtils.getIso8601NoTz( eventDataValue.getCreated() ) );
dataValue.setLastUpdated( DateUtils.getIso8601NoTz( eventDataValue.getLastUpdated() ) );
dataValue.setValue( eventDataValue.getValue() );
dataValue.setProvidedElsewhere( eventDataValue.getProvidedElsewhere() );
dataValue.setDataElement( eventDataValue.getDataElement() );
dataValue.setStoredBy( eventDataValue.getStoredBy() );
return dataValue;
}
private String buildGridSql( EventSearchParams params, List<OrganisationUnit> organisationUnits )
{
SqlHelper hlp = new SqlHelper();
// Select clause
String sql = "select psi.uid as " + EVENT_ID + ", " + "psi.created as " + EVENT_CREATED_ID + ", "
+ "psi.lastupdated as " + EVENT_LAST_UPDATED_ID + ", " + "psi.storedby as " + EVENT_STORED_BY_ID + ", "
+ "psi.completedby as " + EVENT_COMPLETED_BY_ID + ", " + "psi.completeddate as " + EVENT_COMPLETED_DATE_ID
+ ", " + "psi.duedate as " + EVENT_DUE_DATE_ID + ", " + "psi.executiondate as " + EVENT_EXECUTION_DATE_ID
+ ", " + "ou.uid as " + EVENT_ORG_UNIT_ID + ", " + "ou.name as " + EVENT_ORG_UNIT_NAME + ", "
+ "psi.status as " + EVENT_STATUS_ID + ", "
+ "pi.uid as " + EVENT_ENROLLMENT_ID + ", "
+ "ps.uid as " + EVENT_PROGRAM_STAGE_ID + ", " + "p.uid as "
+ EVENT_PROGRAM_ID + ", " + "coc.uid as " + EVENT_ATTRIBUTE_OPTION_COMBO_ID + ", " + "psi.deleted as " + EVENT_DELETED + ", "
+ "psi.geometry as " + EVENT_GEOMETRY + ", ";
for ( QueryItem item : params.getDataElementsAndFilters() )
{
final String col = item.getItemId();
final String dataValueValueSql = "psi.eventdatavalues #>> '{" + col + ", value}'";
String queryCol = item.isNumeric() ? "CAST( " + dataValueValueSql + " AS NUMERIC ) " : dataValueValueSql;
queryCol += " as " + col + ", ";
sql += queryCol;
}
sql = removeLastComma( sql ) + " ";
// From and where clause
sql += getFromWhereClause( params, hlp, organisationUnits );
// Order clause
sql += getGridOrderQuery( params );
// Paging clause
sql += getEventPagingQuery( params );
return sql;
}
/**
* Query is based on three sub queries on event, data value and comment,
* which are joined using program stage instance id. The purpose of the
* separate queries is to be able to page properly on events.
*/
private String buildSql( EventSearchParams params, List<OrganisationUnit> organisationUnits, User user )
{
String sql = "select * from (";
sql += getEventSelectQuery( params, organisationUnits, user );
sql += getOrderQuery( params );
sql += getEventPagingQuery( params );
sql += ") as event left join (";
if ( params.isIncludeAttributes() )
{
sql += getAttributeValueQuery();
sql += ") as att on event.tei_id=att.pav_id left join (";
}
sql += getCommentQuery();
sql += ") as cm on event.psi_id=cm.psic_id ";
sql += getOrderQuery( params );
return sql;
}
private String getEventSelectQuery( EventSearchParams params, List<OrganisationUnit> organisationUnits, User user )
{
List<Integer> orgUnitIds = getIdentifiers( organisationUnits );
SqlHelper hlp = new SqlHelper();
String sql = "select psi.programstageinstanceid as psi_id, psi.uid as psi_uid, psi.code as psi_code, psi.status as psi_status, psi.executiondate as psi_executiondate, "
+ "psi.eventdatavalues as psi_eventdatavalues, psi.duedate as psi_duedate, psi.completedby as psi_completedby, psi.storedby as psi_storedby, "
+ "psi.created as psi_created, psi.lastupdated as psi_lastupdated, psi.completeddate as psi_completeddate, psi.deleted as psi_deleted, "
+ "ST_AsText( psi.geometry ) as psi_geometry, "
+ "coc.categoryoptioncomboid AS coc_categoryoptioncomboid, coc.code AS coc_categoryoptioncombocode, coc.uid AS coc_categoryoptioncombouid, cocco.categoryoptionid AS cocco_categoryoptionid, deco.uid AS deco_uid, ";
if ( (params.getCategoryOptionCombo() == null || params.getCategoryOptionCombo().isDefault()) && !isSuper( user ) )
{
sql += "deco.publicaccess AS deco_publicaccess, decoa.uga_access AS uga_access, decoa.ua_access AS ua_access, cocount.option_size AS option_size, ";
}
for ( QueryItem item : params.getDataElementsAndFilters() )
{
final String col = item.getItemId();
final String dataValueValueSql = "psi.eventdatavalues #>> '{" + col + ", value}'";
String queryCol = item.isNumeric() ? " CAST( " + dataValueValueSql + " AS NUMERIC)" : "lower(" + dataValueValueSql + ")";
queryCol += " as " + col + ", ";
sql += queryCol;
}
sql += "pi.uid as pi_uid, pi.status as pi_status, pi.followup as pi_followup, p.uid as p_uid, p.code as p_code, "
+ "psi.duedate as psi_duedate, psi.completedby as psi_completedby, psi.storedby as psi_storedby, "
+ "coc.categoryoptioncomboid AS coc_categoryoptioncomboid, coc.code AS coc_categoryoptioncombocode, coc.uid AS coc_categoryoptioncombouid, cocco.categoryoptionid AS cocco_categoryoptionid, "
+ "deco.uid AS deco_uid, pi.uid as pi_uid, pi.status as pi_status, pi.followup as pi_followup, p.uid as p_uid, p.code as p_code, "
+ "p.type as p_type, ps.uid as ps_uid, ps.code as ps_code, "
+ "ou.uid as ou_uid, ou.code as ou_code, ou.name as ou_name, "
+ "tei.trackedentityinstanceid as tei_id, tei.uid as tei_uid, teiou.uid as tei_ou, teiou.name as tei_ou_name, tei.created as tei_created, tei.inactive as tei_inactive "
+ "from programstageinstance psi "
+ "inner join programinstance pi on pi.programinstanceid=psi.programinstanceid "
+ "inner join program p on p.programid=pi.programid "
+ "inner join programstage ps on ps.programstageid=psi.programstageid "
+ "inner join categoryoptioncombo coc on coc.categoryoptioncomboid=psi.attributeoptioncomboid "
+ "inner join categoryoptioncombos_categoryoptions cocco on psi.attributeoptioncomboid=cocco.categoryoptioncomboid "
+ "inner join dataelementcategoryoption deco on cocco.categoryoptionid=deco.categoryoptionid "
+ "left join trackedentityinstance tei on tei.trackedentityinstanceid=pi.trackedentityinstanceid "
+ "left join organisationunit ou on (psi.organisationunitid=ou.organisationunitid) "
+ "left join organisationunit teiou on (tei.organisationunitid=teiou.organisationunitid) ";
Set<String> joinedColumns = new HashSet<>();
String eventDataValuesWhereSql = "";
for ( QueryItem item : params.getDataElementsAndFilters() )
{
final String col = item.getItemId();
final String optCol = item.getItemId() + "opt";
final String dataValueValueSql = "psi.eventdatavalues #>> '{" + col + ", value}'";
if ( !joinedColumns.contains( col ) )
{
if ( item.hasOptionSet() && item.hasFilter() )
{
sql += "inner join optionvalue as " + optCol + " on lower(" + optCol + ".code) = " +
"lower(" + dataValueValueSql + ") and " + optCol + ".optionsetid = " + item.getOptionSet().getId() + " ";
}
joinedColumns.add( col );
}
if ( item.hasFilter() )
{
for ( QueryFilter filter : item.getFilters() )
{
final String encodedFilter = statementBuilder.encode( filter.getFilter(), false );
final String queryCol = item.isNumeric() ? " CAST( " + dataValueValueSql + " AS NUMERIC)" : "lower( " + dataValueValueSql + " )";
if ( !item.hasOptionSet() )
{
//Previously, this filter was used in JOIN to trackedentitydatavalue table. Now, the table was removed and I am moving
// it into WHERE part of the query. But assembling it here
if ( !eventDataValuesWhereSql.isEmpty() )
{
eventDataValuesWhereSql += " and ";
}
eventDataValuesWhereSql += " " + queryCol + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( StringUtils.isNumeric( encodedFilter ) ? encodedFilter :
filter.getSqlFilter( encodedFilter ) ) + " ";
}
else if ( QueryOperator.IN.getValue().equalsIgnoreCase( filter.getSqlOperator() ) )
{
sql += "and " + queryCol + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( StringUtils.isNumeric( encodedFilter ) ? encodedFilter :
filter.getSqlFilter( encodedFilter ) ) + " ";
}
else
{
sql += "and lower(" + optCol + ".name)" + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( StringUtils.isNumeric( encodedFilter ) ? encodedFilter :
filter.getSqlFilter( encodedFilter ) ) + " ";
}
}
}
}
if ( (params.getCategoryOptionCombo() == null || params.getCategoryOptionCombo().isDefault()) && !isSuper( user ) )
{
sql += getCategoryOptionSharingForUser( user );
}
if ( !eventDataValuesWhereSql.isEmpty() )
{
sql += hlp.whereAnd() + eventDataValuesWhereSql + " ";
}
if ( params.getTrackedEntityInstance() != null )
{
sql += hlp.whereAnd() + " tei.trackedentityinstanceid=" + params.getTrackedEntityInstance().getId() + " ";
}
if ( params.getProgram() != null )
{
sql += hlp.whereAnd() + " p.programid = " + params.getProgram().getId() + " ";
}
if ( params.getProgramStage() != null )
{
sql += hlp.whereAnd() + " ps.programstageid = " + params.getProgramStage().getId() + " ";
}
if ( params.getProgramStatus() != null )
{
sql += hlp.whereAnd() + " pi.status = '" + params.getProgramStatus() + "' ";
}
if ( params.getFollowUp() != null )
{
sql += hlp.whereAnd() + " pi.followup is " + (params.getFollowUp() ? "true" : "false") + " ";
}
if ( params.getLastUpdatedStartDate() != null )
{
sql += hlp.whereAnd() + " psi.lastupdated >= '"
+ DateUtils.getLongDateString( params.getLastUpdatedStartDate() ) + "' ";
}
if ( params.getLastUpdatedEndDate() != null )
{
Date dateAfterEndDate = getDateAfterAddition( params.getLastUpdatedEndDate(), 1 );
sql += hlp.whereAnd() + " psi.lastupdated < '" + DateUtils.getLongDateString( dateAfterEndDate ) + "' ";
}
if ( params.getCategoryOptionCombo() != null )
{
sql += hlp.whereAnd() + " psi.attributeoptioncomboid = " + params.getCategoryOptionCombo().getId() + " ";
}
if ( orgUnitIds != null && !orgUnitIds.isEmpty() )
{
sql += hlp.whereAnd() + " psi.organisationunitid in (" + getCommaDelimitedString( orgUnitIds ) + ") ";
}
if ( params.getStartDate() != null )
{
sql += hlp.whereAnd() + " (psi.executiondate >= '" + getMediumDateString( params.getStartDate() ) + "' "
+ "or (psi.executiondate is null and psi.duedate >= '" + getMediumDateString( params.getStartDate() )
+ "')) ";
}
if ( params.getEndDate() != null )
{
Date dateAfterEndDate = getDateAfterAddition( params.getEndDate(), 1 );
sql += hlp.whereAnd() + " (psi.executiondate < '" + getMediumDateString( dateAfterEndDate ) + "' "
+ "or (psi.executiondate is null and psi.duedate < '" + getMediumDateString( dateAfterEndDate )
+ "')) ";
}
if ( params.getProgramType() != null )
{
sql += hlp.whereAnd() + " p.type = '" + params.getProgramType() + "' ";
}
if ( params.getEventStatus() != null )
{
if ( params.getEventStatus() == EventStatus.VISITED )
{
sql += hlp.whereAnd() + " psi.status = '" + EventStatus.ACTIVE.name()
+ "' and psi.executiondate is not null ";
}
else if ( params.getEventStatus() == EventStatus.OVERDUE )
{
sql += hlp.whereAnd() + " date(now()) > date(psi.duedate) and psi.status = '"
+ EventStatus.SCHEDULE.name() + "' ";
}
else
{
sql += hlp.whereAnd() + " psi.status = '" + params.getEventStatus().name() + "' ";
}
}
if ( params.getEvents() != null && !params.getEvents().isEmpty() && !params.hasFilters() )
{
sql += hlp.whereAnd() + " (psi.uid in (" + getQuotedCommaDelimitedString( params.getEvents() ) + ")) ";
}
if ( !params.isIncludeDeleted() )
{
sql += hlp.whereAnd() + " psi.deleted is false ";
}
if ( params.hasSecurityFilter() )
{
sql += hlp.whereAnd() + " (p.uid in (" + getQuotedCommaDelimitedString( params.getAccessiblePrograms() ) + ")) ";
sql += hlp.whereAnd() + " (ps.uid in (" + getQuotedCommaDelimitedString( params.getAccessibleProgramStages() ) + ")) ";
}
if ( params.isSynchronizationQuery() )
{
sql += hlp.whereAnd() + " psi.lastupdated > psi.lastsynchronized ";
}
return sql;
}
/**
* From, join and where clause. For dataElement params, restriction is set
* in inner join. For query params, restriction is set in where clause.
*/
private String getFromWhereClause( EventSearchParams params, SqlHelper hlp,
List<OrganisationUnit> organisationUnits )
{
String sql = "from programstageinstance psi "
+ "inner join programinstance pi on pi.programinstanceid = psi.programinstanceid "
+ "inner join program p on p.programid = pi.programid "
+ "inner join programstage ps on ps.programstageid = psi.programstageid "
+ "inner join categoryoptioncombo coc on coc.categoryoptioncomboid = psi.attributeoptioncomboid "
+ "inner join organisationunit ou on psi.organisationunitid = ou.organisationunitid ";
Set<String> joinedColumns = new HashSet<>();
String eventDataValuesWhereSql = "";
for ( QueryItem item : params.getDataElementsAndFilters() )
{
final String col = item.getItemId();
final String optCol = item.getItemId() + "opt";
final String dataValueValueSql = "psi.eventdatavalues #>> '{" + col + ", value}'";
if ( !joinedColumns.contains( col ) )
{
if ( item.hasOptionSet() && item.hasFilter() )
{
sql += "inner join optionvalue as " + optCol + " on lower(" + optCol + ".code) = " +
"lower(" + dataValueValueSql + ") and " + optCol + ".optionsetid = " + item.getOptionSet().getId() + " ";
}
joinedColumns.add( col );
}
if ( item.hasFilter() )
{
for ( QueryFilter filter : item.getFilters() )
{
final String encodedFilter = statementBuilder.encode( filter.getFilter(), false );
final String queryCol = item.isNumeric() ? " CAST( " + dataValueValueSql + " AS NUMERIC)" : "lower(" + dataValueValueSql + ")";
if ( !item.hasOptionSet() )
{
//Previously, this filter was used in JOIN to trackedentitydatavalue table. Now, the table was removed and I am moving
// it into WHERE part of the query. But assembling it here
if ( !eventDataValuesWhereSql.isEmpty() )
{
eventDataValuesWhereSql += " and ";
}
eventDataValuesWhereSql += " " + queryCol + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( filter.getSqlFilter( encodedFilter ) ) + " ";
}
else if ( QueryOperator.IN.getValue().equalsIgnoreCase( filter.getSqlOperator() ) )
{
sql += "and " + queryCol + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( filter.getSqlFilter( encodedFilter ) ) + " ";
}
else
{
sql += "and lower( " + optCol + ".name)" + " " + filter.getSqlOperator() + " "
+ StringUtils.lowerCase( filter.getSqlFilter( encodedFilter ) ) + " ";
}
}
}
}
if ( !eventDataValuesWhereSql.isEmpty() )
{
sql += hlp.whereAnd() + eventDataValuesWhereSql + " ";
}
if ( organisationUnits != null && !organisationUnits.isEmpty() )
{
sql += hlp.whereAnd() + " psi.organisationunitid in ("
+ getCommaDelimitedString( getIdentifiers( organisationUnits ) ) + ") ";
}
if ( params.getProgramStage() != null )
{
sql += hlp.whereAnd() + " ps.programstageid = " + params.getProgramStage().getId() + " ";
}
if ( params.getCategoryOptionCombo() != null )
{
sql += hlp.whereAnd() + " psi.attributeoptioncomboid = " + params.getCategoryOptionCombo().getId() + " ";
}
if ( params.getStartDate() != null )
{
sql += hlp.whereAnd() + " (psi.executiondate >= '" + getMediumDateString( params.getStartDate() ) + "' "
+ "or (psi.executiondate is null and psi.duedate >= '" + getMediumDateString( params.getStartDate() )
+ "')) ";
}
if ( params.getEndDate() != null )
{
sql += hlp.whereAnd() + " (psi.executiondate <= '" + getMediumDateString( params.getEndDate() ) + "' "
+ "or (psi.executiondate is null and psi.duedate <= '" + getMediumDateString( params.getEndDate() )
+ "')) ";
}
if ( params.getLastUpdatedStartDate() != null )
{
sql += hlp.whereAnd() + " psi.lastupdated >= '"
+ DateUtils.getLongDateString( params.getLastUpdatedStartDate() ) + "' ";
}
if ( params.getLastUpdatedEndDate() != null )
{
sql += hlp.whereAnd() + " psi.lastupdated <= '"
+ DateUtils.getLongDateString( params.getLastUpdatedEndDate() ) + "' ";
}
if ( params.getDueDateStart() != null )
{
sql += hlp.whereAnd() + " psi.duedate is not null and psi.duedate >= '"
+ DateUtils.getLongDateString( params.getDueDateStart() ) + "' ";
}
if ( params.getDueDateEnd() != null )
{
sql += hlp.whereAnd() + " psi.duedate is not null and psi.duedate <= '"
+ DateUtils.getLongDateString( params.getDueDateEnd() ) + "' ";
}
if ( !params.isIncludeDeleted() )
{
sql += hlp.whereAnd() + " psi.deleted is false ";
}
if ( params.getEventStatus() != null )
{
if ( params.getEventStatus() == EventStatus.VISITED )
{
sql += hlp.whereAnd() + " psi.status = '" + EventStatus.ACTIVE.name()
+ "' and psi.executiondate is not null ";
}
else if ( params.getEventStatus() == EventStatus.OVERDUE )
{
sql += hlp.whereAnd() + " date(now()) > date(psi.duedate) and psi.status = '"
+ EventStatus.SCHEDULE.name() + "' ";
}
else
{
sql += hlp.whereAnd() + " psi.status = '" + params.getEventStatus().name() + "' ";
}
}
if ( params.getEvents() != null && !params.getEvents().isEmpty() && !params.hasFilters() )
{
sql += hlp.whereAnd() + " (psi.uid in (" + getQuotedCommaDelimitedString( params.getEvents() ) + ")) ";
}
return sql;
}
private String getCategoryOptionSharingForUser( User user )
{
List<Integer> userGroupIds = getIdentifiers( user.getGroups() );
String sql = " left join ( ";
sql += "select categoryoptioncomboid, count(categoryoptioncomboid) as option_size from categoryoptioncombos_categoryoptions group by categoryoptioncomboid) "
+ "as cocount on coc.categoryoptioncomboid = cocount.categoryoptioncomboid "
+ "left join ("
+ "select deco.categoryoptionid as deco_id, deco.uid as deco_uid, deco.publicaccess AS deco_publicaccess, "
+ "couga.usergroupaccessid as uga_id, coua.useraccessid as ua_id, uga.access as uga_access, uga.usergroupid AS usrgrp_id, "
+ "ua.access as ua_access, ua.userid as usr_id from dataelementcategoryoption deco "
+ "left join dataelementcategoryoptionusergroupaccesses couga on deco.categoryoptionid = couga.categoryoptionid "
+ "left join dataelementcategoryoptionuseraccesses coua on deco.categoryoptionid = coua.categoryoptionid "
+ "left join usergroupaccess uga on couga.usergroupaccessid = uga.usergroupaccessid "
+ "left join useraccess ua on coua.useraccessid = ua.useraccessid " + " where ua.userid="
+ user.getId();
if ( userGroupIds != null && !userGroupIds.isEmpty() )
{
sql += " or uga.usergroupid in (" + getCommaDelimitedString( userGroupIds ) + ") ";
}
sql += " ) as decoa on cocco.categoryoptionid = decoa.deco_id ";
return sql;
}
private String getEventPagingQuery( EventSearchParams params )
{
String sql = " ";
if ( params.isPaging() )
{
sql += "limit " + params.getPageSizeWithDefault() + " offset " + params.getOffset() + " ";
}
return sql;
}
private String getCommentQuery()
{
String sql = "select psic.programstageinstanceid as psic_id, psinote.trackedentitycommentid as psinote_id, psinote.commenttext as psinote_value, "
+ "psinote.created as psinote_storeddate, psinote.creator as psinote_storedby, psinote.uid as psinote_uid "
+ "from programstageinstancecomments psic "
+ "inner join trackedentitycomment psinote on psic.trackedentitycommentid=psinote.trackedentitycommentid ";
return sql;
}
private String getGridOrderQuery( EventSearchParams params )
{
if ( params.getGridOrders() != null && params.getDataElements() != null && !params.getDataElements().isEmpty()
&& STATIC_EVENT_COLUMNS != null && !STATIC_EVENT_COLUMNS.isEmpty() )
{
List<String> orderFields = new ArrayList<>();
for ( String order : params.getGridOrders() )
{
String[] prop = order.split( ":" );
if ( prop.length == 2 && (prop[1].equals( "desc" ) || prop[1].equals( "asc" )) )
{
if ( STATIC_EVENT_COLUMNS.contains( prop[0] ) )
{
orderFields.add( prop[0] + " " + prop[1] );
}
else
{
Set<QueryItem> queryItems = params.getDataElements();
for ( QueryItem item : queryItems )
{
if ( prop[0].equals( item.getItemId() ) )
{
orderFields.add( prop[0] + " " + prop[1] );
break;
}
}
}
}
}
if ( !orderFields.isEmpty() )
{
return "order by " + StringUtils.join( orderFields, ',' );
}
}
return "order by lastUpdated desc ";
}
private String getOrderQuery( EventSearchParams params )
{
ArrayList<String> orderFields = new ArrayList<String>();
if ( params.getGridOrders() != null )
{
for ( String order : params.getGridOrders() )
{
String[] prop = order.split( ":" );
if ( prop.length == 2 && (prop[1].equals( "desc" ) || prop[1].equals( "asc" )) )
{
Set<QueryItem> items = params.getDataElements();
for ( QueryItem item : items )
{
if ( prop[0].equals( item.getItemId() ) )
{
orderFields.add( prop[0] + " " + prop[1] );
break;
}
}
}
}
}
if ( params.getOrders() != null )
{
for ( Order order : params.getOrders() )
{
if ( QUERY_PARAM_COL_MAP.containsKey( order.getProperty().getName() ) )
{
String orderText = QUERY_PARAM_COL_MAP.get( order.getProperty().getName() );
orderText += order.isAscending() ? " asc" : " desc";
orderFields.add( orderText );
}
}
}
if ( !orderFields.isEmpty() )
{
return "order by " + StringUtils.join( orderFields, ',' ) + " ";
}
else
{
return "order by psi_lastupdated desc ";
}
}
private String getAttributeValueQuery()
{
String sql = "select pav.trackedentityinstanceid as pav_id, pav.created as pav_created, pav.lastupdated as pav_lastupdated, "
+ "pav.value as pav_value, ta.uid as ta_uid, ta.name as ta_name, ta.valuetype as ta_valuetype "
+ "from trackedentityattributevalue pav "
+ "inner join trackedentityattribute ta on pav.trackedentityattributeid=ta.trackedentityattributeid ";
return sql;
}
private boolean isSuper( User user )
{
return user == null || user.isSuper();
}
private boolean userHasAccess( SqlRowSet rowSet )
{
if ( rowSet.wasNull() )
{
return true;
}
if ( rowSet.getString( "uga_access" ) == null && rowSet.getString( "ua_access" ) == null && rowSet.getString( "deco_publicaccess" ) == null )
{
return false;
}
return AccessStringHelper.isEnabled( rowSet.getString( "deco_publicaccess" ), AccessStringHelper.Permission.DATA_READ );
}
private Set<EventDataValue> convertEventDataValueJsonIntoSet( String jsonString )
{
try
{
Map<String, EventDataValue> data = eventDataValueJsonReader.readValue( jsonString );
return JsonEventDataValueSetBinaryType.convertEventDataValuesMapIntoSet( data );
}
catch ( IOException e )
{
log.error( "Parsing EventDataValues json string failed. String value: " + jsonString );
throw new IllegalArgumentException( e );
}
}
}
|
package uk.gov.nationalarchives.droid.command.filter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import uk.gov.nationalarchives.droid.core.interfaces.filter.CriterionOperator;
import uk.gov.nationalarchives.droid.core.interfaces.filter.FilterCriterion;
/**
* @author boreilly
* Parses a command line filter condition, throwing exceptions for various invalid filter patterns.
* Uses Java code without relying on Antlr (see AntlrDqlParser) which may have dependency issues with particular
* Java versions and environments.
*/
//CHECKSTYLE:OFF Too complex and some don't agree with all the suggestions. But layout issues all OK!
public class SimpleDqlFilterParser implements DqlFilterParser {
private static final String INVALID_ARGUMENT_COUNT = "The filter condition \"%s\" is invalid, since it has only %d arguments - at least 3 are required (are you missing an operator, or a space?)";
private static final String INVALID_ARGUMENT_COUNT_FOR_STRING_OPERATOR = "The filter condition \"%s\" is invalid, since it has %d arguments. String based filter conditions must supply one string value enclosed in single quotes for the final argument";
private static final String INVALID_USE_OF_NOT = "The filter condition \"%s\" is invalid. The \"not\" operator can only be used with string operators \"starts\", \"ends\" and \"contains\"";
private static final String MISSING_SINGLE_QUOTES = "The filter condition \"%s\" is invalid. Queries with \"starts\", \"ends\" and \"contains\" must be followed by a value enclosed in single quotes after the operator.";
private static final String INVALID_COMPARISON_FILTER = "The filter condition \"%s\" is invalid. Filters using a comparison operator must supply a single integer numeric operand, or (for the \"=\" operator only) a string surrounded by single quotes. Dates must use the format yyyy-mm-dd, e.g. 2010-01-23 for 23rd Jan 2010";
private static final String SINGLE_QUOTE = "'";
private static final int MIMIMUM_FILTER_COMPONENTS = 3;
private static final int VALUES_START_INDEX_WITH_NOT_OPERATOR = 3;
private static final int VALUES_START_INDEX_SANS_NOT_OPERATOR = 2;
@Override
public FilterCriterion parse(String dql) {
try {
Pattern p = Pattern.compile("(?<!(\\\\'|\"|'[a-zA-Z0-9\"]{1,1000})) (?!(\\\\|\").*)");
String[] filterComponents = dql.split(p.pattern());
String dqlOperator = null;
String value = null;
int valuesStartIndex = 0;
FilterCriterion criterion = null;
//We must always have at least 3 components i.e. field, operator and one operand
//E.g. "file_name contains 'london'"
if (filterComponents.length < MIMIMUM_FILTER_COMPONENTS) {
throw new DqlParseException(String.format(INVALID_ARGUMENT_COUNT , dql, filterComponents.length));
}
String dqlField = filterComponents[0];
// Currently the operator is always a single token, unless preceded by "not"
//e.g. in "file_name not contains 'london'", the operator is "not contains"
boolean operatorIsTwoPart = filterComponents[1].toLowerCase().equals("not") ? true : false;
if (operatorIsTwoPart) {
String[] operators = Arrays.copyOfRange(filterComponents, 1, VALUES_START_INDEX_WITH_NOT_OPERATOR);
dqlOperator = operators[0] + " " + operators[1];
//dqlOperator = String.join(" ", operators); -- Only works with Java 8 - we have to support 7!!
valuesStartIndex = VALUES_START_INDEX_WITH_NOT_OPERATOR;
} else {
dqlOperator = filterComponents[1];
valuesStartIndex = VALUES_START_INDEX_SANS_NOT_OPERATOR;
}
if (isStringOperator(dqlOperator)) {
// Check that we have the right number of arguments, with "starts", "ends" or "contains", we should
// only have a single value, So there should be 3 arguments, or 4 if preceded by "not"
if ((operatorIsTwoPart && filterComponents.length != (MIMIMUM_FILTER_COMPONENTS + 1)) || ((!operatorIsTwoPart) && filterComponents.length != MIMIMUM_FILTER_COMPONENTS)) {
throw new DqlParseException(String.format(INVALID_ARGUMENT_COUNT_FOR_STRING_OPERATOR, dql , filterComponents.length));
}
// We have the correct number of arguments - check that the value is enclosed in quotes - this is required
// with the string operators i.e. "starts", "ends" or "contains"
value = filterComponents[valuesStartIndex];
if (!(value.startsWith(SINGLE_QUOTE) && value.endsWith(SINGLE_QUOTE))) {
throw new DqlParseException(String.format(MISSING_SINGLE_QUOTES, dql));
}
criterion = DqlCriterionFactory.newCriterion(dqlField, dqlOperator, fromDqlString(value));
} else {
if (operatorIsTwoPart) {
// The "not" prefix is only valid with string operators - so throw an exception if we reach here.
throw new DqlParseException(String.format(INVALID_USE_OF_NOT, dql));
}
if (isComparisonOperator(dqlOperator)) {
// With a comparison operator, we should have only one operand which should be either
// a long integer or a string which can be converted to a Boolean
if (filterComponents.length != MIMIMUM_FILTER_COMPONENTS) {
throw new DqlParseException(String.format(INVALID_COMPARISON_FILTER, dql));
}
value = filterComponents[valuesStartIndex];
if (!isLongInteger(value) && !isBoolean(value) && !isDateValue(value) && (!(isQuotedString(value) && isEqualsOperator(dqlOperator)))) {
throw new DqlParseException(String.format(INVALID_COMPARISON_FILTER, dql));
}
criterion = DqlCriterionFactory.newCriterion(dqlField, dqlOperator, fromDqlString(value));
} else {
//We're using the "any" or "none" operator with a list of values, which may or may not be quoted...
Collection<String> dqlValues = new ArrayList<String>();
for (int i = valuesStartIndex; i < filterComponents.length; i++) {
// Strip the single quotes when using "any" or "none" (previously this would fail if
// quotes were used as these are not handled in the Criterion code).
dqlValues.add(fromDqlString(filterComponents[i]));
}
criterion = DqlCriterionFactory.newCriterion(dqlField, dqlOperator, dqlValues);
}
}
return criterion;
} catch (IllegalArgumentException e) {
throw new DqlParseException(e);
} catch (DqlParseException e) {
throw (DqlParseException) e;
}
}
private static String fromDqlString(String dqlString) {
return StringUtils.strip(dqlString, SINGLE_QUOTE).replace("\\'", SINGLE_QUOTE);
}
private static boolean isStringOperator(String operator) {
CriterionOperator criterionOperator = DqlCriterionMapper.forOperator(operator);
if (criterionOperator == CriterionOperator.STARTS_WITH
|| criterionOperator == CriterionOperator.NOT_STARTS_WITH
|| criterionOperator == CriterionOperator.ENDS_WITH
|| criterionOperator == CriterionOperator.NOT_ENDS_WITH
|| criterionOperator == CriterionOperator.CONTAINS
|| criterionOperator == CriterionOperator.NOT_CONTAINS) {
return true;
}
return false;
}
private static boolean isComparisonOperator(String operator) {
CriterionOperator criterionOperator = DqlCriterionMapper.forOperator(operator);
if (criterionOperator == CriterionOperator.EQ
|| criterionOperator == CriterionOperator.GT
|| criterionOperator == CriterionOperator.GTE
|| criterionOperator == CriterionOperator.LT
|| criterionOperator == CriterionOperator.LTE
|| criterionOperator == CriterionOperator.NE
) {
return true;
}
return false;
}
private static boolean isEqualsOperator(String operator) {
CriterionOperator criterionOperator = DqlCriterionMapper.forOperator(operator);
return criterionOperator == CriterionOperator.EQ;
}
private static boolean isQuotedString(String value) {
return value.startsWith(SINGLE_QUOTE) && value.endsWith(SINGLE_QUOTE);
}
private static boolean isLongInteger(String str) {
try {
Long.parseLong(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
private static boolean isDateValue(String value) {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(value);
} catch (ParseException e) {
}
return (date != null);
}
private static boolean isBoolean(String value) {
try {
if (fromDqlString(value).equalsIgnoreCase("true") || fromDqlString(value).equalsIgnoreCase("false")) {
return true;
} else {
return false;
}
} catch (NumberFormatException nfe) {
return false;
}
}
}
|
package crazypants.enderio.conduits.conduit.liquid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import com.enderio.core.common.fluid.IFluidWrapper.ITankInfoWrapper;
import com.enderio.core.common.util.RoundRobinIterator;
import crazypants.enderio.base.Log;
import crazypants.enderio.base.filter.fluid.IFluidFilter;
import crazypants.enderio.conduits.conduit.AbstractConduitNetwork;
import crazypants.enderio.conduits.config.ConduitConfig;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidTankProperties;
public class EnderLiquidConduitNetwork extends AbstractConduitNetwork<ILiquidConduit, EnderLiquidConduit> {
List<NetworkTank> tanks = new ArrayList<NetworkTank>();
Map<NetworkTankKey, NetworkTank> tankMap = new HashMap<NetworkTankKey, NetworkTank>();
Map<NetworkTank, RoundRobinIterator<NetworkTank>> iterators;
boolean filling;
public EnderLiquidConduitNetwork() {
super(EnderLiquidConduit.class, ILiquidConduit.class);
}
public void connectionChanged(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
NetworkTankKey key = new NetworkTankKey(con, conDir);
NetworkTank tank = new NetworkTank(con, conDir);
tanks.remove(tank); // remove old tank, NB: =/hash is only calced on location and dir
tanks.add(tank);
tankMap.remove(key);
tankMap.put(key, tank);
tanks.sort((left, right) -> right.priority - left.priority);
}
public boolean extractFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
final NetworkTank tank = getTank(con, conDir);
if (!tank.isValid()) {
return false;
}
final int fullLimit = (int) (ConduitConfig.fluid_tier3_extractRate.get() * getExtractSpeedMultiplier(tank));
if (tank.supportsMultipleTanks) {
int limit = fullLimit;
for (ITankInfoWrapper tankInfoWrapper : tank.externalTank.getTankInfoWrappers()) {
final IFluidTankProperties tankProperties = tankInfoWrapper.getIFluidTankProperties();
if (tankProperties.canDrain()) {
limit -= tryTransfer(con, conDir, tank, tankProperties.getContents(), limit);
if (limit <= 0) {
return true;
}
}
}
return limit < fullLimit;
} else {
return tryTransfer(con, conDir, tank, tank.externalTank.getAvailableFluid(), fullLimit) > 0;
}
}
private int tryTransfer(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, @Nonnull NetworkTank from, FluidStack toDrain, int limit) {
if (toDrain == null || toDrain.amount <= 0 || !matchedFilter(toDrain, con, conDir, true)) {
return 0;
}
// (1) Our limit
FluidStack draining = toDrain.copy();
draining.amount = Math.min(draining.amount, limit);
// (2) Simulate putting all of that into targets
int amountAccepted = fillFrom(from, draining.copy(), false);
if (amountAccepted <= 0) {
return 0;
}
draining.amount = Math.min(draining.amount, amountAccepted);
// (3) Drain what we could insert from the source
FluidStack drained = from.externalTank.drain(draining);
if (drained == null || drained.amount <= 0) {
return 0;
}
int amountFilled = fillFrom(from, drained.copy(), true);
if (amountFilled > drained.amount) {
Log.warn(
"EnderLiquidConduit at " + con.getBundle().getLocation() + " in dimension " + con.getBundle().getBundleworld().provider.getDimensionType().getId()
+ ": Inserted fluid volume (" + amountFilled + "mB) is more than we tried to insert (" + drained.amount + "mB).");
} else if (amountFilled < drained.amount) {
Log.warn(
"EnderLiquidConduit at " + con.getBundle().getLocation() + " in dimension " + con.getBundle().getBundleworld().provider.getDimensionType().getId()
+ ": Inserted fluid volume (" + amountFilled + "mB) is less than when we asked the target how much to insert (" + drained.amount
+ "mB). This means that one of the blocks connected to this conduit line has a bug.");
FluidStack toPutBack = toDrain.copy();
toPutBack.amount = drained.amount - amountFilled;
int putBack = from.externalTank.fill(toPutBack.copy());
if (putBack < toPutBack.amount) {
Log.warn("EnderLiquidConduit at " + con.getBundle().getLocation() + " in dimension "
+ con.getBundle().getBundleworld().provider.getDimensionType().getId() + ": In addition, putting back " + toPutBack.amount
+ "mB into the source tank failed, leading to " + (toPutBack.amount - putBack) + "mB being voided.");
}
}
return amountFilled;
}
@Nonnull
private NetworkTank getTank(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
return tankMap.get(new NetworkTankKey(con, conDir));
}
// this is called when a neighbor block pushes fluid into the conduit
public int fillFrom(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, FluidStack resource, boolean doFill) {
return fillFrom(getTank(con, conDir), resource, doFill);
}
public int fillFrom(@Nonnull NetworkTank tank, FluidStack resource, boolean doFill) {
if (filling || resource == null) {
return 0;
}
/**
* Some targets change dependent on other targets (e.g. 2 conduit connections to the same tank). Simulation will differ from execution in this case. To
* prevent simulation from reporting higher amounts that execution can really move, we stop simulation after the first target. This limits throughput, but
* prevents errors (including voiding fluids and backspill into blocks with separate input and output tanks). It also makes sure that higher priority
* targets must be full before lower priority tanks get filled.
*/
boolean firstOnly = !doFill;
RoundRobinIterator<NetworkTank> iteratorForTank = getIteratorForTank(tank);
if (!doFill) {
iteratorForTank = iteratorForTank.copy();
}
try {
filling = true;
if (!matchedFilter(resource, tank.con, tank.conDir, true)) {
return 0;
}
resource = resource.copy();
resource.amount = Math.min(resource.amount, (int) (ConduitConfig.fluid_tier3_maxIO.get() * getExtractSpeedMultiplier(tank)));
int filled = 0;
int remaining = resource.amount;
for (NetworkTank target : iteratorForTank) {
if ((!target.equals(tank) || tank.selfFeed) && target.acceptsOuput && target.isValid() && target.inputColor == tank.outputColor
&& matchedFilter(resource, target.con, target.conDir, false)) {
int vol = doFill ? target.externalTank.fill(resource.copy()) : target.externalTank.offer(resource.copy());
remaining -= vol;
filled += vol;
if (remaining <= 0 || (firstOnly && filled > 0)) {
return filled;
}
resource.amount = remaining;
}
}
return filled;
} finally {
if (!tank.roundRobin) {
iteratorForTank.reset();
}
filling = false;
}
}
private float getExtractSpeedMultiplier(NetworkTank tank) {
return tank.con.getExtractSpeedMultiplier(tank.conDir);
}
private boolean matchedFilter(FluidStack drained, @Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir, boolean isInput) {
if (drained == null) {
return false;
}
IFluidFilter filter = con.getFilter(conDir, isInput);
if (filter == null || filter.isEmpty()) {
return true;
}
return filter.matchesFilter(drained);
}
private RoundRobinIterator<NetworkTank> getIteratorForTank(@Nonnull NetworkTank tank) {
if (iterators == null) {
iterators = new HashMap<NetworkTank, RoundRobinIterator<NetworkTank>>();
}
RoundRobinIterator<NetworkTank> res = iterators.get(tank);
if (res == null) {
res = new RoundRobinIterator<NetworkTank>(tanks);
iterators.put(tank, res);
}
return res;
}
public IFluidTankProperties[] getTankProperties(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
List<IFluidTankProperties> res = new ArrayList<IFluidTankProperties>(tanks.size());
NetworkTank tank = getTank(con, conDir);
for (NetworkTank target : tanks) {
if (!target.equals(tank) && target.isValid()) {
for (ITankInfoWrapper info : target.externalTank.getTankInfoWrappers()) {
res.add(info.getIFluidTankProperties());
}
}
}
return res.toArray(new IFluidTankProperties[res.size()]);
}
static class NetworkTankKey {
EnumFacing conDir;
BlockPos conduitLoc;
public NetworkTankKey(@Nonnull EnderLiquidConduit con, @Nonnull EnumFacing conDir) {
this(con.getBundle().getLocation(), conDir);
}
public NetworkTankKey(@Nonnull BlockPos conduitLoc, @Nonnull EnumFacing conDir) {
this.conDir = conDir;
this.conduitLoc = conduitLoc;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((conDir == null) ? 0 : conDir.hashCode());
result = prime * result + ((conduitLoc == null) ? 0 : conduitLoc.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NetworkTankKey other = (NetworkTankKey) obj;
if (conDir != other.conDir) {
return false;
}
if (conduitLoc == null) {
if (other.conduitLoc != null) {
return false;
}
} else if (!conduitLoc.equals(other.conduitLoc)) {
return false;
}
return true;
}
}
}
|
package org.pentaho.reporting.engine.classic.core.function;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.engine.classic.core.AttributeNames;
import org.pentaho.reporting.engine.classic.core.Band;
import org.pentaho.reporting.engine.classic.core.CrosstabCell;
import org.pentaho.reporting.engine.classic.core.CrosstabCellBody;
import org.pentaho.reporting.engine.classic.core.CrosstabColumnGroup;
import org.pentaho.reporting.engine.classic.core.CrosstabOtherGroupBody;
import org.pentaho.reporting.engine.classic.core.CrosstabRowGroup;
import org.pentaho.reporting.engine.classic.core.Element;
import org.pentaho.reporting.engine.classic.core.Group;
import org.pentaho.reporting.engine.classic.core.GroupBody;
import org.pentaho.reporting.engine.classic.core.ItemBand;
import org.pentaho.reporting.engine.classic.core.ReportDefinition;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.RootLevelBand;
import org.pentaho.reporting.engine.classic.core.Section;
import org.pentaho.reporting.engine.classic.core.SubGroupBody;
import org.pentaho.reporting.engine.classic.core.SubReport;
import org.pentaho.reporting.engine.classic.core.event.PageEventListener;
import org.pentaho.reporting.engine.classic.core.event.ReportEvent;
import org.pentaho.reporting.engine.classic.core.metadata.ElementMetaData;
import org.pentaho.reporting.engine.classic.core.states.LayoutProcess;
import org.pentaho.reporting.engine.classic.core.states.ReportState;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
/**
* The AbstractElementFormatFunction provides a common base implementation for all functions that need to modify the
* report definition or the style of an report element or band during the report processing.
* <p/>
* The Expression retrieves the next root-level band that will be printed and uses this band as parameter for the {@link
* AbstractElementFormatFunction#processRootBand(org.pentaho.reporting.engine.classic.core.Section)} method.
*
* @author Thomas Morgner
*/
public abstract class AbstractElementFormatFunction extends AbstractFunction
implements PageEventListener, LayoutProcessorFunction
{
private static class NeedEvalResult
{
private boolean needToRun;
private long changeTracker;
private NeedEvalResult(final boolean needToRun, final long changeTracker)
{
this.needToRun = needToRun;
this.changeTracker = changeTracker;
}
public boolean isNeedToRun()
{
return needToRun;
}
public long getChangeTracker()
{
return changeTracker;
}
public String toString()
{
return "NeedEvalResult{" +
"needToRun=" + needToRun +
", changeTracker=" + changeTracker +
'}';
}
}
private static class PerformanceCollector implements Serializable
{
public int totalEvaluations;
public int evaluations;
public int skippedEvaluations;
}
private PerformanceCollector performanceCollector;
private final Log performanceLogger = LogFactory.getLog(getClass());
/**
* The name of the element that should be formatted.
*/
private String element;
private transient String attrName;
/**
* Creates an unnamed function. Make sure the name of the function is set using {@link #setName} before the function
* is added to the report's function collection.
*/
protected AbstractElementFormatFunction()
{
attrName = computeUniqueIdentifier();
}
/**
* Sets the element name. The name denotes an element or band within the root-band or the root-band itself. It is
* possible to define multiple elements with the same name to apply the modification to all of these elements.
*
* @param name The element name.
* @see org.pentaho.reporting.engine.classic.core.function.FunctionUtilities#findAllElements(org.pentaho.reporting.engine.classic.core.Band, String)
*/
public void setElement(final String name)
{
this.element = name;
}
/**
* Returns the element name.
*
* @return The element name.
* @see #setElement(String)
*/
public String getElement()
{
return element;
}
/**
* Receives notification that report generation initializes the current run. <P> The event carries a
* ReportState.Started state. Use this to initialize the report.
*
* @param event The event.
*/
public void reportInitialized(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
performanceCollector = new PerformanceCollector();
if (isExecutable() == false)
{
return;
}
if (event.getState().isSubReportEvent() == false)
{
evaluateElement(event.getReport());
}
processRootBand(event.getReport().getPageHeader());
processRootBand(event.getReport().getWatermark());
}
/**
* Processes the Report-Header.
*
* @param event the event.
*/
public void reportStarted(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
final Band b = event.getReport().getReportHeader();
processRootBand(b);
processFooterBands(event.getState());
}
/**
* Processes the group header of the current group.
*
* @param event the event.
*/
public void groupStarted(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
final Group group = FunctionUtilities.getCurrentGroup(event);
evaluateElement(group);
processGroupHeaders(group);
evaluateElement(group.getBody());
processFooterBands(event.getState());
}
/**
* Processes the No-Data-Band.
*
* @param event the report event.
*/
public void itemsStarted(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
if (event.getState().isCrosstabActive())
{
final CrosstabCellBody crosstabCellBody = event.getReport().getCrosstabCellBody();
processRootBand(crosstabCellBody.getHeader());
processRootBand(crosstabCellBody.findElement(null, null));
}
else
{
final ReportDefinition reportDefinition = event.getReport();
processRootBand(reportDefinition.getDetailsHeader());
processRootBand(reportDefinition.getNoDataBand());
}
processFooterBands(event.getState());
}
/**
* Processes the ItemBand.
*
* @param event the event.
*/
public void itemsAdvanced(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
if (event.getState().isCrosstabActive())
{
final CrosstabCellBody crosstabCellBody = event.getReport().getCrosstabCellBody();
processRootBand(crosstabCellBody.findElement(null, null));
}
else
{
final ItemBand itemBand = event.getReport().getItemBand();
processRootBand(itemBand);
}
processFooterBands(event.getState());
}
/**
* Receives notification that a group of item bands has been completed. <P> The itemBand is finished, the report
* starts to close open groups.
*
* @param event The event.
*/
public void itemsFinished(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
if (event.getState().isCrosstabActive())
{
final CrosstabCellBody crosstabCellBody = event.getReport().getCrosstabCellBody();
processRootBand(crosstabCellBody.findElement(null, null));
}
else
{
processRootBand(event.getReport().getDetailsFooter());
}
processFooterBands(event.getState());
}
/**
* Processes the group footer of the current group.
*
* @param event the event.
*/
public void groupFinished(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
final Group group = FunctionUtilities.getCurrentGroup(event);
if (group instanceof CrosstabColumnGroup)
{
final CrosstabCellBody crosstabCellBody = event.getReport().getCrosstabCellBody();
final int elementCount = crosstabCellBody.getElementCount();
for (int i = 1; i < elementCount; i += 1)
{
final CrosstabCell cell = (CrosstabCell) crosstabCellBody.getElement(i);
if (cell.getRowField() == null)
{
processRootBand(cell);
}
}
}
else if (group instanceof CrosstabRowGroup)
{
final CrosstabRowGroup rowGroup = (CrosstabRowGroup) group;
final CrosstabCellBody crosstabCellBody = event.getReport().getCrosstabCellBody();
final int elementCount = crosstabCellBody.getElementCount();
for (int i = 1; i < elementCount; i += 1)
{
final CrosstabCell cell = (CrosstabCell) crosstabCellBody.getElement(i);
if (ObjectUtilities.equal(cell.getRowField(), rowGroup.getField()))
{
processRootBand(cell);
}
}
}
else
{
processAllGroupFooterBands(group);
}
processFooterBands(event.getState());
}
/**
* Processes the Report-Footer.
*
* @param event the event.
*/
public void reportFinished(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
final Band b = event.getReport().getReportFooter();
processRootBand(b);
processFooterBands(event.getState());
}
public void reportDone(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
reportCachePerformance();
}
protected void reportCachePerformance()
{
if (performanceLogger.isInfoEnabled())
{
performanceLogger.info(String.format("Performance: %s => total=%d, evaluated=%d (%f%%), avoided=%d (%f%%)", getClass(),
performanceCollector.totalEvaluations,
performanceCollector.evaluations,
100f * performanceCollector.evaluations / Math.max(1.0f, performanceCollector.totalEvaluations),
performanceCollector.skippedEvaluations,
100f * performanceCollector.skippedEvaluations / Math.max(1.0f, performanceCollector.totalEvaluations)));
}
}
protected void processGroupHeaders(final Group group)
{
final int elementCount = group.getElementCount();
for (int i = 0; i < elementCount; i += 1)
{
final Element e = group.getElement(i);
final ElementMetaData.TypeClassification reportElementType = e.getMetaData().getReportElementType();
if (reportElementType != ElementMetaData.TypeClassification.HEADER)
{
continue;
}
final Band b = (Band) e;
processRootBand(b);
}
}
private void processAllGroupFooterBands(final Group group)
{
final int elementCount = group.getElementCount();
for (int i = 0; i < elementCount; i += 1)
{
final Element e = group.getElement(i);
final ElementMetaData.TypeClassification reportElementType = e.getMetaData().getReportElementType();
if (reportElementType != ElementMetaData.TypeClassification.FOOTER)
{
continue;
}
final Band b = (Band) e;
processRootBand(b);
}
}
/**
* Processes the page footer.
*
* @param event the event.
*/
public void pageFinished(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
final Band b = event.getReport().getPageFooter();
processRootBand(b);
}
/**
* Processes the page header.
*
* @param event the event.
*/
public void pageStarted(final ReportEvent event)
{
if (FunctionUtilities.isLayoutLevel(event) == false)
{
// dont do anything if there is no printing done ...
return;
}
if (isExecutable() == false)
{
return;
}
if (performanceCollector == null)
{
// this is part of a bug. LayoutProcessorFunctions seem to get informed of page-started before they receive
// a reportInitialized event.
performanceCollector = new PerformanceCollector();
}
final Band w = event.getReport().getWatermark();
processRootBand(w);
processHeaderBands(event.getState());
processFooterBands(event.getState());
}
protected void processFooterBands(ReportState state)
{
while (state != null)
{
final ReportDefinition reportDefinition = state.getReport();
processRootBand(reportDefinition.getPageFooter());
if (state.isInItemGroup())
{
processRootBand(reportDefinition.getDetailsFooter());
}
Group g = reportDefinition.getRootGroup();
int groupCounter = 0;
while (g != null && groupCounter <= state.getCurrentGroupIndex())
{
processAllGroupFooterBands(g);
final GroupBody body = g.getBody();
if (body instanceof SubGroupBody)
{
groupCounter += 1;
final SubGroupBody sgb = (SubGroupBody) body;
g = sgb.getGroup();
}
else if (body instanceof CrosstabOtherGroupBody)
{
groupCounter += 1;
final CrosstabOtherGroupBody sgb = (CrosstabOtherGroupBody) body;
g = sgb.getGroup();
}
else
{
break;
}
}
state = state.getParentSubReportState();
}
}
protected void processHeaderBands(ReportState state)
{
while (state != null)
{
final ReportDefinition reportDefinition = state.getReport();
processRootBand(reportDefinition.getPageHeader());
if (state.isInItemGroup())
{
processRootBand(reportDefinition.getDetailsHeader());
}
Group g = reportDefinition.getRootGroup();
int groupCounter = 0;
while (g != null && groupCounter <= state.getCurrentGroupIndex())
{
processGroupHeaders(g);
final GroupBody body = g.getBody();
if (body instanceof SubGroupBody)
{
groupCounter += 1;
final SubGroupBody sgb = (SubGroupBody) body;
g = sgb.getGroup();
}
else if (body instanceof CrosstabOtherGroupBody)
{
groupCounter += 1;
final CrosstabOtherGroupBody sgb = (CrosstabOtherGroupBody) body;
g = sgb.getGroup();
}
else
{
break;
}
}
state = state.getParentSubReportState();
}
}
/**
* Format-Functions usually are not expected to return anything.
*
* @return null, as format functions do not compute values.
*/
public Object getValue()
{
return null;
}
protected boolean isExecutable()
{
return true;
}
/**
* Evaluates all style expressions from all elements and updates the style-sheet if needed.
*
* @param b the band.
*/
protected final void processRootBand(final Section b)
{
if (b == null)
{
return;
}
final NeedEvalResult needToRun = (NeedEvalResult) b.getAttribute(AttributeNames.Internal.NAMESPACE, attrName);
if (needToRun != null)
{
if (needToRun.isNeedToRun() == false)
{
if (b.getChangeTracker() == needToRun.getChangeTracker())
{
recordCacheHit(b);
return;
}
}
}
recordCacheMiss(b);
final boolean needToRunVal = processBand(b);
b.setAttribute(AttributeNames.Internal.NAMESPACE, attrName, new NeedEvalResult(needToRunVal, b.getChangeTracker()), false);
}
protected void recordCacheHit(final ReportElement e)
{
performanceCollector.totalEvaluations += 1;
performanceCollector.skippedEvaluations += 1;
}
protected void recordCacheMiss(final ReportElement e)
{
performanceCollector.totalEvaluations += 1;
performanceCollector.evaluations += 1;
}
protected abstract boolean evaluateElement(final ReportElement e);
protected final boolean processBand(final Section b)
{
boolean hasAttrExpressions = evaluateElement(b);
final int length = b.getElementCount();
for (int i = 0; i < length; i++)
{
final Element element = b.getElement(i);
final ElementMetaData.TypeClassification reportElementType = element.getMetaData().getReportElementType();
if (reportElementType == ElementMetaData.TypeClassification.DATA ||
reportElementType == ElementMetaData.TypeClassification.CONTROL ||
reportElementType == ElementMetaData.TypeClassification.SUBREPORT ||
element instanceof Section == false)
{
if (evaluateElement(element))
{
hasAttrExpressions = true;
}
}
else
{
final Section section = (Section) element;
if (processBand(section))
{
hasAttrExpressions = true;
}
}
}
if (b instanceof RootLevelBand)
{
final RootLevelBand rlb = (RootLevelBand) b;
final SubReport[] reports = rlb.getSubReports();
for (int i = 0; i < reports.length; i++)
{
final SubReport subReport = reports[i];
if (evaluateElement(subReport))
{
hasAttrExpressions = true;
}
}
}
return hasAttrExpressions;
}
public final int getDependencyLevel()
{
return LayoutProcess.LEVEL_PAGINATE;
}
/**
* Helper method for serialization.
*
* @param in the input stream from where to read the serialized object.
* @throws java.io.IOException when reading the stream fails.
* @throws ClassNotFoundException if a class definition for a serialized object could not be found.
*/
private void readObject(final ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
attrName = computeUniqueIdentifier();
}
public AbstractElementFormatFunction getInstance()
{
final AbstractElementFormatFunction expression = (AbstractElementFormatFunction) super.getInstance();
expression.attrName = computeUniqueIdentifier();
return expression;
}
private String computeUniqueIdentifier()
{
return "need-eval-result:" + getClass().getName() + '@' + System.identityHashCode(this);
}
}
|
package org.eclipse.persistence.sessions.serializers;
import java.io.Serializable;
import org.eclipse.persistence.sessions.Session;
/**
* Generic serializer interface.
* Allows for a plugable serializer for Remote, Cache Coordination, Converters.
* @author James Sutherland
*/
public interface Serializer extends Serializable, Cloneable {
Object serialize(Object object, Session session);
Object deserialize(Object bytes, Session session);
Class getType();
}
|
package org.silverpeas.components.gallery;
import org.silverpeas.core.admin.user.model.SilverpeasRole;
import org.silverpeas.core.admin.service.DefaultOrganizationController;
import org.silverpeas.core.admin.user.model.User;
import org.silverpeas.core.admin.user.model.UserDetail;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.silverpeas.core.cache.service.SessionCacheService;
import org.silverpeas.core.security.session.SessionInfo;
import org.silverpeas.core.test.DataSetTest;
import org.silverpeas.core.admin.user.constant.UserAccessLevel;
import org.silverpeas.core.cache.service.CacheServiceProvider;
import org.silverpeas.core.admin.service.OrganizationController;
import org.silverpeas.core.util.ServiceProvider;
import javax.annotation.Priority;
import javax.enterprise.inject.Alternative;
import javax.inject.Singleton;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.Date;
import static javax.interceptor.Interceptor.Priority.APPLICATION;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.silverpeas.core.test.rule.DbSetupRule.getActualDataSet;
/**
* Base class for tests in the gallery component.
* It prepares the database to use in tests.
*/
@SuppressWarnings("CdiManagedBeanInconsistencyInspection")
@RunWith(Arquillian.class)
public abstract class BaseGalleryTest extends DataSetTest {
private static final String TABLE_CREATION_SCRIPT =
"/org/silverpeas/components/gallery/dao/create-media-database.sql";
private static final String DATASET_XML_SCRIPT =
"/org/silverpeas/components/gallery/dao/media_dataset.xml";
protected static final String GALLERY0 = "gallery25";
protected static final String GALLERY1 = "gallery26";
protected static final String GALLERY2 = "gallery27";
protected final static String INSTANCE_A = "instanceId_A";
protected final static Date TODAY = java.sql.Date.valueOf("2014-03-01");
protected final static Date CREATE_DATE = Timestamp.valueOf("2014-06-01 16:38:52.253");
protected final static Date LAST_UPDATE_DATE = Timestamp.valueOf("2014-06-03 11:20:42.637");
protected final static int MEDIA_ROW_COUNT = 12;
protected final static int MEDIA_INTERNAL_ROW_COUNT = 9;
protected final static int MEDIA_PHOTO_ROW_COUNT = 3;
protected final static int MEDIA_VIDEO_ROW_COUNT = 3;
protected final static int MEDIA_SOUND_ROW_COUNT = 3;
protected final static int MEDIA_STREAMING_ROW_COUNT = 3;
protected final static int MEDIA_PATH_ROW_COUNT = 13;
protected final static int MEDIA_ORDER_ROW_COUNT = 3;
protected final static int MEDIA_ORDER_DETAIL_ROW_COUNT = 6;
protected UserDetail adminAccessUser;
protected UserDetail publisherUser;
protected UserDetail writerUser;
protected UserDetail userUser;
@Deployment
public static Archive<?> createTestArchive() {
return GalleryWarBuilder.onWarForTestClass(BaseGalleryTest.class)
.addClasses(StubbedOrganizationController.class)
.addAsResource(TABLE_CREATION_SCRIPT.substring(1))
.addAsResource(DATASET_XML_SCRIPT.substring(1)).build();
}
@Override
protected String getDbSetupTableCreationSqlScript() {
return TABLE_CREATION_SCRIPT;
}
@SuppressWarnings("unchecked")
@Override
protected String getDbSetupInitializations() {
return DATASET_XML_SCRIPT;
}
@Before
public void setUp() throws Exception {
verifyDataBeforeTest();
adminAccessUser = new UserDetail();
adminAccessUser.setId("adminUserId");
adminAccessUser.setLastName("adminUserName");
adminAccessUser.setAccessLevel(UserAccessLevel.ADMINISTRATOR);
publisherUser = new UserDetail();
publisherUser.setId("publisherUserId");
publisherUser.setLastName("publisherUserName");
writerUser = new UserDetail();
writerUser.setId("writerUserId");
writerUser.setLastName("writerUserName");
userUser = new UserDetail();
userUser.setId("userUserId");
userUser.setLastName("userUserName");
when(getOrganisationControllerMock().getUserDetail(adminAccessUser.getId()))
.thenReturn(adminAccessUser);
when(getOrganisationControllerMock().getUserDetail(publisherUser.getId()))
.thenReturn(publisherUser);
when(getOrganisationControllerMock().getUserDetail(writerUser.getId())).thenReturn(writerUser);
when(getOrganisationControllerMock().getUserDetail(userUser.getId())).thenReturn(userUser);
for (String instanceId : new String[]{INSTANCE_A, GALLERY0, GALLERY1, GALLERY2}) {
when(getOrganisationControllerMock().getUserProfiles(publisherUser.getId(), instanceId))
.thenReturn(new String[]{SilverpeasRole.reader.name(), SilverpeasRole.publisher.name()});
when(getOrganisationControllerMock().getUserProfiles(writerUser.getId(), instanceId))
.thenReturn(new String[]{SilverpeasRole.reader.name(), SilverpeasRole.writer.name()});
when(getOrganisationControllerMock().getUserProfiles(userUser.getId(), instanceId))
.thenReturn(new String[]{SilverpeasRole.reader.name()});
}
}
@After
public void tearDown() throws Exception {
CacheServiceProvider.clearAllThreadCaches();
}
protected OrganizationController getOrganisationControllerMock() {
return StubbedOrganizationController.getMock();
}
/**
* Verifying the data before a test.
*/
protected void verifyDataBeforeTest() throws Exception {
try (Connection connection = getConnection()) {
IDataSet actualDataSet = getActualDataSet(connection);
ITable mediaTable = actualDataSet.getTable("SC_Gallery_Media");
assertThat(mediaTable.getRowCount(), is(MEDIA_ROW_COUNT));
ITable internalTable = actualDataSet.getTable("SC_Gallery_Internal");
assertThat(internalTable.getRowCount(), is(MEDIA_INTERNAL_ROW_COUNT));
ITable photoTable = actualDataSet.getTable("SC_Gallery_Photo");
assertThat(photoTable.getRowCount(), is(MEDIA_PHOTO_ROW_COUNT));
ITable videoTable = actualDataSet.getTable("SC_Gallery_Video");
assertThat(videoTable.getRowCount(), is(MEDIA_VIDEO_ROW_COUNT));
ITable soundTable = actualDataSet.getTable("SC_Gallery_Sound");
assertThat(soundTable.getRowCount(), is(MEDIA_SOUND_ROW_COUNT));
ITable streamingTable = actualDataSet.getTable("SC_Gallery_Streaming");
assertThat(streamingTable.getRowCount(), is(MEDIA_STREAMING_ROW_COUNT));
ITable pathTable = actualDataSet.getTable("SC_Gallery_Path");
assertThat(pathTable.getRowCount(), is(MEDIA_PATH_ROW_COUNT));
ITable orderTable = actualDataSet.getTable("SC_Gallery_Order");
assertThat(orderTable.getRowCount(), is(MEDIA_ORDER_ROW_COUNT));
ITable orderDetailTable = actualDataSet.getTable("SC_Gallery_OrderDetail");
assertThat(orderDetailTable.getRowCount(), is(MEDIA_ORDER_DETAIL_ROW_COUNT));
}
}
/**
* @author Yohann Chastagnier
*/
@Singleton
@Alternative
@Priority(APPLICATION + 10)
public static class StubbedOrganizationController extends DefaultOrganizationController {
private OrganizationController mock = mock(OrganizationController.class);
static OrganizationController getMock() {
return ((StubbedOrganizationController) ServiceProvider
.getService(OrganizationController.class)).mock;
}
@Override
public UserDetail getUserDetail(final String sUserId) {
return mock.getUserDetail(sUserId);
}
@Override
public String[] getUserProfiles(final String userId, final String componentId) {
return mock.getUserProfiles(userId, componentId);
}
}
}
|
package uk.ac.ebi.spot.goci.curation.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException;
import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport;
import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter;
import uk.ac.ebi.spot.goci.curation.service.MailService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.CurationStatus;
import uk.ac.ebi.spot.goci.model.Curator;
import uk.ac.ebi.spot.goci.model.DiseaseTrait;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Ethnicity;
import uk.ac.ebi.spot.goci.model.Housekeeping;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.CurationStatusRepository;
import uk.ac.ebi.spot.goci.repository.CuratorRepository;
import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.EthnicityRepository;
import uk.ac.ebi.spot.goci.repository.HousekeepingRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import uk.ac.ebi.spot.goci.service.DefaultPubMedSearchService;
import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Controller
@RequestMapping("/studies")
public class StudyController {
// Repositories allowing access to database objects associated with a study
private StudyRepository studyRepository;
private HousekeepingRepository housekeepingRepository;
private DiseaseTraitRepository diseaseTraitRepository;
private EfoTraitRepository efoTraitRepository;
private CuratorRepository curatorRepository;
private CurationStatusRepository curationStatusRepository;
private AssociationRepository associationRepository;
private EthnicityRepository ethnicityRepository;
// Pubmed ID lookup service
private DefaultPubMedSearchService defaultPubMedSearchService;
private MailService mailService;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public StudyController(StudyRepository studyRepository,
HousekeepingRepository housekeepingRepository,
DiseaseTraitRepository diseaseTraitRepository,
EfoTraitRepository efoTraitRepository,
CuratorRepository curatorRepository,
CurationStatusRepository curationStatusRepository,
AssociationRepository associationRepository,
EthnicityRepository ethnicityRepository,
DefaultPubMedSearchService defaultPubMedSearchService,
MailService mailService) {
this.studyRepository = studyRepository;
this.housekeepingRepository = housekeepingRepository;
this.diseaseTraitRepository = diseaseTraitRepository;
this.efoTraitRepository = efoTraitRepository;
this.curatorRepository = curatorRepository;
this.curationStatusRepository = curationStatusRepository;
this.associationRepository = associationRepository;
this.ethnicityRepository = ethnicityRepository;
this.defaultPubMedSearchService = defaultPubMedSearchService;
this.mailService = mailService;
}
/* All studies and various filtered lists */
// Return all studies
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public String searchStudies(Model model) {
// Find all studies
model.addAttribute("studies", studyRepository.findAll());
// Add a studySearchFilter to model in case user want to filter table
model.addAttribute("studySearchFilter", new StudySearchFilter());
return "studies";
}
// Studies by curator and/or status
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE, params = "filters=true", method = RequestMethod.POST)
public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter, Model model) {
// Get ids of objects searched for
Long status = studySearchFilter.getStatusSearchFilterId();
Long curator = studySearchFilter.getCuratorSearchFilterId();
String pubmedId = studySearchFilter.getPubmedId();
String author = studySearchFilter.getAuthor();
// Search by pubmed ID option available from landing page
if (pubmedId != null && !pubmedId.isEmpty()) {
model.addAttribute("studies", studyRepository.findByPubmedId(pubmedId));
return "studies";
}
// Search by author option available from landing page
if (author != null && !author.isEmpty()) {
model.addAttribute("studies", studyRepository.findByAuthorContainingIgnoreCase(author));
return "studies";
}
// If user entered a status
if (status != null) {
// If we have curator and status find by both
if (curator != null) {
model.addAttribute("studies",
studyRepository.findByCurationStatusAndCuratorAllIgnoreCase(status, curator));
}
else {
model.addAttribute("studies", studyRepository.findByCurationStatusIgnoreCase(status));
}
}
// If user entered curator
else if (curator != null) {
model.addAttribute("studies", studyRepository.findByCuratorIgnoreCase(curator));
}
// If all else fails return all studies
else {
model.addAttribute("studies", studyRepository.findAll());
}
return "studies";
}
/* New Study*/
// Add a new study
// Directs user to an empty form to which they can create a new study
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String newStudyForm(Model model) {
model.addAttribute("study", new Study());
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Save study found by Pubmed Id
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new/import", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String importStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport) throws PubmedImportException {
// Remove whitespace
String pubmedId = pubmedIdForImport.getPubmedId().trim();
// Check if there is an existing study with the same pubmed id
Collection<Study> existingStudies = studyRepository.findByPubmedId(pubmedId);
if (existingStudies.size() > 0) {
throw new PubmedImportException();
}
// Pass to importer
Study importedStudy = defaultPubMedSearchService.findPublicationSummary(pubmedId);
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
importedStudy.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(importedStudy);
// Save new study
studyRepository.save(importedStudy);
return "redirect:/studies/" + importedStudy.getId();
}
// Save newly added study details
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model) {
// If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix
if (bindingResult.hasErrors()) {
model.addAttribute("study", study);
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
study.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(study);
return "redirect:/studies/" + newStudy.getId();
}
/* Exitsing study*/
// View a study
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudy(Model model, @PathVariable Long studyId) {
Study studyToView = studyRepository.findOne(studyId);
model.addAttribute("study", studyToView);
return "study";
}
// Edit an existing study
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String updateStudy(@ModelAttribute Study study,
Model model,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Use id in URL to get study and then its associated housekeeping
Study existingStudy = studyRepository.findOne(studyId);
Housekeeping existingHousekeeping = existingStudy.getHousekeeping();
// Set the housekeeping of the study returned to one already linked to it in database
// Need to do this as we don't return housekeeping in form
study.setHousekeeping(existingHousekeeping);
// Saves the new information returned from form
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId();
}
// Delete an existing study
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyToDelete(Model model, @PathVariable Long studyId) {
Study studyToDelete = studyRepository.findOne(studyId);
// Check if it has any associations
Collection<Association> associations = associationRepository.findByStudyId(studyId);
// If so warn the curator
if (!associations.isEmpty()) {
return "delete_study_with_associations_warning";
}
else {
model.addAttribute("studyToDelete", studyToDelete);
return "delete_study";
}
}
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String deleteStudy(@PathVariable Long studyId) {
// Find our study based on the ID
Study studyToDelete = studyRepository.findOne(studyId);
// Before we delete the study get its associated housekeeping and ethnicity
Long housekeepingId = studyToDelete.getHousekeeping().getId();
Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId);
Collection<Ethnicity> ethnicitiesAttachedToStudy = ethnicityRepository.findByStudyId(studyId);
// Delete ethnicity information linked to this study
for (Ethnicity ethnicity : ethnicitiesAttachedToStudy) {
ethnicityRepository.delete(ethnicity);
}
// Delete study
studyRepository.delete(studyToDelete);
// Delete housekeeping
housekeepingRepository.delete(housekeepingAttachedToStudy);
return "redirect:/studies";
}
// Duplicate a study
@RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// Find study user wants to duplicate, based on the ID
Study studyToDuplicate = studyRepository.findOne(studyId);
Study duplicateStudy = copyStudy(studyToDuplicate);
// Create housekeeping object and add duplicate message
Housekeeping studyHousekeeping = createHousekeeping();
studyHousekeeping.setNotes(
"Duplicate of study: " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId());
duplicateStudy.setHousekeeping(studyHousekeeping);
// Save newly duplicated study
studyRepository.save(duplicateStudy);
// Copy existing ethnicity
Collection<Ethnicity> studyToDuplicateEthnicities = ethnicityRepository.findByStudyId(studyId);
for (Ethnicity studyToDuplicateEthnicity : studyToDuplicateEthnicities) {
Ethnicity duplicateEthnicity = copyEthnicity(studyToDuplicateEthnicity);
duplicateEthnicity.setStudy(duplicateStudy);
ethnicityRepository.save(duplicateEthnicity);
}
// Add duplicate message
String message =
"Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId();
redirectAttributes.addFlashAttribute("duplicateMessage", message);
return "redirect:/studies/" + duplicateStudy.getId();
}
/* Study housekeeping/curator information */
// Generate page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) {
// Find study
Study study = studyRepository.findOne(studyId);
// If we don't have a housekeeping object create one, this should not occur though as they are created when study is created
if (study.getHousekeeping() == null) {
model.addAttribute("studyHousekeeping", new Housekeeping());
}
else {
model.addAttribute("studyHousekeeping", study.getHousekeeping());
}
// Return the housekeeping object attached to study and return the study
model.addAttribute("study", study);
return "study_housekeeping";
}
// Update page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Establish linked study
Study study = studyRepository.findOne(studyId);
// Before we save housekeeping get the status in database so we can check for a change
CurationStatus statusInDatabase = housekeepingRepository.findOne(housekeeping.getId()).getCurationStatus();
// Save housekeeping returned from form straight away to save any curator entered details like notes etc
housekeepingRepository.save(housekeeping);
// For the study check all SNPs have been checked
Collection<Association> associations = associationRepository.findByStudyId(studyId);
int snpsNotChecked = 0;
for (Association association : associations) {
// If we have one that is not checked set value
if (association.getSnpChecked() == false) {
snpsNotChecked = 1;
}
}
// Establish whether user has set status to "Publish study" and "Send to NCBI"
// as corresponding dates will be set in housekeeping table
CurationStatus currentStatus = housekeeping.getCurationStatus();
// If the status has changed
if (currentStatus != statusInDatabase) {
if (currentStatus != null && currentStatus.getStatus().equals("Publish study")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before publishing";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date publishDate = new java.util.Date();
housekeeping.setPublishDate(publishDate);
}
}
//Set date and send email notification
if (currentStatus != null && currentStatus.getStatus().equals("Send to NCBI")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before sending to NCBI";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date sendToNCBIDate = new java.util.Date();
housekeeping.setSendToNCBIDate(sendToNCBIDate);
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Send notification email to curators
if (currentStatus != null && currentStatus.getStatus().equals("Level 1 curation done")) {
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
// Set study housekeeping
study.setHousekeeping(housekeeping);
// Save our study
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
/* General purpose methods */
private Housekeeping createHousekeeping() {
// Create housekeeping object and create the study added date
Housekeeping housekeeping = new Housekeeping();
java.util.Date studyAddedDate = new java.util.Date();
housekeeping.setStudyAddedDate(studyAddedDate);
// Set status
CurationStatus status = curationStatusRepository.findByStatus("Awaiting Curation");
housekeeping.setCurationStatus(status);
// Set curator
Curator curator = curatorRepository.findByLastName("Level 1 Curator");
housekeeping.setCurator(curator);
// Save housekeeping
housekeepingRepository.save(housekeeping);
// Save housekeeping
return housekeeping;
}
private Study copyStudy(Study studyToDuplicate) {
Study duplicateStudy = new Study();
duplicateStudy.setAuthor(studyToDuplicate.getAuthor() + " DUP");
duplicateStudy.setStudyDate(studyToDuplicate.getStudyDate());
duplicateStudy.setPublication(studyToDuplicate.getPublication());
duplicateStudy.setTitle(studyToDuplicate.getTitle());
duplicateStudy.setInitialSampleSize(studyToDuplicate.getInitialSampleSize());
duplicateStudy.setReplicateSampleSize(studyToDuplicate.getReplicateSampleSize());
duplicateStudy.setPlatform(studyToDuplicate.getPlatform());
duplicateStudy.setPubmedId(studyToDuplicate.getPubmedId());
duplicateStudy.setCnv(studyToDuplicate.getCnv());
duplicateStudy.setGxe(studyToDuplicate.getGxe());
duplicateStudy.setGxg(studyToDuplicate.getGxg());
duplicateStudy.setDiseaseTrait(studyToDuplicate.getDiseaseTrait());
// Deal with EFO traits
Collection<EfoTrait> efoTraits = studyToDuplicate.getEfoTraits();
Collection<EfoTrait> efoTraitsDuplicateStudy = new ArrayList<EfoTrait>();
if (efoTraits != null && !efoTraits.isEmpty()) {
efoTraitsDuplicateStudy.addAll(efoTraits);
duplicateStudy.setEfoTraits(efoTraitsDuplicateStudy);
}
return duplicateStudy;
}
private Ethnicity copyEthnicity(Ethnicity studyToDuplicateEthnicity) {
Ethnicity duplicateEthnicity = new Ethnicity();
duplicateEthnicity.setType(studyToDuplicateEthnicity.getType());
duplicateEthnicity.setNumberOfIndividuals(studyToDuplicateEthnicity.getNumberOfIndividuals());
duplicateEthnicity.setEthnicGroup(studyToDuplicateEthnicity.getEthnicGroup());
duplicateEthnicity.setCountryOfOrigin(studyToDuplicateEthnicity.getCountryOfOrigin());
duplicateEthnicity.setCountryOfRecruitment(studyToDuplicateEthnicity.getCountryOfRecruitment());
duplicateEthnicity.setDescription(studyToDuplicateEthnicity.getDescription());
duplicateEthnicity.setPreviouslyReported(studyToDuplicateEthnicity.getPreviouslyReported());
duplicateEthnicity.setSampleSizesMatch(studyToDuplicateEthnicity.getSampleSizesMatch());
duplicateEthnicity.setNotes(studyToDuplicateEthnicity.getNotes());
return duplicateEthnicity;
}
/* Exception handling */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(PubmedLookupException.class)
public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) {
getLog().error("pubmed lookup exception", pubmedLookupException);
return "pubmed_lookup_warning";
}
@ExceptionHandler(PubmedImportException.class)
public String handlePubmedImportException(PubmedImportException pubmedImportException) {
getLog().error("pubmed import exception", pubmedImportException);
return "pubmed_import_warning";
}
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// Disease Traits
@ModelAttribute("diseaseTraits")
public List<DiseaseTrait> populateDiseaseTraits(Model model) {
return diseaseTraitRepository.findAll(sortByTraitAsc());
}
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEFOTraits(Model model) {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Curators
@ModelAttribute("curators")
public List<Curator> populateCurators(Model model) {
return curatorRepository.findAll();
}
// Curation statuses
@ModelAttribute("curationstatuses")
public List<CurationStatus> populateCurationStatuses(Model model) {
return curationStatusRepository.findAll();
}
// Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
}
|
package io.fluxcapacitor.javaclient.persisting.caching;
import io.fluxcapacitor.common.MessageType;
import io.fluxcapacitor.common.api.SerializedMessage;
import io.fluxcapacitor.javaclient.common.Message;
import io.fluxcapacitor.javaclient.common.serialization.DeserializingMessage;
import io.fluxcapacitor.javaclient.common.serialization.Serializer;
import io.fluxcapacitor.javaclient.modeling.Aggregate;
import io.fluxcapacitor.javaclient.modeling.AggregateRepository;
import io.fluxcapacitor.javaclient.persisting.eventsourcing.EventSourcingHandler;
import io.fluxcapacitor.javaclient.persisting.eventsourcing.EventSourcingHandlerFactory;
import io.fluxcapacitor.javaclient.tracking.client.TrackingClient;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
import static io.fluxcapacitor.common.MessageType.EVENT;
import static io.fluxcapacitor.javaclient.modeling.AggregateIdResolver.getAggregateId;
import static io.fluxcapacitor.javaclient.modeling.AggregateTypeResolver.getAggregateType;
import static io.fluxcapacitor.javaclient.tracking.client.TrackingUtils.start;
import static java.lang.String.format;
import static java.time.Instant.ofEpochMilli;
@RequiredArgsConstructor
@Slf4j
public class CachingAggregateRepository implements AggregateRepository {
private static final Function<String, String> keyFunction = aggregateId ->
CachingAggregateRepository.class.getSimpleName() + ":" + aggregateId;
private final AggregateRepository delegate;
private final EventSourcingHandlerFactory handlerFactory;
private final Cache cache;
private final String clientName;
private final TrackingClient trackingClient;
private final Serializer serializer;
private final AtomicBoolean started = new AtomicBoolean();
private final AtomicLong lastEventIndex = new AtomicLong();
@Override
public <T> Aggregate<T> load(@NonNull String aggregateId, @NonNull Class<T> aggregateType, boolean onlyCached) {
DeserializingMessage current = DeserializingMessage.getCurrent();
if (current != null && current.getMessageType() == MessageType.COMMAND) {
return delegate.load(aggregateId, aggregateType, onlyCached);
}
Aggregate<T> result = delegate.load(aggregateId, aggregateType, true);
if (result == null) {
return Optional.<Aggregate<T>>ofNullable(doLoad(aggregateId))
.orElseGet(() -> delegate.load(aggregateId, aggregateType, onlyCached));
}
return result;
}
private <T> RefreshingAggregate<T> doLoad(String aggregateId) {
if (started.compareAndSet(false, true)) {
log.info("Start tracking notifications");
start(format("%s_%s", clientName, CachingAggregateRepository.class.getSimpleName()),
trackingClient, this::handleEvents);
return null;
}
DeserializingMessage current = DeserializingMessage.getCurrent();
if (current != null) {
switch (current.getMessageType()) {
case EVENT:
case NOTIFICATION:
Long eventIndex = current.getSerializedObject().getIndex();
if (eventIndex != null && lastEventIndex.get() < eventIndex) {
synchronized (cache) {
while (lastEventIndex.get() < eventIndex) {
try {
cache.wait(5_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Failed to load aggregate for event {}", current, e);
return null;
}
}
}
}
break;
}
}
return cache.getIfPresent(keyFunction.apply(aggregateId));
}
protected void handleEvents(List<SerializedMessage> messages) {
serializer.deserializeMessages(messages.stream(), false, EVENT)
.forEach(m -> {
String aggregateId = getAggregateId(m);
Class<?> aggregateType = getAggregateType(m);
if (aggregateId != null && aggregateType != null) {
try {
handleEvent(m, aggregateId, aggregateType);
} catch (Exception e) {
log.error("Failed to handle event for aggregate with id {} of type {}", aggregateId,
aggregateType, e);
}
}
});
}
protected void handleEvent(DeserializingMessage event, String aggregateId, Class<?> type) {
try {
EventSourcingHandler<Object> handler = handlerFactory.forType(type);
String cacheKey = keyFunction.apply(aggregateId);
String eventId = event.getSerializedObject().getMessageId();
Instant timestamp = ofEpochMilli(event.getSerializedObject().getTimestamp());
RefreshingAggregate<?> aggregate = cache.getIfPresent(cacheKey);
//may be the first event for this aggregate
if (aggregate == null && handler.canHandle(null, event)) {
try {
aggregate = new RefreshingAggregate<>(handler.invoke(null, event), eventId,
timestamp, true);
} catch (Exception ignored) {
}
}
if (aggregate == null) {
aggregate = Optional.ofNullable(delegate.load(aggregateId, type)).map(a -> new RefreshingAggregate<>(
a.get(), a.lastEventId(), a.timestamp(), Objects.equals(a.lastEventId(), eventId)))
.orElseGet(() -> {
log.warn("Delegate repository did not contain aggregate with id {} of type {}",
aggregateId, type);
return null;
});
} else if (aggregate.inSync) {
try {
aggregate = new RefreshingAggregate<>(handler.invoke(aggregate.get(), event), eventId,
timestamp, true);
} catch (Exception e) {
log.error("Failed to update aggregate with id {} of type {}", aggregateId, type, e);
aggregate = null;
}
} else if (eventId.equals(aggregate.lastEventId)) {
aggregate = aggregate.toBuilder().inSync(true).build();
}
if (aggregate == null) {
cache.invalidate(cacheKey);
} else {
cache.put(cacheKey, aggregate);
}
} finally {
this.lastEventIndex.updateAndGet(
i -> Optional.ofNullable(event.getSerializedObject().getIndex()).orElse(i));
synchronized (cache) {
cache.notifyAll();
}
}
}
@Override
public boolean supports(Class<?> aggregateType) {
return delegate.supports(aggregateType);
}
@AllArgsConstructor
@Value @Accessors(fluent = true)
@Builder(toBuilder = true)
private static class RefreshingAggregate<T> implements Aggregate<T> {
T model;
String lastEventId;
Instant timestamp;
boolean inSync;
@Override
public T get() {
return model;
}
@Override
public Aggregate<T> apply(Message eventMessage) {
throw new UnsupportedOperationException(
format("Not allowed to apply a %s. The aggregate is readonly.", eventMessage));
}
}
}
|
package org.languagetool.rules.en;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.*;
import org.languagetool.rules.en.translation.BeoLingusTranslator;
import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule;
import org.languagetool.rules.translation.Translator;
import org.languagetool.synthesis.en.EnglishSynthesizer;
import org.languagetool.tools.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
@SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule {
private static Logger logger = LoggerFactory.getLogger(AbstractEnglishSpellerRule.class);
private static final EnglishSynthesizer synthesizer = (EnglishSynthesizer) Languages.getLanguageForShortCode("en").getSynthesizer();
private final BeoLingusTranslator translator;
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException {
this(messages, language, null, Collections.emptyList());
}
/**
* @since 4.4
*/
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
this(messages, language, null, userConfig, altLanguages, null, null);
}
protected static Map<String,String> loadWordlist(String path, int column) {
if (column != 0 && column != 1) {
throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column);
}
Map<String,String> words = new HashMap<>();
List<String> lines = JLanguageTool.getDataBroker().getFromResourceDirAsLines(path);
for (String line : lines) {
line = line.trim();
if (line.isEmpty() || line.startsWith("
continue;
}
String[] parts = line.split(";");
if (parts.length != 2) {
throw new RuntimeException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'");
}
words.put(parts[column].toLowerCase(), parts[column == 1 ? 0 : 1]);
}
return words;
}
/**
* @since 4.5
* optional: language model for better suggestions
*/
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, GlobalConfig globalConfig, UserConfig userConfig,
List<Language> altLanguages, LanguageModel languageModel, Language motherTongue) throws IOException {
super(messages, language, globalConfig, userConfig, altLanguages, languageModel, motherTongue);
super.ignoreWordsWithLength = 1;
setCheckCompound(true);
addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."),
Example.fixed("This <marker>sentence</marker> contains a spelling mistake."));
String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_" + language.getShortCodeWithCountryAndVariant() + ".txt");
for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) {
addIgnoreWords(ignoreWord);
}
translator = BeoLingusTranslator.getInstance(globalConfig);
topSuggestions = getTopSuggestions();
topSuggestionsIgnoreCase = getTopSuggestionsIgnoreCase();
}
@Override
protected List<SuggestedReplacement> filterSuggestions(List<SuggestedReplacement> suggestions, AnalyzedSentence sentence, int i) {
List<SuggestedReplacement> result = super.filterSuggestions(suggestions, sentence, i);
List<SuggestedReplacement> clean = new ArrayList<>();
for (SuggestedReplacement suggestion : result) {
if (!suggestion.getReplacement().matches(".* (s|t|d|ll|ve)")) { // e.g. 'timezones' suggests 'timezone s'
clean.add(suggestion);
}
}
return clean;
}
@Override
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException {
List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens);
if (ruleMatches.size() > 0) {
// so 'word' is misspelled:
IrregularForms forms = getIrregularFormsOrNull(word);
if (forms != null) {
String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) +
"</suggestion>, the " + forms.formName + " form of the " + forms.posName +
" '" + forms.baseform + "'?";
addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms);
} else {
VariantInfo variantInfo = isValidInOtherVariant(word);
if (variantInfo != null) {
String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + ".";
String suggestion = StringTools.startsWithUppercase(word) ?
StringTools.uppercaseFirstChar(variantInfo.otherVariant()) : variantInfo.otherVariant();
replaceFormsOfFirstMatch(message, sentence, ruleMatches, suggestion);
}
}
}
// filter "re ..." (#2562):
for (RuleMatch ruleMatch : ruleMatches) {
List<SuggestedReplacement> cleaned = ruleMatch.getSuggestedReplacementObjects().stream()
.filter(k -> !k.getReplacement().startsWith("re ") &&
!k.getReplacement().startsWith("en ") &&
!k.getReplacement().startsWith("inter ") &&
!k.getReplacement().endsWith(" able") &&
!k.getReplacement().endsWith(" ed"))
.collect(Collectors.toList());
ruleMatch.setSuggestedReplacementObjects(cleaned);
}
return ruleMatches;
}
/**
* @since 4.5
*/
@Nullable
protected VariantInfo isValidInOtherVariant(String word) {
return null;
}
private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
List<String> allSuggestions = new ArrayList<>(forms);
for (String repl : oldMatch.getSuggestedReplacements()) {
if (!allSuggestions.contains(repl)) {
allSuggestions.add(repl);
}
}
newMatch.setSuggestedReplacements(allSuggestions);
ruleMatches.set(0, newMatch);
}
private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
SuggestedReplacement sugg = new SuggestedReplacement(suggestion);
sugg.setShortDescription(language.getName());
newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg));
ruleMatches.set(0, newMatch);
}
@SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"})
@Nullable
private IrregularForms getIrregularFormsOrNull(String word) {
IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative");
return irregularFormsOrNull;
}
@Nullable
private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) {
try {
for (String suffix : suffixes) {
if (word.endsWith(wordSuffix)) {
String baseForm = word.substring(0, word.length() - suffix.length());
String[] forms = Objects.requireNonNull(language.getSynthesizer()).synthesize(new AnalyzedToken(word, null, baseForm), posTag);
List<String> result = new ArrayList<>();
for (String form : forms) {
if (!speller1.isMisspelled(form)) {
// only accept suggestions that the spellchecker will accept
result.add(form);
}
}
// the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'),
// but we trust the spell checker in this case:
result.remove(word);
result.remove("badder"); // non-standard usage
result.remove("baddest"); // non-standard usage
result.remove("spake"); // can be removed after dict update
if (result.size() > 0) {
return new IrregularForms(baseForm, posName, formName, result);
}
}
}
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected final Map<String, List<String>> topSuggestions;
protected final Map<String, List<String>> topSuggestionsIgnoreCase;
protected Map<String, List<String>> getTopSuggestionsIgnoreCase() {
Map<String, List<String>> s = new HashMap<>();
s.put("xml", Arrays.asList("XML"));
s.put("php", Arrays.asList("PHP"));
s.put("asp", Arrays.asList("ASP"));
s.put("rss", Arrays.asList("RSS"));
s.put("ssd", Arrays.asList("SSD"));
s.put("ssds", Arrays.asList("SSDs"));
s.put("hdds", Arrays.asList("HDDs"));
s.put("isp", Arrays.asList("ISP"));
s.put("isps", Arrays.asList("ISPs"));
s.put("suv", Arrays.asList("SUV"));
s.put("suvs", Arrays.asList("SUVs"));
s.put("gif", Arrays.asList("GIF"));
s.put("gifs", Arrays.asList("GIFs"));
s.put("atm", Arrays.asList("ATM"));
s.put("atms", Arrays.asList("ATMs"));
s.put("png", Arrays.asList("PNG"));
s.put("pngs", Arrays.asList("PNGs"));
s.put("csv", Arrays.asList("CSV"));
s.put("csvs", Arrays.asList("CSVs"));
s.put("pdf", Arrays.asList("PDF"));
s.put("pdfs", Arrays.asList("PDFs"));
s.put("jpeg", Arrays.asList("JPEG"));
s.put("jpegs", Arrays.asList("JPEGs"));
s.put("jpg", Arrays.asList("JPG"));
s.put("jpgs", Arrays.asList("JPGs"));
s.put("bmp", Arrays.asList("BMP"));
s.put("bmps", Arrays.asList("BMPs"));
s.put("docx", Arrays.asList("DOCX"));
s.put("xlsx", Arrays.asList("XLSX"));
s.put("btw", Arrays.asList("BTW"));
s.put("idk", Arrays.asList("IDK"));
s.put("ai", Arrays.asList("AI"));
s.put("ip", Arrays.asList("IP"));
s.put("rfc", Arrays.asList("RFC"));
s.put("ppt", Arrays.asList("PPT"));
s.put("ppts", Arrays.asList("PPTs"));
s.put("pptx", Arrays.asList("PPTX"));
s.put("vpn", Arrays.asList("VPN"));
s.put("psn", Arrays.asList("PSN"));
s.put("usd", Arrays.asList("USD"));
s.put("tv", Arrays.asList("TV"));
s.put("eur", Arrays.asList("EUR"));
s.put("tbh", Arrays.asList("TBH"));
s.put("tbd", Arrays.asList("TBD"));
s.put("tba", Arrays.asList("TBA"));
s.put("omg", Arrays.asList("OMG"));
s.put("lol", Arrays.asList("LOL"));
s.put("lmao", Arrays.asList("LMAO"));
s.put("wtf", Arrays.asList("WTF"));
s.put("fyi", Arrays.asList("FYI"));
s.put("url", Arrays.asList("URL"));
s.put("urls", Arrays.asList("URLs"));
s.put("usb", Arrays.asList("USB"));
s.put("bbq", Arrays.asList("BBQ"));
s.put("bbqs", Arrays.asList("BBQs"));
s.put("ngo", Arrays.asList("NGO"));
s.put("ngos", Arrays.asList("NGOs"));
s.put("js", Arrays.asList("JS"));
s.put("css", Arrays.asList("CSS"));
s.put("roi", Arrays.asList("ROI"));
s.put("pov", Arrays.asList("POV"));
s.put("ctrl", Arrays.asList("Ctrl"));
s.put("italia", Arrays.asList("Italy"));
s.put("macboook", Arrays.asList("MacBook"));
s.put("macboooks", Arrays.asList("MacBooks"));
s.put("paypal", Arrays.asList("PayPal"));
s.put("youtube", Arrays.asList("YouTube"));
s.put("whatsapp", Arrays.asList("WhatsApp"));
s.put("webex", Arrays.asList("WebEx"));
s.put("jira", Arrays.asList("Jira"));
s.put("applepay", Arrays.asList("Apple Pay"));
s.put("&&", Arrays.asList("&"));
s.put("wensday", Arrays.asList("Wednesday"));
s.put("linkedin", Arrays.asList("LinkedIn"));
s.put("ebay", Arrays.asList("eBay"));
s.put("interweb", Arrays.asList("internet"));
s.put("interwebs", Arrays.asList("internet"));
s.put("afro-american", Arrays.asList("Afro-American"));
s.put("oconnor", Arrays.asList("O'Connor"));
s.put("oconor", Arrays.asList("O'Conor"));
s.put("obrien", Arrays.asList("O'Brien"));
s.put("odonnell", Arrays.asList("O'Donnell"));
s.put("oneill", Arrays.asList("O'Neill"));
s.put("oneil", Arrays.asList("O'Neil"));
s.put("oconnell", Arrays.asList("O'Connell"));
s.put("todo", Arrays.asList("To-do", "To do"));
s.put("todos", Arrays.asList("To-dos"));
s.put("ecommerce", Arrays.asList("e-commerce"));
s.put("elearning", Arrays.asList("e-learning"));
s.put("esport", Arrays.asList("e-sport"));
s.put("esports", Arrays.asList("e-sports"));
s.put("g-mail", Arrays.asList("Gmail"));
s.put("playstation", Arrays.asList("PlayStation"));
s.put("wix", Arrays.asList("Wix"));
return s;
}
protected Map<String, List<String>> getTopSuggestions() {
Map<String, List<String>> s = new HashMap<>();
s.put("on-prem", Arrays.asList("on-premise"));
s.put("sin-off", Arrays.asList("sign-off"));
s.put("sin-offs", Arrays.asList("sign-offs"));
s.put("Sin-off", Arrays.asList("Sign-off"));
s.put("Sin-offs", Arrays.asList("Sign-offs"));
s.put("Alot", Arrays.asList("A lot"));
s.put("alot", Arrays.asList("a lot"));
s.put("DDOS", Arrays.asList("DDoS"));
s.put("async", Arrays.asList("asynchronous", "asynchronously"));
s.put("Async", Arrays.asList("Asynchronous", "Asynchronously"));
s.put("endevours", Arrays.asList("endeavours"));
s.put("endevors", Arrays.asList("endeavors"));
s.put("endevour", Arrays.asList("endeavour"));
s.put("endevor", Arrays.asList("endeavor"));
s.put("countrys", Arrays.asList("countries", "country's", "country"));
s.put("Countrys", Arrays.asList("Countries", "Country's", "Country"));
s.put("familys", Arrays.asList("families", "family's", "family"));
s.put("Familys", Arrays.asList("Families", "Family's", "Family"));
s.put("infact", Arrays.asList("in fact"));
s.put("Infact", Arrays.asList("In fact"));
s.put("ad-hoc", Arrays.asList("ad hoc"));
s.put("adhoc", Arrays.asList("ad hoc"));
s.put("Ad-hoc", Arrays.asList("Ad hoc"));
s.put("Adhoc", Arrays.asList("Ad hoc"));
s.put("ad-on", Arrays.asList("add-on"));
s.put("add-o", Arrays.asList("add-on"));
s.put("acc", Arrays.asList("account", "accusative"));
s.put("Acc", Arrays.asList("Account", "Accusative"));
s.put("ºC", Arrays.asList("°C"));
s.put("jus", Arrays.asList("just", "juice"));
s.put("Jus", Arrays.asList("Just", "Juice"));
s.put("sayed", Arrays.asList("said"));
s.put("sess", Arrays.asList("says", "session", "cess"));
s.put("Addon", Arrays.asList("Add-on"));
s.put("Addons", Arrays.asList("Add-ons"));
s.put("ios", Arrays.asList("iOS"));
s.put("yrs", Arrays.asList("years"));
s.put("standup", Arrays.asList("stand-up"));
s.put("standups", Arrays.asList("stand-ups"));
s.put("Standup", Arrays.asList("Stand-up"));
s.put("Standups", Arrays.asList("Stand-ups"));
s.put("Playdough", Arrays.asList("Play-Doh"));
s.put("playdough", Arrays.asList("Play-Doh"));
s.put("biggy", Arrays.asList("biggie"));
s.put("lieing", Arrays.asList("lying"));
s.put("preffered", Arrays.asList("preferred"));
s.put("preffering", Arrays.asList("preferring"));
s.put("reffered", Arrays.asList("referred"));
s.put("reffering", Arrays.asList("referring"));
s.put("passthrough", Arrays.asList("pass-through"));
s.put("&&", Arrays.asList("&"));
s.put("cmon", Arrays.asList("c'mon"));
s.put("Cmon", Arrays.asList("C'mon"));
s.put("da", Arrays.asList("the"));
s.put("Da", Arrays.asList("The"));
s.put("Vue", Arrays.asList("Vue.JS"));
s.put("errornous", Arrays.asList("erroneous"));
s.put("brang", Arrays.asList("brought"));
s.put("brung", Arrays.asList("brought"));
s.put("thru", Arrays.asList("through"));
s.put("pitty", Arrays.asList("pity"));
s.put("barbwire", Arrays.asList("barbed wire"));
s.put("barbwires", Arrays.asList("barbed wires"));
s.put("monkie", Arrays.asList("monkey"));
s.put("Monkie", Arrays.asList("Monkey"));
s.put("monkies", Arrays.asList("monkeys"));
s.put("Monkies", Arrays.asList("Monkeys"));
// the replacement pairs would prefer "speak"
s.put("speach", Arrays.asList("speech"));
s.put("icecreem", Arrays.asList("ice cream"));
// in en-gb it's 'maths'
s.put("math", Arrays.asList("maths"));
s.put("fora", Arrays.asList("for a"));
s.put("fomr", Arrays.asList("form", "from"));
s.put("lotsa", Arrays.asList("lots of"));
s.put("tryna", Arrays.asList("trying to"));
s.put("coulda", Arrays.asList("could have"));
s.put("shoulda", Arrays.asList("should have"));
s.put("woulda", Arrays.asList("would have"));
s.put("tellem", Arrays.asList("tell them"));
s.put("Tellem", Arrays.asList("Tell them"));
s.put("Webex", Arrays.asList("WebEx"));
s.put("didint", Arrays.asList("didn't"));
s.put("Didint", Arrays.asList("Didn't"));
s.put("wasint", Arrays.asList("wasn't"));
s.put("hasint", Arrays.asList("hasn't"));
s.put("doesint", Arrays.asList("doesn't"));
s.put("ist", Arrays.asList("is"));
s.put("Boing", Arrays.asList("Boeing"));
s.put("te", Arrays.asList("the"));
s.put("todays", Arrays.asList("today's"));
s.put("Todays", Arrays.asList("Today's"));
s.put("todo", Arrays.asList("to-do", "to do"));
s.put("todos", Arrays.asList("to-dos", "to do"));
s.put("heres", Arrays.asList("here's"));
s.put("Heres", Arrays.asList("Here's"));
s.put("aways", Arrays.asList("always"));
s.put("McDonalds", Arrays.asList("McDonald's"));
s.put("ux", Arrays.asList("UX"));
s.put("ive", Arrays.asList("I've"));
s.put("infos", Arrays.asList("informations"));
s.put("Infos", Arrays.asList("Informations"));
s.put("prios", Arrays.asList("priorities"));
s.put("Prio", Arrays.asList("Priority"));
s.put("prio", Arrays.asList("priority"));
s.put("Ecommerce", Arrays.asList("E-Commerce"));
s.put("ebook", Arrays.asList("e-book"));
s.put("ebooks", Arrays.asList("e-books"));
s.put("eBook", Arrays.asList("e-book"));
s.put("eBooks", Arrays.asList("e-books"));
s.put("Ebook", Arrays.asList("E-Book"));
s.put("Ebooks", Arrays.asList("E-Books"));
s.put("Esport", Arrays.asList("E-Sport"));
s.put("Esports", Arrays.asList("E-Sports"));
s.put("R&B", Arrays.asList("R & B", "R 'n' B"));
s.put("ie", Arrays.asList("i.e."));
s.put("eg", Arrays.asList("e.g."));
s.put("ppl", Arrays.asList("people"));
s.put("kiddin", Arrays.asList("kidding"));
s.put("doin", Arrays.asList("doing"));
s.put("nothin", Arrays.asList("nothing"));
s.put("SPOC", Arrays.asList("SpOC"));
s.put("Thx", Arrays.asList("Thanks"));
s.put("thx", Arrays.asList("thanks"));
s.put("ty", Arrays.asList("thank you", "thanks"));
s.put("Sry", Arrays.asList("Sorry"));
s.put("sry", Arrays.asList("sorry"));
s.put("im", Arrays.asList("I'm"));
s.put("spoilt", Arrays.asList("spoiled"));
s.put("Lil", Arrays.asList("Little"));
s.put("lil", Arrays.asList("little"));
s.put("gmail", Arrays.asList("Gmail"));
s.put("Sucka", Arrays.asList("Sucker"));
s.put("sucka", Arrays.asList("sucker"));
s.put("whaddya", Arrays.asList("what are you", "what do you"));
s.put("Whaddya", Arrays.asList("What are you", "What do you"));
s.put("sinc", Arrays.asList("sync"));
s.put("sweety", Arrays.asList("sweetie"));
s.put("sweetys", Arrays.asList("sweeties"));
s.put("sowwy", Arrays.asList("sorry"));
s.put("Sowwy", Arrays.asList("Sorry"));
s.put("grandmum", Arrays.asList("grandma", "grandmother"));
s.put("Grandmum", Arrays.asList("Grandma", "Grandmother"));
s.put("Hongkong", Arrays.asList("Hong Kong"));
// For non-US English
s.put("center", Arrays.asList("centre"));
s.put("ur", Arrays.asList("your", "you are"));
s.put("Ur", Arrays.asList("Your", "You are"));
s.put("ure", Arrays.asList("your", "you are"));
s.put("Ure", Arrays.asList("Your", "You are"));
s.put("mins", Arrays.asList("minutes", "min"));
s.put("addon", Arrays.asList("add-on"));
s.put("addons", Arrays.asList("add-ons"));
s.put("afterparty", Arrays.asList("after-party"));
s.put("Afterparty", Arrays.asList("After-party"));
s.put("wellbeing", Arrays.asList("well-being"));
s.put("cuz", Arrays.asList("because"));
s.put("coz", Arrays.asList("because"));
s.put("pls", Arrays.asList("please"));
s.put("Pls", Arrays.asList("Please"));
s.put("plz", Arrays.asList("please"));
s.put("Plz", Arrays.asList("Please"));
// AtD irregular plurals - START
s.put("addendums", Arrays.asList("addenda"));
s.put("algas", Arrays.asList("algae"));
s.put("alumnas", Arrays.asList("alumnae"));
s.put("alumnuses", Arrays.asList("alumni"));
s.put("analysises", Arrays.asList("analyses"));
s.put("appendixs", Arrays.asList("appendices"));
s.put("axises", Arrays.asList("axes"));
s.put("bacilluses", Arrays.asList("bacilli"));
s.put("bacteriums", Arrays.asList("bacteria"));
s.put("basises", Arrays.asList("bases"));
s.put("beaus", Arrays.asList("beaux"));
s.put("bisons", Arrays.asList("bison"));
s.put("buffalos", Arrays.asList("buffaloes"));
s.put("calfs", Arrays.asList("calves"));
s.put("Childs", Arrays.asList("Children"));
s.put("childs", Arrays.asList("children"));
s.put("crisises", Arrays.asList("crises"));
s.put("criterions", Arrays.asList("criteria"));
s.put("curriculums", Arrays.asList("curricula"));
s.put("datums", Arrays.asList("data"));
s.put("deers", Arrays.asList("deer"));
s.put("diagnosises", Arrays.asList("diagnoses"));
s.put("echos", Arrays.asList("echoes"));
s.put("elfs", Arrays.asList("elves"));
s.put("ellipsises", Arrays.asList("ellipses"));
s.put("embargos", Arrays.asList("embargoes"));
s.put("erratums", Arrays.asList("errata"));
s.put("firemans", Arrays.asList("firemen"));
s.put("fishs", Arrays.asList("fishes", "fish"));
s.put("genuses", Arrays.asList("genera"));
s.put("gooses", Arrays.asList("geese"));
s.put("halfs", Arrays.asList("halves"));
s.put("heros", Arrays.asList("heroes"));
s.put("indexs", Arrays.asList("indices", "indexes"));
s.put("lifes", Arrays.asList("lives"));
s.put("mans", Arrays.asList("men"));
s.put("matrixs", Arrays.asList("matrices"));
s.put("meanses", Arrays.asList("means"));
s.put("mediums", Arrays.asList("media"));
s.put("memorandums", Arrays.asList("memoranda"));
s.put("mooses", Arrays.asList("moose"));
s.put("mosquitos", Arrays.asList("mosquitoes"));
s.put("neurosises", Arrays.asList("neuroses"));
s.put("nucleuses", Arrays.asList("nuclei"));
s.put("oasises", Arrays.asList("oases"));
s.put("ovums", Arrays.asList("ova"));
s.put("oxs", Arrays.asList("oxen"));
s.put("oxes", Arrays.asList("oxen"));
s.put("paralysises", Arrays.asList("paralyses"));
s.put("potatos", Arrays.asList("potatoes"));
s.put("radiuses", Arrays.asList("radii"));
s.put("selfs", Arrays.asList("selves"));
s.put("serieses", Arrays.asList("series"));
s.put("sheeps", Arrays.asList("sheep"));
s.put("shelfs", Arrays.asList("shelves"));
s.put("scissorses", Arrays.asList("scissors"));
s.put("specieses", Arrays.asList("species"));
s.put("stimuluses", Arrays.asList("stimuli"));
s.put("stratums", Arrays.asList("strata"));
s.put("tableaus", Arrays.asList("tableaux"));
s.put("thats", Arrays.asList("those"));
s.put("thesises", Arrays.asList("theses"));
s.put("thiefs", Arrays.asList("thieves"));
s.put("thises", Arrays.asList("these"));
s.put("tomatos", Arrays.asList("tomatoes"));
s.put("tooths", Arrays.asList("teeth"));
s.put("torpedos", Arrays.asList("torpedoes"));
s.put("vertebras", Arrays.asList("vertebrae"));
s.put("vetos", Arrays.asList("vetoes"));
s.put("vitas", Arrays.asList("vitae"));
s.put("watchs", Arrays.asList("watches"));
s.put("wifes", Arrays.asList("wives", "wife's"));
s.put("womans", Arrays.asList("women", "woman's"));
s.put("womens", Arrays.asList("women's"));
// AtD irregular plurals - END
// "tippy-top" is an often used word by Donald Trump
s.put("tippy-top", Arrays.asList("tip-top", "top most"));
s.put("tippytop", Arrays.asList("tip-top", "top most"));
s.put("imma", Arrays.asList("I'm going to", "I'm a"));
s.put("Imma", Arrays.asList("I'm going to", "I'm a"));
s.put("dontcha", Arrays.asList("don't you"));
s.put("tobe", Arrays.asList("to be"));
s.put("Gi", Arrays.asList("Hi"));
s.put("Ji", Arrays.asList("Hi"));
s.put("Dontcha", Arrays.asList("don't you"));
s.put("greatfruit", Arrays.asList("grapefruit", "great fruit"));
s.put("ur", Arrays.asList("your", "you are"));
s.put("Insta", Arrays.asList("Instagram"));
s.put("IO", Arrays.asList("I/O"));
s.put("wierd", Arrays.asList("weird"));
s.put("Wierd", Arrays.asList("Weird"));
return s;
}
/**
* @since 2.7
*/
@Override
protected List<SuggestedReplacement> getAdditionalTopSuggestions(List<SuggestedReplacement> suggestions, String word) throws IOException {
if (word.length() < 20 && word.matches("[a-zA-Z-]+.?")) {
List<String> prefixes = Arrays.asList("inter", "pre");
for (String prefix : prefixes) {
if (word.startsWith(prefix)) {
String lastPart = word.substring(prefix.length());
if (!isMisspelled(lastPart)) {
// as these are only single words and both the first part and the last part are spelled correctly
// (but the combination is not), it's okay to log the words from a privacy perspective:
logger.info("UNKNOWN-EN: " + word);
}
}
}
}
List<String> curatedSuggestions = new ArrayList<>();
curatedSuggestions.addAll(topSuggestions.getOrDefault(word, Collections.emptyList()));
curatedSuggestions.addAll(topSuggestionsIgnoreCase.getOrDefault(word.toLowerCase(), Collections.emptyList()));
if (!curatedSuggestions.isEmpty()) {
return SuggestedReplacement.convert(curatedSuggestions);
} else if (word.endsWith("ys")) {
String suggestion = word.replaceFirst("ys$", "ies");
if (!speller1.isMisspelled(suggestion)) {
return SuggestedReplacement.convert(Arrays.asList(suggestion));
}
}
return super.getAdditionalTopSuggestions(suggestions, word);
}
@Override
protected Translator getTranslator(GlobalConfig globalConfig) {
return translator;
}
private static class IrregularForms {
final String baseform;
final String posName;
final String formName;
final List<String> forms;
private IrregularForms(String baseform, String posName, String formName, List<String> forms) {
this.baseform = baseform;
this.posName = posName;
this.formName = formName;
this.forms = forms;
}
}
}
|
package org.hildan.livedoc.springmvc.scanner;
import java.util.List;
import org.hildan.livedoc.core.annotations.Api;
import org.hildan.livedoc.core.annotations.ApiOperation;
import org.hildan.livedoc.core.annotations.ApiPathParam;
import org.hildan.livedoc.core.annotations.ApiQueryParam;
import org.hildan.livedoc.core.annotations.ApiRequestBodyType;
import org.hildan.livedoc.core.annotations.ApiResponseBodyType;
import org.hildan.livedoc.core.annotations.ApiVersion;
import org.hildan.livedoc.core.annotations.auth.ApiAuthNone;
import org.hildan.livedoc.core.annotations.errors.ApiError;
import org.hildan.livedoc.core.annotations.errors.ApiErrors;
import org.hildan.livedoc.core.model.doc.ApiAuthType;
import org.hildan.livedoc.core.model.doc.ApiDoc;
import org.hildan.livedoc.core.model.doc.ApiOperationDoc;
import org.hildan.livedoc.core.model.doc.ApiParamDoc;
import org.hildan.livedoc.core.model.doc.ApiVerb;
import org.hildan.livedoc.core.model.doc.auth.ApiAuthDoc;
import org.hildan.livedoc.core.model.doc.headers.ApiHeaderDoc;
import org.hildan.livedoc.core.model.doc.version.ApiVersionDoc;
import org.hildan.livedoc.core.readers.javadoc.JavadocHelper;
import org.hildan.livedoc.springmvc.test.TestUtils;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
public class SpringDocAnnotationScannerTest {
/**
* Test controller.
*/
@SuppressWarnings("unused")
@Api(description = "A spring controller", name = "Spring controller")
@RequestMapping(value = "/api", produces = {MediaType.APPLICATION_JSON_VALUE})
@ApiAuthNone
@ApiVersion(since = "1.0")
@ApiErrors({@ApiError(code = "100", description = "error-100")})
private class SpringController {
/**
* Gets an integer.
*
* @param input
* a test input
*
* @return something
*/
@GetMapping
@ResponseBody
public Integer integer(@RequestParam String input) {
return 0;
}
@ApiOperation(description = "Gets a string", path = "/overridden", verbs = ApiVerb.GET)
@RequestMapping(value = "/string/{name}",
headers = "header=test",
params = "delete",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ApiResponseBodyType
@ResponseBody
public String string(@ApiPathParam(name = "name") @PathVariable("test") String name,
@ApiQueryParam @RequestParam("id") Integer id,
@ApiQueryParam(name = "query", defaultValue = "test") @RequestParam("myquery") Long query,
@RequestBody @ApiRequestBodyType String requestBody) {
return "ok";
}
}
@Test
public void testMergeApiDoc() {
if (!JavadocHelper.getJavadocDescription(SpringController.class).isPresent()) {
fail("Javadoc processor was not enabled");
}
ApiDoc apiDoc = TestUtils.buildDoc(SpringController.class);
assertEquals("A spring controller", apiDoc.getDescription());
assertEquals("Spring controller", apiDoc.getName());
List<ApiOperationDoc> operations = apiDoc.getOperations();
assertEquals(2, operations.size());
checkIntegerOperation(operations.get(0));
checkStringOperation(operations.get(1));
}
private static void checkIntegerOperation(ApiOperationDoc opDoc) {
assertEquals("integer", opDoc.getName());
assertEquals("Gets an integer.", opDoc.getDescription());
assertAuthNone(opDoc.getAuth());
assertVersion(opDoc.getSupportedVersions());
assertFalse(opDoc.getApiErrors().isEmpty());
assertNull(opDoc.getRequestBody());
assertEquals("Integer", opDoc.getResponseBodyType().getOneLineText());
assertEquals(1, opDoc.getVerbs().size());
assertEquals(ApiVerb.GET, opDoc.getVerbs().get(0));
List<ApiParamDoc> queryParameters = opDoc.getQueryParameters();
assertEquals(1, queryParameters.size());
ApiParamDoc apiParamDoc = queryParameters.get(0);
assertEquals("input", apiParamDoc.getName());
assertEquals("a test input", apiParamDoc.getDescription());
assertEquals("true", apiParamDoc.getRequired());
assertNull(apiParamDoc.getDefaultValue());
assertEquals(0, apiParamDoc.getAllowedValues().length);
}
private static void checkStringOperation(ApiOperationDoc opDoc) {
assertEquals("string", opDoc.getName());
assertEquals("Gets a string", opDoc.getDescription());
assertAuthNone(opDoc.getAuth());
assertVersion(opDoc.getSupportedVersions());
assertFalse(opDoc.getApiErrors().isEmpty());
assertEquals("String", opDoc.getRequestBody().getType().getOneLineText());
assertEquals("String", opDoc.getResponseBodyType().getOneLineText());
// livedoc annotations override Spring config
assertEquals("/overridden", opDoc.getPaths().get(0));
assertEquals(1, opDoc.getVerbs().size());
assertEquals(ApiVerb.GET, opDoc.getVerbs().get(0));
assertEquals("application/json", opDoc.getProduces().get(0));
assertEquals("application/json", opDoc.getConsumes().get(0));
assertEquals("201 - Created", opDoc.getResponseStatusCode());
List<ApiHeaderDoc> headers = opDoc.getHeaders();
ApiHeaderDoc header = headers.get(0);
assertEquals("header", header.getName());
assertEquals("test", header.getValues().get(0));
List<ApiParamDoc> queryParameters = opDoc.getQueryParameters();
assertEquals(3, queryParameters.size());
ApiParamDoc apiParamDoc = queryParameters.get(0);
assertEquals("delete", apiParamDoc.getName());
assertEquals("true", apiParamDoc.getRequired());
assertNull(apiParamDoc.getDefaultValue());
assertEquals(0, apiParamDoc.getAllowedValues().length);
apiParamDoc = queryParameters.get(1);
assertEquals("id", apiParamDoc.getName());
assertEquals("true", apiParamDoc.getRequired());
assertNull(apiParamDoc.getDefaultValue());
apiParamDoc = queryParameters.get(2);
assertEquals("query", apiParamDoc.getName());
assertEquals("true", apiParamDoc.getRequired());
assertEquals("test", apiParamDoc.getDefaultValue());
apiParamDoc = opDoc.getPathParameters().get(0);
assertEquals("name", apiParamDoc.getName());
}
private static void assertAuthNone(ApiAuthDoc authDoc) {
assertEquals(ApiAuthType.NONE, authDoc.getType());
}
private static void assertVersion(ApiVersionDoc supportedVersions) {
assertEquals("1.0", supportedVersions.getSince());
assertNull(supportedVersions.getUntil());
}
}
|
package name.abuchen.portfolio.ui.views.panes;
import java.util.ArrayList;
import javax.inject.Inject;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import com.ibm.icu.text.MessageFormat;
import name.abuchen.portfolio.model.Adaptor;
import name.abuchen.portfolio.model.Security;
import name.abuchen.portfolio.money.Values;
import name.abuchen.portfolio.snapshot.QuoteQualityMetrics;
import name.abuchen.portfolio.ui.Messages;
import name.abuchen.portfolio.ui.util.Colors;
import name.abuchen.portfolio.ui.util.FormDataFactory;
import name.abuchen.portfolio.ui.util.viewers.Column;
import name.abuchen.portfolio.ui.util.viewers.ColumnViewerSorter;
import name.abuchen.portfolio.ui.util.viewers.ShowHideColumnHelper;
import name.abuchen.portfolio.ui.views.SecurityQuoteQualityMetricsViewer;
import name.abuchen.portfolio.util.Interval;
public class HistoricalPricesDataQualityPane implements InformationPanePage
{
@Inject
private IPreferenceStore preferences;
private Label completeness;
private Label checkInterval;
private TableViewer missing;
private Security security;
@Override
public String getLabel()
{
return Messages.GroupLabelDataQuality;
}
@Override
public Control createViewControl(Composite parent)
{
Composite container = new Composite(parent, SWT.NONE);
container.setBackground(Colors.WHITE);
FormLayout layout = new FormLayout();
layout.marginHeight = layout.marginWidth = 5;
container.setLayout(layout);
Label lCompleteness = new Label(container, SWT.NONE);
lCompleteness.setText(Messages.ColumnMetricCompleteness);
lCompleteness.setToolTipText(Messages.ColumnMetricCompleteness_Description);
completeness = new Label(container, SWT.NONE);
completeness.setToolTipText(Messages.ColumnMetricCompleteness_Description);
checkInterval = new Label(container, SWT.NONE);
Composite table = createTable(container);
FormDataFactory.startingWith(completeness, lCompleteness).right(new FormAttachment(100))
.thenBelow(checkInterval).left(new FormAttachment(0)).right(new FormAttachment(100))
.thenBelow(table)
.bottom(new FormAttachment(100));
return container;
}
protected Composite createTable(Composite parent)
{
Composite container = new Composite(parent, SWT.NONE);
TableColumnLayout layout = new TableColumnLayout();
container.setLayout(layout);
missing = new TableViewer(container, SWT.FULL_SELECTION);
ShowHideColumnHelper support = new ShowHideColumnHelper(
SecurityQuoteQualityMetricsViewer.class.getSimpleName() + "@missing", //$NON-NLS-1$
preferences, missing, layout);
Column column = new Column(Messages.ColumnDate, SWT.None, 300);
column.setLabelProvider(new ColumnLabelProvider()
{
@Override
public String getText(Object element)
{
Interval interval = (Interval) element;
if (interval.getStart().equals(interval.getEnd()))
return Values.Date.format(interval.getStart());
else
return MessageFormat.format(Messages.LabelDateXToY, Values.Date.format(interval.getStart()),
Values.Date.format(interval.getEnd()));
}
});
column.setSorter(ColumnViewerSorter.create(e -> ((Interval) e).getStart()), SWT.UP);
support.addColumn(column);
support.createColumns();
missing.getTable().setHeaderVisible(true);
missing.getTable().setLinesVisible(true);
missing.setContentProvider(ArrayContentProvider.getInstance());
return container;
}
@Override
public void setInput(Object input)
{
if (completeness == null || completeness.isDisposed())
return;
security = Adaptor.adapt(Security.class, input);
if (security == null)
{
completeness.setText(""); //$NON-NLS-1$
checkInterval.setText(""); //$NON-NLS-1$
missing.setInput(new ArrayList<>());
}
else
{
QuoteQualityMetrics metrics = new QuoteQualityMetrics(security);
completeness.setText(Values.Percent2.format(metrics.getCompleteness()));
checkInterval.setText(metrics.getCheckInterval()
.map(i -> MessageFormat.format(Messages.LabelMetricCheckInterval,
Values.Date.format(i.getStart()), Values.Date.format(i.getEnd())))
.orElse("")); //$NON-NLS-1$
missing.setInput(metrics.getMissingIntervals());
}
}
@Override
public void onRecalculationNeeded()
{
if (security != null)
setInput(security);
}
}
|
package com.yahoo.vespa.hosted.node.verification.commons;
import com.yahoo.vespa.hosted.node.verification.mock.MockCommandExecutor;
import com.yahoo.vespa.hosted.node.verification.commons.HostURLGenerator;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class HostURLGeneratorTest {
private MockCommandExecutor mockCommandExecutor;
private static final String CAT_NODE_HOST_NAME_PATH = "cat src/test/java/com/yahoo/vespa/hosted/node/verification/spec/resources/hostURLGeneratorTest";
private static final String CAT_CONFIG_SERVER_HOST_NAME_PATH = "cat src/test/java/com/yahoo/vespa/hosted/node/verification/spec/resources/nodeHostNameOutput";
private static final String CAT_WRONG_HOSTNAME_PATH = "cat src/test/java/com/yahoo/vespa/hosted/node/verification/spec/resources/hostURLGeneratorExceptionTest";
private static final String CONFIG_SERVER_HOSTNAME = "http://cfg1.prod.region1:4080";
private static final String NODE_HOSTNAME_PREFIX = "/nodes/v2/node/";
private static final String EXPECTED_HOSTNAME = "expected.hostname";
@Before
public void setup() {
mockCommandExecutor = new MockCommandExecutor();
}
@Test
public void generateNodeInfoUrl_find_config_server_test_if_url_is_formatted_correctly() throws Exception {
mockCommandExecutor.addCommand(CAT_CONFIG_SERVER_HOST_NAME_PATH);
mockCommandExecutor.addCommand(CAT_NODE_HOST_NAME_PATH);
ArrayList<URL> url = HostURLGenerator.generateNodeInfoUrl(mockCommandExecutor);
String expectedUrl = CONFIG_SERVER_HOSTNAME + NODE_HOSTNAME_PREFIX + EXPECTED_HOSTNAME;
String actualUrl = url.get(0).toString();
assertEquals(expectedUrl, actualUrl);
}
@Test
public void generateNodeInfoURL_expected_IOException() {
try {
mockCommandExecutor.addCommand(CAT_CONFIG_SERVER_HOST_NAME_PATH);
mockCommandExecutor.addCommand(CAT_WRONG_HOSTNAME_PATH);
HostURLGenerator.generateNodeInfoUrl(mockCommandExecutor);
fail("Expected an IOException to be thrown");
} catch (IOException e) {
String expectedExceptionMessage = "Unexpected output from \"hostname\" command.";
assertEquals(expectedExceptionMessage, e.getMessage());
}
}
@Test
public void generateNodeInfoUrl_retrieve_config_server_as_parameter_test_if_url_is_formatted_correctly() throws Exception {
mockCommandExecutor.addCommand(CAT_NODE_HOST_NAME_PATH);
String configServerHostname = "cfg1.prod.corp-us-east-1.vespahosted.corp.bf1.yahoo.com";
ArrayList<URL> actualUrls = HostURLGenerator.generateNodeInfoUrl(mockCommandExecutor, configServerHostname);
String expectedUrl = CONFIG_SERVER_HOSTNAME + NODE_HOSTNAME_PREFIX + EXPECTED_HOSTNAME;
String actualUrl = actualUrls.get(0).toString();
assertEquals(expectedUrl, actualUrl);
}
@Test
public void buildNodeInfoURL_should_add_protocol_and_port_in_front_when_protocol_is_absent() throws IOException {
String configServerHostName = "www.yahoo.com";
String nodeHostName = "index.html";
String nodeHostnamePrefix = "/nodes/v2/node/";
String portNumber = ":4080";
String expectedUrl = "http://" + configServerHostName + portNumber + nodeHostnamePrefix + nodeHostName;
assertEquals(expectedUrl, HostURLGenerator.buildNodeInfoURL(configServerHostName, nodeHostName).toString());
}
@Test
public void buildNodeInfoURL_should_not_add_protocol_and_port_in_front_when_protocol_already_exists() throws IOException {
String configServerHostName = "http:
String nodeHostName = "index.html";
String nodeHostnamePrefix = "/nodes/v2/node/";
String expectedUrl = configServerHostName + nodeHostnamePrefix + nodeHostName;
assertEquals(expectedUrl, HostURLGenerator.buildNodeInfoURL(configServerHostName, nodeHostName).toString());
}
}
|
package org.nuxeo.drive.service;
import java.security.Principal;
import org.nuxeo.drive.adapter.FolderItem;
import org.nuxeo.drive.service.impl.DefaultTopLevelFolderItemFactory;
import org.nuxeo.ecm.core.api.ClientException;
/**
* Interface for the classes contributed to the
* {@code topLevelFolderItemFactory} extension point of the
* {@link FileSystemItemAdapterService}.
* <p>
* Allows to get the top level {@link FolderItem} for a given user.
*
* @author Antoine Taillefer
* @see DefaultTopLevelFolderItemFactory
*/
public interface TopLevelFolderItemFactory extends VirtualFolderItemFactory {
FolderItem getTopLevelFolderItem(Principal principal)
throws ClientException;
}
|
package org.metaborg.spoofax.core.language;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelectInfo;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.MetaborgConstants;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.analysis.AnalyzerFacet;
import org.metaborg.core.config.ConfigRequest;
import org.metaborg.core.config.ILanguageComponentConfig;
import org.metaborg.core.config.ILanguageComponentConfigService;
import org.metaborg.core.context.ContextFacet;
import org.metaborg.core.context.IContextFactory;
import org.metaborg.core.context.IContextStrategy;
import org.metaborg.core.context.ProjectContextStrategy;
import org.metaborg.core.language.ILanguageComponent;
import org.metaborg.core.language.ILanguageDiscoveryRequest;
import org.metaborg.core.language.ILanguageDiscoveryService;
import org.metaborg.core.language.ILanguageService;
import org.metaborg.core.language.IdentificationFacet;
import org.metaborg.core.language.LanguageContributionIdentifier;
import org.metaborg.core.language.LanguageCreationRequest;
import org.metaborg.core.language.LanguageIdentifier;
import org.metaborg.core.language.ResourceExtensionFacet;
import org.metaborg.core.language.ResourceExtensionsIdentifier;
import org.metaborg.core.messages.IMessage;
import org.metaborg.core.syntax.ParseFacet;
import org.metaborg.spoofax.core.action.ActionFacet;
import org.metaborg.spoofax.core.action.ActionFacetFromESV;
import org.metaborg.spoofax.core.analysis.AnalysisFacet;
import org.metaborg.spoofax.core.analysis.AnalysisFacetFromESV;
import org.metaborg.spoofax.core.analysis.ISpoofaxAnalyzer;
import org.metaborg.spoofax.core.analysis.legacy.StrategoAnalyzer;
import org.metaborg.spoofax.core.analysis.taskengine.TaskEngineAnalyzer;
import org.metaborg.spoofax.core.context.ContextFacetFromESV;
import org.metaborg.spoofax.core.context.IndexTaskContextFactory;
import org.metaborg.spoofax.core.context.LegacyContextFactory;
import org.metaborg.spoofax.core.esv.ESVReader;
import org.metaborg.spoofax.core.outline.OutlineFacet;
import org.metaborg.spoofax.core.outline.OutlineFacetFromESV;
import org.metaborg.spoofax.core.stratego.StrategoRuntimeFacet;
import org.metaborg.spoofax.core.stratego.StrategoRuntimeFacetFromESV;
import org.metaborg.spoofax.core.style.StylerFacet;
import org.metaborg.spoofax.core.style.StylerFacetFromESV;
import org.metaborg.spoofax.core.syntax.ParseFacetFromESV;
import org.metaborg.spoofax.core.syntax.SyntaxFacet;
import org.metaborg.spoofax.core.syntax.SyntaxFacetFromESV;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.spoofax.core.tracing.HoverFacet;
import org.metaborg.spoofax.core.tracing.ResolverFacet;
import org.metaborg.spoofax.core.tracing.ResolverFacetFromESV;
import org.metaborg.util.iterators.Iterables2;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.terms.IStrategoAppl;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.terms.ParseError;
import org.spoofax.terms.io.binary.TermReader;
import com.google.common.base.Joiner;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.inject.Inject;
public class LanguageDiscoveryService implements ILanguageDiscoveryService {
private static final ILogger logger = LoggerUtils.logger(LanguageDiscoveryService.class);
private final ILanguageService languageService;
private final ILanguageComponentConfigService componentConfigService;
private final ITermFactoryService termFactoryService;
private final Map<String, IContextFactory> contextFactories;
private final Map<String, IContextStrategy> contextStrategies;
private final Map<String, ISpoofaxAnalyzer> analyzers;
@Inject public LanguageDiscoveryService(ILanguageService languageService,
ILanguageComponentConfigService componentConfigService, ITermFactoryService termFactoryService,
Map<String, IContextFactory> contextFactories, Map<String, IContextStrategy> contextStrategies,
Map<String, ISpoofaxAnalyzer> analyzers) {
this.languageService = languageService;
this.componentConfigService = componentConfigService;
this.termFactoryService = termFactoryService;
this.contextFactories = contextFactories;
this.contextStrategies = contextStrategies;
this.analyzers = analyzers;
}
@Override public Collection<ILanguageDiscoveryRequest> request(FileObject location) throws MetaborgException {
final Collection<ILanguageDiscoveryRequest> requests = Lists.newLinkedList();
final FileObject[] configFiles;
try {
configFiles = location.findFiles(new FileSelector() {
@Override public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception {
final String baseName = fileInfo.getFile().getName().getBaseName();
return !baseName.equals("bin");
}
@Override public boolean includeFile(FileSelectInfo fileInfo) throws Exception {
return fileInfo.getFile().getName().getBaseName().equals(MetaborgConstants.FILE_COMPONENT_CONFIG);
}
});
} catch(FileSystemException e) {
throw new MetaborgException("Searching for language components failed unexpectedly", e);
}
if(configFiles == null || configFiles.length == 0) {
return requests;
}
final Multimap<FileName, FileName> locToConfigs = ArrayListMultimap.create();
final Map<FileName, FileObject> nameToFile = Maps.newHashMap();
for(FileObject configFile : configFiles) {
try {
final FileName configName = configFile.getName();
final FileObject languageLoc = configFile.getParent().getParent();
final FileName languageLocName = languageLoc.getName();
locToConfigs.put(languageLocName, configName);
nameToFile.put(languageLocName, languageLoc);
} catch(FileSystemException e) {
logger.error("Could not resolve parent directory of config file {}, skipping", e, configFile);
continue;
}
}
final Collection<FileObject> languageLocations = Lists.newArrayList();
for(Entry<FileName, Collection<FileName>> configEntry : locToConfigs.asMap().entrySet()) {
final FileName languageLocName = configEntry.getKey();
final FileObject languageLoc = nameToFile.get(languageLocName);
final Collection<FileName> configLocNames = configEntry.getValue();
if(configLocNames.size() > 1) {
final String message = logger.format("Found multiple config files at location {}: {}", languageLocName,
Joiner.on(", ").join(configLocNames));
requests.add(new LanguageDiscoveryRequest(languageLoc, message));
continue;
} else {
languageLocations.add(languageLoc);
}
}
for(FileObject languageLocation : languageLocations) {
final Collection<String> errors = Lists.newLinkedList();
final Collection<Throwable> exceptions = Lists.newLinkedList();
final ConfigRequest<ILanguageComponentConfig> configRequest = componentConfigService.get(languageLocation);
if(!configRequest.valid()) {
for(IMessage message : configRequest.errors()) {
errors.add(message.message());
final Throwable exception = message.exception();
if(exception != null) {
exceptions.add(exception);
}
}
}
final ILanguageComponentConfig config = configRequest.config();
if(config == null) {
final String message =
logger.format("Cannot retrieve language component configuration at {}", languageLocation);
errors.add(message);
requests.add(new LanguageDiscoveryRequest(languageLocation, errors, exceptions));
continue;
}
final IStrategoAppl esvTerm;
try {
final FileObject esvFile = languageLocation.resolveFile("target/metaborg/editor.esv.af");
if(!esvFile.exists()) {
esvTerm = null;
} else {
esvTerm = esvTerm(languageLocation, esvFile);
}
} catch(ParseError | IOException | MetaborgException e) {
exceptions.add(e);
requests.add(new LanguageDiscoveryRequest(languageLocation, errors, exceptions));
continue;
}
SyntaxFacet syntaxFacet = null;
StrategoRuntimeFacet strategoRuntimeFacet = null;
if(esvTerm != null) {
try {
syntaxFacet = SyntaxFacetFromESV.create(esvTerm, languageLocation);
if(syntaxFacet != null) {
Iterables.addAll(errors, syntaxFacet.available());
}
} catch(FileSystemException e) {
exceptions.add(e);
}
try {
strategoRuntimeFacet = StrategoRuntimeFacetFromESV.create(esvTerm, languageLocation);
if(strategoRuntimeFacet != null) {
Iterables.addAll(errors, strategoRuntimeFacet.available());
}
} catch(FileSystemException e) {
exceptions.add(e);
}
}
final ILanguageDiscoveryRequest request;
if(errors.isEmpty() && exceptions.isEmpty()) {
request =
new LanguageDiscoveryRequest(languageLocation, config, esvTerm, syntaxFacet, strategoRuntimeFacet);
} else {
request = new LanguageDiscoveryRequest(languageLocation, errors, exceptions);
}
requests.add(request);
}
return requests;
}
@Override public ILanguageComponent discover(ILanguageDiscoveryRequest request) throws MetaborgException {
return createComponent((LanguageDiscoveryRequest) request);
}
@Override public Collection<ILanguageComponent> discover(Iterable<ILanguageDiscoveryRequest> requests)
throws MetaborgException {
final Collection<ILanguageComponent> components = Lists.newLinkedList();
for(ILanguageDiscoveryRequest request : requests) {
components.add(discover(request));
}
return components;
}
private IStrategoAppl esvTerm(FileObject location, FileObject esvFile)
throws ParseError, IOException, MetaborgException {
final TermReader reader =
new TermReader(termFactoryService.getGeneric().getFactoryWithStorageType(IStrategoTerm.MUTABLE));
final IStrategoTerm term = reader.parseFromStream(esvFile.getContent().getInputStream());
if(term.getTermType() != IStrategoTerm.APPL) {
final String message = logger.format(
"Cannot discover language at {}, ESV file at {} does not contain a valid ESV term", location, esvFile);
throw new MetaborgException(message);
}
return (IStrategoAppl) term;
}
private ILanguageComponent createComponent(LanguageDiscoveryRequest discoveryRequest) throws MetaborgException {
final FileObject location = discoveryRequest.location();
if(!discoveryRequest.available()) {
throw new MetaborgException(discoveryRequest.toString());
}
final ILanguageComponentConfig config = discoveryRequest.config();
logger.debug("Creating language component for {}", location);
final LanguageIdentifier identifier = config.identifier();
final Collection<LanguageContributionIdentifier> langContribs = discoveryRequest.config().langContribs();
if(langContribs.isEmpty()) {
langContribs.add(new LanguageContributionIdentifier(identifier, config.name()));
}
final LanguageCreationRequest request = languageService.create(identifier, location, langContribs, config);
final SyntaxFacet syntaxFacet = discoveryRequest.syntaxFacet();
if(syntaxFacet != null) {
request.addFacet(syntaxFacet);
}
final StrategoRuntimeFacet strategoRuntimeFacet = discoveryRequest.strategoRuntimeFacet();
if(strategoRuntimeFacet != null) {
request.addFacet(strategoRuntimeFacet);
}
final IStrategoAppl esvTerm = discoveryRequest.esvTerm();
if(esvTerm != null) {
final String[] extensions = extensions(esvTerm);
if(extensions.length != 0) {
final Iterable<String> extensionsIterable = Iterables2.from(extensions);
final IdentificationFacet identificationFacet =
new IdentificationFacet(new ResourceExtensionsIdentifier(extensionsIterable));
request.addFacet(identificationFacet);
final ResourceExtensionFacet resourceExtensionsFacet = new ResourceExtensionFacet(extensionsIterable);
request.addFacet(resourceExtensionsFacet);
}
if(ParseFacetFromESV.hasParser(esvTerm)) {
request.addFacet(ParseFacetFromESV.create(esvTerm));
} else {
request.addFacet(new ParseFacet("jsglr"));
}
final boolean hasContext = ContextFacetFromESV.hasContext(esvTerm);
final boolean hasAnalysis = AnalysisFacetFromESV.hasAnalysis(esvTerm);
final IContextFactory contextFactory;
final ISpoofaxAnalyzer analyzer;
final AnalysisFacet analysisFacet;
if(!hasContext && !hasAnalysis) {
contextFactory = contextFactory(LegacyContextFactory.name);
analyzer = null;
analysisFacet = null;
} else if(hasContext && !hasAnalysis) {
final String type = ContextFacetFromESV.type(esvTerm);
contextFactory = contextFactory(type);
analyzer = null;
analysisFacet = null;
} else if(!hasContext && hasAnalysis) {
final String analysisType = AnalysisFacetFromESV.type(esvTerm);
assert analysisType != null : "Analyzer type cannot be null because hasAnalysis is true, no null check is needed.";
switch(analysisType) {
default:
case StrategoAnalyzer.name:
contextFactory = contextFactory(LegacyContextFactory.name);
break;
case TaskEngineAnalyzer.name:
contextFactory = contextFactory(IndexTaskContextFactory.name);
break;
}
analyzer = analyzers.get(analysisType);
analysisFacet = AnalysisFacetFromESV.create(esvTerm);
} else { // Both context and analysis are specified.
final String contextType = ContextFacetFromESV.type(esvTerm);
contextFactory = contextFactory(contextType);
final String analysisType = AnalysisFacetFromESV.type(esvTerm);
assert analysisType != null : "Analyzer type cannot be null because hasAnalysis is true, no null check is needed.";
analyzer = analyzers.get(analysisType);
analysisFacet = AnalysisFacetFromESV.create(esvTerm);
}
if(contextFactory != null) {
final IContextStrategy contextStrategy = contextStrategy(ProjectContextStrategy.name);
request.addFacet(new ContextFacet(contextFactory, contextStrategy));
}
if(analyzer != null) {
request.addFacet(new AnalyzerFacet<>(analyzer));
}
if(analysisFacet != null) {
request.addFacet(analysisFacet);
}
final ActionFacet menusFacet = ActionFacetFromESV.create(esvTerm);
if(menusFacet != null) {
request.addFacet(menusFacet);
}
final StylerFacet stylerFacet = StylerFacetFromESV.create(esvTerm);
if(stylerFacet != null) {
request.addFacet(stylerFacet);
}
final ResolverFacet resolverFacet = ResolverFacetFromESV.createResolver(esvTerm);
if(resolverFacet != null) {
request.addFacet(resolverFacet);
}
final HoverFacet hoverFacet = ResolverFacetFromESV.createHover(esvTerm);
if(hoverFacet != null) {
request.addFacet(hoverFacet);
}
final OutlineFacet outlineFacet = OutlineFacetFromESV.create(esvTerm);
if(outlineFacet != null) {
request.addFacet(outlineFacet);
}
}
return languageService.add(request);
}
private static String[] extensions(IStrategoAppl document) {
final String extensionsStr = ESVReader.getProperty(document, "Extensions");
if(extensionsStr == null) {
return new String[0];
}
return extensionsStr.split(",");
}
private @Nullable IContextFactory contextFactory(@Nullable String name) throws MetaborgException {
if(name == null) {
return null;
}
final IContextFactory contextFactory = contextFactories.get(name);
if(contextFactory == null) {
final String message = logger.format("Could not get context factory with name {}", name);
throw new MetaborgException(message);
}
return contextFactory;
}
private IContextStrategy contextStrategy(String name) throws MetaborgException {
final IContextStrategy contextStrategy = contextStrategies.get(name);
if(contextStrategy == null) {
final String message = logger.format("Could not get context strategy with name {}", name);
throw new MetaborgException(message);
}
return contextStrategy;
}
}
|
package com.intellij.util.indexing.impl.perFileVersion;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.vfs.newvfs.FileAttribute;
import com.intellij.openapi.vfs.newvfs.persistent.FSRecords;
import com.intellij.util.indexing.*;
import com.intellij.util.io.DataInputOutputUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public final class PersistentSubIndexerRetriever<SubIndexerType, SubIndexerVersion> implements Closeable {
private static final String INDEXED_VERSIONS = "indexed_versions";
private static final int UNINDEXED_STATE = -2;
@NotNull
private final PersistentSubIndexerVersionEnumerator<SubIndexerVersion> myPersistentVersionEnumerator;
@NotNull
private final FileAttribute myFileAttribute;
@NotNull
private final CompositeDataIndexer<?, ?, SubIndexerType, SubIndexerVersion> myIndexer;
public PersistentSubIndexerRetriever(@NotNull ID<?, ?> id,
int indexVersion,
@NotNull CompositeDataIndexer<?, ?, SubIndexerType, SubIndexerVersion> indexer) throws IOException {
this(IndexInfrastructure.getIndexRootDir(id), id.getName(), indexVersion, indexer);
}
@TestOnly
PersistentSubIndexerRetriever(@NotNull File root,
@NotNull String indexName,
int indexVersion,
@NotNull CompositeDataIndexer<?, ?, SubIndexerType, SubIndexerVersion> indexer) throws IOException {
Path versionMapRoot = root.toPath().resolve(versionMapRoot());
myFileAttribute = getFileAttribute(indexName, indexVersion);
myIndexer = indexer;
myPersistentVersionEnumerator = new PersistentSubIndexerVersionEnumerator<>(
versionMapRoot.resolve(INDEXED_VERSIONS).toFile(),
indexer.getSubIndexerVersionDescriptor());
}
public void clear() throws IOException {
myPersistentVersionEnumerator.clear();
}
@Override
public void close() throws IOException {
myPersistentVersionEnumerator.close();
}
public void flush() throws IOException {
myPersistentVersionEnumerator.flush();
}
private static Path versionMapRoot() {
return Paths.get(".perFileVersion", INDEXED_VERSIONS);
}
public void setIndexedState(int fileId, @NotNull IndexedFile file) throws IOException {
int indexerId = ProgressManager.getInstance().computeInNonCancelableSection(() -> getFileIndexerId(file));
setFileIndexerId(fileId, indexerId);
}
public void setUnindexedState(int fileId) throws IOException {
setFileIndexerId(fileId, UNINDEXED_STATE);
}
private void setFileIndexerId(int fileId, int indexerId) throws IOException {
try (DataOutputStream stream = FSRecords.writeAttribute(fileId, myFileAttribute)) {
DataInputOutputUtil.writeINT(stream, indexerId);
}
}
public FileIndexingState getSubIndexerState(int fileId, @NotNull IndexedFile file) throws IOException {
try (DataInputStream stream = FSRecords.readAttributeWithLock(fileId, myFileAttribute)) {
if (stream != null) {
int currentIndexedVersion = DataInputOutputUtil.readINT(stream);
if (currentIndexedVersion == UNINDEXED_STATE) {
return FileIndexingState.NOT_INDEXED;
}
int actualVersion = getFileIndexerId(file);
return actualVersion == currentIndexedVersion ? FileIndexingState.UP_TO_DATE : FileIndexingState.OUT_DATED;
}
return FileIndexingState.NOT_INDEXED;
}
}
public int getFileIndexerId(@NotNull IndexedFile file) throws IOException {
SubIndexerVersion version = getVersion(file);
if (version == null) return UNINDEXED_STATE;
return myPersistentVersionEnumerator.enumerate(version);
}
@Nullable
public SubIndexerVersion getVersion(@NotNull IndexedFile file) {
SubIndexerType type = myIndexer.calculateSubIndexer(file);
if (type == null) return null;
return myIndexer.getSubIndexerVersion(type);
}
private static final Map<Pair<String, Integer>, FileAttribute> ourAttributes = new HashMap<>();
private static FileAttribute getFileAttribute(String name, int version) {
synchronized (ourAttributes) {
return ourAttributes.computeIfAbsent(new Pair<>(name, version), __ -> new FileAttribute(name + ".index.version", version, false));
}
}
}
|
package com.redhat.ceylon.eclipse.core.builder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;
import com.redhat.ceylon.common.Constants;
import com.redhat.ceylon.common.config.CeylonConfig;
import com.redhat.ceylon.common.config.ConfigParser;
import com.redhat.ceylon.common.config.ConfigWriter;
import com.redhat.ceylon.common.config.DefaultToolOptions;
import com.redhat.ceylon.common.config.Repositories;
import com.redhat.ceylon.common.config.Repositories.Repository;
import com.redhat.ceylon.eclipse.ui.CeylonEncodingSynchronizer;
public class CeylonProjectConfig {
private static final Map<IProject, CeylonProjectConfig> PROJECT_CONFIGS = new HashMap<IProject, CeylonProjectConfig>();
public static CeylonProjectConfig get(IProject project) {
CeylonProjectConfig projectConfig = PROJECT_CONFIGS.get(project);
if (projectConfig == null) {
projectConfig = new CeylonProjectConfig(project);
PROJECT_CONFIGS.put(project, projectConfig);
}
return projectConfig;
}
public static void remove(IProject project) {
PROJECT_CONFIGS.remove(project);
}
private final IProject project;
private CeylonConfig mergedConfig;
private CeylonConfig projectConfig;
private Repositories mergedRepositories;
private Repositories projectRepositories;
private String transientOutputRepo;
private List<String> transientProjectLocalRepos;
private List<String> transientProjectRemoteRepos;
private boolean isOfflineChanged = false;
private boolean isEncodingChanged = false;
private Boolean transientOffline;
private String transientEncoding;
private List<String> transientSourceDirectories;
private List<String> transientResourceDirectories;
private CeylonProjectConfig(IProject project) {
this.project = project;
initMergedConfig();
initProjectConfig();
}
private void initMergedConfig() {
mergedConfig = CeylonConfig.createFromLocalDir(project.getLocation().toFile());
mergedRepositories = Repositories.withConfig(mergedConfig);
}
private void initProjectConfig() {
projectConfig = new CeylonConfig();
File projectConfigFile = getProjectConfigFile();
if (projectConfigFile.exists() && projectConfigFile.isFile()) {
try {
projectConfig = ConfigParser.loadConfigFromFile(projectConfigFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
projectRepositories = Repositories.withConfig(projectConfig);
}
public Repositories getMergedRepositories() {
return mergedRepositories;
}
public Repositories getProjectRepositories() {
return projectRepositories;
}
public String getOutputRepo() {
Repository outputRepo = mergedRepositories.getOutputRepository();
return outputRepo.getUrl();
}
public void setOutputRepo(String outputRepo) {
transientOutputRepo = outputRepo;
}
public IPath getOutputRepoPath() {
Repository outputRepo = mergedRepositories.getOutputRepository();
String outputRepoUrl = outputRepo.getUrl();
IPath outputRepoPath;
if (outputRepoUrl.startsWith("./") || outputRepoUrl.startsWith(".\\")) {
outputRepoPath = project.getFullPath().append(outputRepoUrl.substring(2));
} else {
outputRepoPath = project.getFullPath().append(outputRepoUrl);
}
return outputRepoPath;
}
public List<String> getGlobalLookupRepos() {
return toRepositoriesUrlList(mergedRepositories.getGlobalLookupRepositories());
}
public List<String> getOtherRemoteRepos() {
return toRepositoriesUrlList(mergedRepositories.getOtherLookupRepositories());
}
public List<String> getProjectLocalRepos() {
return toRepositoriesUrlList(projectRepositories.getRepositoriesByType(Repositories.REPO_TYPE_LOCAL_LOOKUP));
}
public void setProjectLocalRepos(List<String> projectLocalRepos) {
transientProjectLocalRepos = projectLocalRepos;
}
public List<String> getProjectRemoteRepos() {
return toRepositoriesUrlList(projectRepositories.getRepositoriesByType(Repositories.REPO_TYPE_REMOTE_LOOKUP));
}
public void setProjectRemoteRepos(List<String> projectRemoteRepos) {
transientProjectRemoteRepos = projectRemoteRepos;
}
public String getEncoding() {
return mergedConfig.getOption(DefaultToolOptions.DEFAULTS_ENCODING);
}
public String getProjectEncoding() {
return projectConfig.getOption(DefaultToolOptions.DEFAULTS_ENCODING);
}
public void setProjectEncoding(String encoding) {
this.isEncodingChanged = true;
this.transientEncoding = encoding;
}
public boolean isOffline() {
return mergedConfig.getBoolOption(DefaultToolOptions.DEFAULTS_OFFLINE, false);
}
public Boolean isProjectOffline() {
return projectConfig.getBoolOption(DefaultToolOptions.DEFAULTS_OFFLINE);
}
public void setProjectOffline(Boolean offline) {
this.isOfflineChanged = true;
this.transientOffline = offline;
}
public List<String> getSourceDirectories() {
return getConfigSourceDirectories(mergedConfig);
}
public List<String> getProjectSourceDirectories() {
return getConfigSourceDirectories(projectConfig);
}
private List<String> getConfigSourceDirectories(CeylonConfig config) {
return getConfigValuesAsList(config, DefaultToolOptions.COMPILER_SOURCE, Constants.DEFAULT_SOURCE_DIR);
}
public void setProjectSourceDirectories(List<String> dirs) {
transientSourceDirectories = dirs;
}
public List<String> getReourceDirectories() {
return getConfigResourceDirectories(mergedConfig);
}
public List<String> getProjectResourceDirectories() {
return getConfigResourceDirectories(projectConfig);
}
private List<String> getConfigResourceDirectories(CeylonConfig config) {
return getConfigValuesAsList(config, DefaultToolOptions.COMPILER_RESOURCE, Constants.DEFAULT_RESOURCE_DIR);
}
public void setProjectReourceDirectories(List<String> dirs) {
transientResourceDirectories = dirs;
}
public void refresh() {
initMergedConfig();
initProjectConfig();
isOfflineChanged = false;
isEncodingChanged = false;
transientEncoding = null;
transientOffline = null;
transientOutputRepo = null;
transientProjectLocalRepos = null;
transientProjectRemoteRepos = null;
transientSourceDirectories = null;
transientResourceDirectories = null;
}
public void save() {
initProjectConfig();
String oldOutputRepo = getOutputRepo();
List<String> oldProjectLocalRepos = getProjectLocalRepos();
List<String> oldProjectRemoteRepos = getProjectRemoteRepos();
List<String> oldSourceDirectories = getProjectSourceDirectories();
List<String> oldResourceDirectories = getProjectResourceDirectories();
boolean isOutputRepoChanged = transientOutputRepo != null && !transientOutputRepo.equals(oldOutputRepo);
boolean isProjectLocalReposChanged = transientProjectLocalRepos != null && !transientProjectLocalRepos.equals(oldProjectLocalRepos);
boolean isProjectRemoteReposChanged = transientProjectRemoteRepos != null && !transientProjectRemoteRepos.equals(oldProjectRemoteRepos);
boolean isSourceDirsChanged = transientSourceDirectories != null && !transientSourceDirectories.equals(oldSourceDirectories);
boolean isResourceDirsChanged = transientResourceDirectories != null && !transientResourceDirectories.equals(oldResourceDirectories);
if (isOutputRepoChanged) {
deleteOldOutputFolder(oldOutputRepo);
createNewOutputFolder();
} else if (transientOutputRepo != null) {
// fix #422: output folder must be create for new projects
IFolder newOutputRepoFolder = project.getFolder(removeCurrentDirPrefix(transientOutputRepo));
if (!newOutputRepoFolder.exists()) {
createNewOutputFolder();
}
}
if (isOutputRepoChanged || isProjectLocalReposChanged || isProjectRemoteReposChanged
|| isOfflineChanged || isEncodingChanged || isSourceDirsChanged || isResourceDirsChanged) {
try {
if (isOutputRepoChanged) {
Repository newOutputRepo = new Repositories.SimpleRepository("", transientOutputRepo, null);
projectRepositories.setRepositoriesByType(Repositories.REPO_TYPE_OUTPUT, new Repository[] { newOutputRepo });
}
if (isProjectLocalReposChanged) {
Repository[] newLocalRepos = toRepositoriesArray(transientProjectLocalRepos);
projectRepositories.setRepositoriesByType(Repositories.REPO_TYPE_LOCAL_LOOKUP, newLocalRepos);
}
if (isProjectRemoteReposChanged) {
Repository[] newRemoteRepos = toRepositoriesArray(transientProjectRemoteRepos);
projectRepositories.setRepositoriesByType(Repositories.REPO_TYPE_REMOTE_LOOKUP, newRemoteRepos);
}
if (isOfflineChanged) {
if (transientOffline != null) {
projectConfig.setBoolOption(DefaultToolOptions.DEFAULTS_OFFLINE, transientOffline);
} else {
projectConfig.removeOption(DefaultToolOptions.DEFAULTS_OFFLINE);
}
}
if (isEncodingChanged) {
if (transientEncoding != null) {
projectConfig.setOption(DefaultToolOptions.DEFAULTS_ENCODING, transientEncoding);
} else {
projectConfig.removeOption(DefaultToolOptions.DEFAULTS_ENCODING);
}
}
if (isSourceDirsChanged) {
setConfigValuesAsList(projectConfig, DefaultToolOptions.COMPILER_SOURCE, transientSourceDirectories);
}
if (isResourceDirsChanged) {
setConfigValuesAsList(projectConfig, DefaultToolOptions.COMPILER_RESOURCE, transientResourceDirectories);
}
ConfigWriter.write(projectConfig, getProjectConfigFile());
refresh();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private File getProjectConfigFile() {
File projectCeylonDir = new File(project.getLocation().toFile(), ".ceylon");
File projectCeylonConfigFile = new File(projectCeylonDir, "config");
return projectCeylonConfigFile;
}
private List<String> toRepositoriesUrlList(Repository[] repositories) {
List<String> result = new ArrayList<String>();
if (repositories != null) {
for (Repository repository : repositories) {
result.add(repository.getUrl());
}
}
return result;
}
private Repository[] toRepositoriesArray(List<String> repositoriesUrl) {
Repository[] repositories = new Repository[repositoriesUrl.size()];
for (int i = 0; i < repositoriesUrl.size(); i++) {
repositories[i] = new Repositories.SimpleRepository("", repositoriesUrl.get(i), null);
}
return repositories;
}
private void deleteOldOutputFolder(String oldOutputRepo) {
IFolder oldOutputRepoFolder = project.getFolder(removeCurrentDirPrefix(oldOutputRepo));
if( oldOutputRepoFolder.exists() ) {
boolean remove = MessageDialog.openQuestion(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Changing Ceylon output repository",
"The Ceylon output repository has changed. Do you want to remove the old output repository folder '" +
oldOutputRepoFolder.getFullPath().toString() + "' and all its contents?");
if (remove) {
try {
oldOutputRepoFolder.delete(true, null);
} catch (CoreException e) {
e.printStackTrace();
}
}
}
if (oldOutputRepoFolder.exists() && oldOutputRepoFolder.isHidden()) {
try {
oldOutputRepoFolder.setHidden(false);
} catch (CoreException e) {
e.printStackTrace();
}
}
}
private void createNewOutputFolder() {
IFolder newOutputRepoFolder = project.getFolder(removeCurrentDirPrefix(transientOutputRepo));
if (!newOutputRepoFolder.exists()) {
try {
CoreUtility.createDerivedFolder(newOutputRepoFolder, true, true, null);
} catch (CoreException e) {
e.printStackTrace();
}
}
if (!newOutputRepoFolder.isHidden()) {
try {
newOutputRepoFolder.setHidden(true);
} catch (CoreException e) {
e.printStackTrace();
}
}
CeylonEncodingSynchronizer.getInstance().refresh(project, null);
}
private String removeCurrentDirPrefix(String url) {
return url.startsWith("./") || url.startsWith(".\\") ? url.substring(2) : url;
}
private List<String> getConfigValuesAsList(CeylonConfig config, String optionKey, String defaultKey) {
String[] values = config.getOptionValues(optionKey);
if (values != null) {
return Arrays.asList(values);
} else {
return Collections.singletonList(defaultKey);
}
}
private void setConfigValuesAsList(CeylonConfig config, String optionKey, List<String> values) {
String[] array = new String[values.size()];
config.setOptionValues(optionKey, values.toArray(array));
}
}
|
package org.ow2.chameleon.rose.zookeeper;
import static org.osgi.service.log.LogService.LOG_ERROR;
import static org.osgi.service.log.LogService.LOG_INFO;
import static org.ow2.chameleon.rose.zookeeper.ZookeeperManager.SEPARATOR;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.osgi.service.log.LogService;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.ow2.chameleon.json.JSONService;
import org.ow2.chameleon.rose.RoseEndpointDescription;
import org.ow2.chameleon.rose.RoseMachine;
import org.ow2.chameleon.rose.util.RoseTools;
public class ZooRemoteEndpointWatcher {
private final ZookeeperManager manager;
private final RoseMachine machine;
private final String rootNode;
private ConcurrentHashMap<String, List<String>> registrations;
private List<String> nodes;
private boolean running = false;
public ZooRemoteEndpointWatcher(ZookeeperManager pManager,
RoseMachine pMachine, String pRootNode) {
manager = pManager;
machine = pMachine;
this.rootNode = pRootNode;
registrations = new ConcurrentHashMap<String, List<String>>();
try {
nodes = keeper().getChildren(rootNode, new MachineWatcher());
running = true;
for (String node : nodes) {
if (node.equals(manager.frameworkid)) {
continue; // ignore myself
}
registrations.put(node, new ArrayList<String>());
keeper().getChildren(rootNode + SEPARATOR + node,
new EndpointWatcher(node));
}
logger().log(LOG_INFO,
"Remote endpoints watcher successfully created");
} catch (KeeperException e) {
logger().log(LOG_ERROR, "Can not create a watcher for nodes", e);
} catch (InterruptedException e) {
logger().log(LOG_ERROR, "Can not create a watcher for nodes", e);
}
}
public void stop() {
running = false;
for (String node : nodes) {
processMachineRemoved(node);
}
}
private void processMachineRemoved(String node) {
if (node.equals(manager.frameworkid))
return;
for (String endpoint : registrations.get(node)) {
machine.removeRemote(node + SEPARATOR + endpoint);
}
registrations.remove(node);
logger().log(LOG_INFO, "Machine: " + node + " removed");
}
private void processEndpointAdded(String node, String endpoint)
throws KeeperException, InterruptedException, ParseException {
try{
byte[] desc = keeper().getData(
rootNode + SEPARATOR + node + SEPARATOR + endpoint, true, null);
@SuppressWarnings("unchecked")
Map<String, Object> map = json().fromJSON(new String(desc));
EndpointDescription endp = RoseEndpointDescription
.getEndpointDescription(map);
machine.putRemote(node + SEPARATOR + endpoint, endp);
registrations.get(node).add(endpoint);
logger().log(LOG_INFO,
"Added from machine: " + node + " ,endpoint: " + endpoint);
}
catch (Exception e) {
logger().log(LOG_ERROR,
"Cant register : " + node + " ,endpoint: " + endpoint, e);
}
}
private void processEndpointRemoved(String node, String endpoint) {
machine.removeRemote(node + SEPARATOR + endpoint);
registrations.get(node).remove(endpoint);
logger().log(LOG_INFO,
"Removed from machine: " + node + " ,endpoint: " + endpoint);
}
private class MachineWatcher implements Watcher {
List<String> newNodes;
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent
* )
*/
public void process(WatchedEvent event) {
if (running == false)
return;
try {
newNodes = keeper().getChildren(rootNode, this);
if (nodes.containsAll(newNodes)) {// node deleted
for (String node : (List<String>) RoseTools.listSubtract(
nodes, newNodes)) {
processMachineRemoved(node);
}
}
if (newNodes.containsAll(nodes)) {// new node
for (String node : (List<String>) RoseTools.listSubtract(
newNodes, nodes)) {
logger().log(LOG_INFO, "Machine: " + node + " found");
registrations.put(node, new ArrayList<String>());
new EndpointWatcher(node);
}
}
nodes = newNodes;
} catch (InterruptedException e) {
logger().log(LOG_ERROR,
"Can not get childrens(endpoints) for node", e);
} catch (KeeperException e) {
logger().log(LOG_ERROR,
"Can not get childrens(endpoints) for node", e);
}
}
}
private class EndpointWatcher implements Watcher {
private List<String> endpoints;
private String node;
private List<String> newEndpoints;
private boolean getAll = false; // register all endpoints, run at the
// beginning of node discovered
public EndpointWatcher(String node) {
this.node = node;
try {
endpoints = keeper().getChildren(rootNode + SEPARATOR + node,
false);
if (endpoints.size() > 0) {
getAll = true;
this.process(null);
}
} catch (KeeperException e) {
logger().log(LOG_ERROR, "Can not find a node: " + node, e);
} catch (InterruptedException e) {
logger().log(LOG_ERROR, "Can not find a node: " + node, e);
}
}
/*
* (non-Javadoc)
*
* @see
* org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent
* )
*/
public void process(WatchedEvent event) {
if (running == false)
return;
try {
if (keeper().exists(rootNode + SEPARATOR + this.node, false) == null)
return; // node has been deleted
newEndpoints = keeper().getChildren(
rootNode + SEPARATOR + node, this);
if (nodes.containsAll(newEndpoints)) {// endpoint deleted
for (String endpoint : (List<String>) RoseTools
.listSubtract(endpoints, newEndpoints)) {
processEndpointRemoved(node, endpoint);
}
}
if (newEndpoints.containsAll(endpoints)) {// endpoint added
if (getAll == true) {
for (String endpoint : newEndpoints) {
processEndpointAdded(this.node, endpoint);
}
} else {
for (String endpoint : (List<String>) RoseTools
.listSubtract(newEndpoints, endpoints)) {
processEndpointAdded(this.node, endpoint);
}
}
getAll = false;
}
} catch (KeeperException e) {
logger().log(LOG_ERROR, "Can not find a node", e);
} catch (InterruptedException e) {
logger().log(LOG_ERROR, "Can not find a node", e);
} catch (ParseException e) {
logger().log(LOG_ERROR, "Can not add an endpoint", e);
}
}
}
private ZooKeeper keeper() {
return manager.getKeeper();
}
private JSONService json() {
return manager.getJson();
}
private LogService logger() {
return manager.getLogger();
}
}
|
package dk.statsbiblioteket.medieplatform.autonomous;
import dk.statsbiblioteket.doms.central.summasearch.SearchWS;
import dk.statsbiblioteket.doms.central.summasearch.SearchWSService;
import dk.statsbiblioteket.util.xml.DOM;
import dk.statsbiblioteket.util.xml.XPathSelector;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.namespace.QName;
import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Implementation of the {@link EventAccessor} and {@link EventTrigger} interface using SBOI summa index and DOMS.
* Uses soap, json and xml to query the summa instance for batches, and REST to get batch details from DOMS.
*/
public class SBOIEventIndex<T extends Item> implements EventTrigger<T>, EventAccessor<T> {
private static final String SUCCESSEVENT = "success_event";
private static final String FAILEVENT = "fail_event";
private static final String RECORD_BASE = "recordBase:doms_sboiCollection";
private static final String ROUND_TRIP_NO = "round_trip_no";
private static final String BATCH_ID = "batch_id";
private static final String UUID = "round_trip_uuid";
private static final String PREMIS_NO_DETAILS = "premis_no_details";
private static Logger log = org.slf4j.LoggerFactory.getLogger(SBOIEventIndex.class);
private final PremisManipulatorFactory<T> premisManipulatorFactory;
private DomsEventStorage<T> domsEventStorage;
private final SearchWS summaSearch;
public SBOIEventIndex(String summaLocation, PremisManipulatorFactory<T> premisManipulatorFactory,
DomsEventStorage<T> domsEventStorage) throws MalformedURLException {
this.premisManipulatorFactory = premisManipulatorFactory;
this.domsEventStorage = domsEventStorage;
summaSearch = new SearchWSService(
new java.net.URL(summaLocation),
new QName("http://statsbiblioteket.dk/summa/search", "SearchWSService")).getSearchWS();
}
@Override
public Iterator<T> findItems(boolean details, List<String> pastSuccessfulEvents, List<String> pastFailedEvents,
List<String> futureEvents) throws
CommunicationException {
return search(details, pastSuccessfulEvents, pastFailedEvents, futureEvents,null);
}
@Override
public T getItem(String itemFullID) throws CommunicationException, NotFoundException {
return domsEventStorage.getItemFromFullID(itemFullID);
}
@Override
public Iterator<T> getTriggeredItems(Collection<String> pastSuccessfulEvents,
Collection<String> pastFailedEvents, Collection<String> futureEvents) throws CommunicationException {
return getTriggeredItems(pastSuccessfulEvents, pastFailedEvents, futureEvents, null);
}
@Override
public Iterator<T> getTriggeredItems(Collection<String> pastSuccessfulEvents,
Collection<String> pastFailedEvents, Collection<String> futureEvents,
Collection<T> batches) throws CommunicationException {
Iterator<T> sboiBatches = search(false, pastSuccessfulEvents, pastFailedEvents, futureEvents,batches);
ArrayList<T> result = new ArrayList<>();
while (sboiBatches.hasNext()) {
T next = sboiBatches.next();
T instead = null;
try {
instead = domsEventStorage.getItemFromDomsID(next.getDomsID());
} catch (NotFoundException ignored) {
continue;
}
if (match(instead, pastSuccessfulEvents, pastFailedEvents, futureEvents)) {
result.add(instead);
}
}
return result.iterator();
}
/**
* Check that the item matches the requirements expressed in the three lists
*
* @param item the item to check
* @param pastSuccessfulEvents events that must be success
* @param pastFailedEvents events that must be failed
* @param futureEvents events that must not be there
*
* @return true if the item match all requirements
*/
private boolean match(Item item, Collection<String> pastSuccessfulEvents, Collection<String> pastFailedEvents,
Collection<String> futureEvents) {
Set<String> successEvents = new HashSet<>();
Set<String> failEvents = new HashSet<>();
for (Event event : item.getEventList()) {
if (event.isSuccess()) {
successEvents.add(event.getEventID());
} else {
failEvents.add(event.getEventID());
}
}
return successEvents.containsAll(pastSuccessfulEvents) && failEvents.containsAll(pastFailedEvents) && Collections
.disjoint(futureEvents, successEvents) && Collections.disjoint(futureEvents, failEvents);
}
/**
* Perform a search for items matching the given criteria
*
* @param pastSuccessfulEvents Events that the batch must have sucessfully experienced
* @param pastFailedEvents Events that the batch must have experienced, but which failed
* @param futureEvents Events that the batch must not have experienced
* @param items if not null, the resulting iterator will only contain items from this set. If the
* items is empty, the result will be empty.
*
* @return An iterator over the found items
* @throws CommunicationException if the communication failed
*/
public Iterator<T> search(boolean details, Collection<String> pastSuccessfulEvents, Collection<String> pastFailedEvents,
Collection<String> futureEvents, Collection<T> items) throws CommunicationException {
try {
if (items != null && items.isEmpty()){
//If the items constraint is set to no result, give no result.
return new ArrayList<T>().iterator();
}
JSONObject jsonQuery = new JSONObject();
jsonQuery.put("search.document.resultfields", commaSeparate(UUID, getPremisFieldName(details)));
jsonQuery.put(
"search.document.query",
toQueryString(pastSuccessfulEvents, pastFailedEvents, futureEvents,items));
jsonQuery.put("search.document.startindex", 0);
//TODO fix this static maxrecords (we can order on creation date)
jsonQuery.put("search.document.maxrecords", 1000);
String searchResultString;
synchronized (summaSearch) {//TODO is this nessesary?
searchResultString = summaSearch.directJSON(jsonQuery.toString());
}
Document searchResultDOM = DOM.stringToDOM(searchResultString);
XPathSelector xPath = DOM.createXPathSelector();
NodeList nodeList = xPath.selectNodeList(
searchResultDOM, "/responsecollection/response/documentresult/record");
List<T> results = new ArrayList<>(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
String uuid = DOM.selectString(node, "field[@name='" + UUID + "']");
T result = null;
if (!details) { //no details, so we can retrieve everything from Summa
String premis = DOM.selectString(node, "field[@name='" + PREMIS_NO_DETAILS + "']");
result = premisManipulatorFactory.createFromBlob(new ByteArrayInputStream(premis.getBytes()))
.toItem();
result.setDomsID(uuid);
} else {//Details requested so go to DOMS
result = domsEventStorage.getItemFromDomsID(uuid);
}
results.add(result);
}
return results.iterator();
} catch (Exception e) {
log.warn("Caught Unknown Exception", e);
throw new CommunicationException(e);
}
}
private String commaSeparate(String... elements) {
StringBuilder result = new StringBuilder();
for (String element : elements) {
if (element == null) {
continue;
}
if (result.length() != 0) {
result.append(",");
}
result.append(element);
}
return result.toString();
}
private String getPremisFieldName(boolean details) {
if (details) {
return "";
} else {
return PREMIS_NO_DETAILS;
}
}
private String spaced(String string) {
return " " + string.trim() + " ";
}
private String quoted(String string) {
return "\"" + string + "\"";
}
private String toQueryString(Collection<String> pastSuccessfulEvents, Collection<String> pastFailedEvents, Collection<String> futureEvents, Collection<T> batches) {
String base = spaced(RECORD_BASE);
StringBuilder batchesString = new StringBuilder();
if (batches != null ){
batchesString.append(" ( ");
boolean first = true;
for (Item item : batches) {
if (first){
first = false;
} else {
batchesString.append(" OR ");
}
batchesString.append(" ( ");
if (item instanceof Batch) {
//TODO: Can this be replaced with just checking the UUID instead?
Batch batch = (Batch) item;
batchesString.append(BATCH_ID).append(":B").append(batch.getBatchID());
if (batch.getRoundTripNumber() > 0) {
batchesString.append(" ");
batchesString.append(ROUND_TRIP_NO).append(":RT").append(batch.getRoundTripNumber());
}
} else {
batchesString.append(UUID).append(":").append(item.getDomsID());
}
batchesString.append(" ) ");
}
batchesString.append(" ) ");
}
StringBuilder events = new StringBuilder();
if (pastSuccessfulEvents != null) {
for (String successfulPastEvent : pastSuccessfulEvents) {
events.append(spaced("+"+SUCCESSEVENT + ":" + quoted(successfulPastEvent)));
}
}
if (pastFailedEvents != null) {
for (String failedPastEvent : pastFailedEvents) {
events.append(spaced("+"+FAILEVENT + ":" + quoted(failedPastEvent)));
}
}
if (futureEvents != null) {
for (String futureEvent : futureEvents) {
events.append(spaced("-" + SUCCESSEVENT + ":" + quoted(futureEvent)));
events.append(spaced("-" + FAILEVENT + ":" + quoted(futureEvent)));
}
}
return base + batchesString.toString() + events.toString();
}
}
|
package cz.quinix.condroid.database;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import cz.quinix.condroid.model.Annotation;
import cz.quinix.condroid.model.Convention;
import cz.quinix.condroid.model.ProgramLine;
import cz.quinix.condroid.model.Reminder;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class DataProvider {
public static String AUTHORITY = "cz.quinix.condroid.database.DataProvider";
public static Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/database");
public static int ITEMS_PER_PAGE = 40;
private CondroidDatabase mDatabase;
private Convention con;
private List<Integer> favorited;
private static volatile DataProvider instance;
private static HashMap<Integer, String> programLines = null;
private DataProvider(Context context) {
mDatabase = new CondroidDatabase(context);
}
public static DataProvider getInstance(Context context) {
if (instance == null) {
synchronized (CondroidDatabase.class) {
if (instance == null) {
instance = new DataProvider(context);
}
}
}
return instance;
}
public boolean hasData() {
return !mDatabase.isEmpty();
}
public void setConvention(Convention convention) {
con = convention;
}
public DatabaseLoader prepareInsert(boolean fullInsert) {
if (fullInsert && !mDatabase.isEmpty()) {
mDatabase.purge();
}
programLines = null;
favorited = null;
return new DatabaseLoader(null, mDatabase, con, fullInsert);
}
public List<Annotation> getAnnotations(SearchQueryBuilder con, int skip) {
List<Annotation> ret = new ArrayList<Annotation>();
String condition = null;
if (con != null)
condition = con.buildCondition();
Cursor c = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, condition, null, "startTime ASC, lid ASC, title ASC", (skip) + "," + ITEMS_PER_PAGE);
while (c.moveToNext()) {
ret.add(readAnnotation(c));
}
c.close();
return ret;
}
public ProgramLine getProgramLine(int lid) {
ProgramLine pl = new ProgramLine();
if (programLines == null) {
this.loadProgramLines();
}
if (programLines != null) {
if (programLines.containsKey(lid)) {
pl.setLid(lid);
pl.setName(programLines.get(lid));
}
}
return pl;
}
public HashMap<Integer, String> getProgramLines() {
if (programLines == null) {
this.loadProgramLines();
}
return programLines;
}
private void loadProgramLines() {
programLines = new HashMap<Integer, String>();
Cursor c = this.mDatabase.query(CondroidDatabase.LINE_TABLE, null, null, null, "title ASC", null);
while (c.moveToNext()) {
programLines.put(c.getInt(c.getColumnIndex("id")), c.getString(c.getColumnIndex("title")));
}
c.close();
}
public List<Date> getDates() {
Cursor c = this.mDatabase.query("SELECT DISTINCT STRFTIME('%Y-%m-%d',startTime) AS sDate FROM " + CondroidDatabase.ANNOTATION_TABLE + " ORDER by STRFTIME('%Y-%m-%d',startTime) ASC");
List<Date> map = new ArrayList<Date>();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
if (c.getCount() > 0) {
do {
try {
if (c.getString(c.getColumnIndex("sDate")) != null) {
map.add(df.parse(c.getString(c.getColumnIndex("sDate"))));
}
} catch (ParseException e) {
Log.e("Condroid", "Exception when parsing dates for list dialog.", e);
}
} while (c.moveToNext());
}
c.close();
return map;
}
public List<Annotation> getRunningAndNext(int page) {
return this.getRunningAndNext(null, page);
}
public List<Annotation> getRunningAndNext(SearchQueryBuilder sb, int skip) {
List<Annotation> l = new ArrayList<Annotation>();
String condition = "";
if (sb != null) {
condition = sb.buildCondition();
}
if (condition != null) {
}
if (skip == 0) {
Cursor c = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime < DATETIME('now') AND endTime > DATETIME('now')" + (condition != null && !condition.equals("") ? " AND " + condition : ""), null, "startTime DESC", null, false);
while (c.moveToNext()) {
Annotation annotation = readAnnotation(c);
l.add(annotation);
}
c.close();
}
Cursor c2 = this.mDatabase.query(CondroidDatabase.ANNOTATION_TABLE, null, "startTime > DATETIME('now')" + (condition != null && !condition.equals("") ? " AND " + condition : ""), null, "startTime ASC, lid ASC", (skip) + "," + ITEMS_PER_PAGE, false);
Log.d("Condroid", "LIMIT: " + ((skip) + "," + ITEMS_PER_PAGE) + ", returned items " + c2.getCount());
while (c2.moveToNext()) {
Annotation annotation = readAnnotation(c2);
l.add(annotation);
}
c2.close();
return l;
}
private Annotation readAnnotation(Cursor c) {
Annotation annotation = new Annotation();
annotation.setPid(c.getString(c.getColumnIndex("pid")));
annotation.setTitle(c.getString(c.getColumnIndex("title")));
annotation.setAnnotation(c.getString(c.getColumnIndex("annotation")));
annotation.setAuthor(c.getString(c.getColumnIndex("talker")));
annotation.setSQLEndTime(c.getString(c.getColumnIndex("endTime")));
//annotation.setLength(c.getString(c.getColumnIndex("length")));
annotation.setLocation(c.getString(c.getColumnIndex("location")));
annotation.setLid(c.getInt(c.getColumnIndex("lid")));
annotation.setSQLStartTime(c.getString(c.getColumnIndex("startTime")));
annotation.setType(c.getString(c.getColumnIndex("mainType")));
annotation.setAdditonalTypes(c.getString(c.getColumnIndex("additionalTypes")));
return annotation;
}
public Convention getCon() {
if (this.con != null) {
return con;
}
Cursor c = this.mDatabase.query(CondroidDatabase.CON_TABLE, null, null, null, null, null);
Convention co = new Convention();
while (c.moveToNext()) {
co.setCid(c.getInt(c.getColumnIndex("id")));
co.setDataUrl(c.getString(c.getColumnIndex("dataUrl")));
co.setDate(c.getString(c.getColumnIndex("date")));
co.setIconUrl(c.getString(c.getColumnIndex("iconUrl")));
co.setName(c.getString(c.getColumnIndex("name")));
co.setMessage(c.getString(c.getColumnIndex("message")));
co.setLocationsFile(c.getString(c.getColumnIndex("locationsFile")));
DateTimeFormatter format = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC();
try {
co.setLastUpdate(format.parseDateTime(c.getString(c.getColumnIndex("lastUpdate"))).toDate());
} catch (Exception e) {
Log.e("Condroid", "Parsing DB date", e);
co.setLastUpdate(new Date());
}
}
c.close();
this.con = co;
return co;
}
public List<Integer> getFavorited() {
if (favorited != null) {
return favorited;
}
Cursor c = this.mDatabase.query(CondroidDatabase.FAVORITE_TABLE, null, null, null, "pid ASC", null);
favorited = new ArrayList<Integer>();
while (c.moveToNext()) {
favorited.add(c.getInt(c.getColumnIndex("pid")));
}
return favorited;
}
public boolean doFavorite(int pid) {
Cursor c = this.mDatabase.query(CondroidDatabase.FAVORITE_TABLE, null, "pid=" + pid, null, null, null);
favorited = null;
if (c.getCount() > 0) {
this.mDatabase.query("DELETE FROM " + CondroidDatabase.FAVORITE_TABLE + " WHERE pid = '" + pid + "'");
return false;
} else {
this.mDatabase.query("INSERT INTO " + CondroidDatabase.FAVORITE_TABLE + " (pid) VALUES ('" + pid + "')");
return true;
}
}
public boolean setReminder(Annotation annotation, int i) {
try {
Cursor c = this.mDatabase.query("SELECT pid FROM " + CondroidDatabase.ANNOTATION_TABLE + " WHERE pid =" + annotation.getPid() + " AND startTime IS NOT NULL");
if (c.getCount() > 0) {
this.mDatabase.query("DELETE FROM " + CondroidDatabase.REMINDER_TABLE + " WHERE pid=" + annotation.getPid());
this.mDatabase.query("INSERT INTO " + CondroidDatabase.REMINDER_TABLE + " (pid, minutes) VALUES ('" + annotation.getPid() + "','" + i + "')");
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Integer getReminder(int pid) {
Cursor c = this.mDatabase.query(CondroidDatabase.REMINDER_TABLE, null, "pid = " + pid, null, null, null);
if (c.getCount() > 0) {
c.moveToNext();
return Integer.parseInt(c.getString(c.getColumnIndex("minutes")));
} else {
return null;
}
}
public boolean removeReminder(int pid) {
try {
this.mDatabase.query("DELETE FROM " + CondroidDatabase.REMINDER_TABLE + " WHERE pid=" + pid);
return true;
} catch (Exception e) {
Log.w("Condroid", e);
return false;
}
}
public Reminder getNextReminder() {
Cursor c = this.mDatabase.query("SELECT r.minutes AS remind, a.* FROM " + CondroidDatabase.REMINDER_TABLE + " r JOIN " + CondroidDatabase.ANNOTATION_TABLE + " a USING (pid) ORDER by startTime ASC LIMIT 1");
if (c != null && c.getCount() > 0) {
c.moveToFirst();
Reminder r = new Reminder();
r.annotation = this.readAnnotation(c);
r.reminder = c.getInt(c.getColumnIndex("remind"));
c.close();
return r;
}
return null;
}
public List<Reminder> getReminderList() {
List<Reminder> r = new ArrayList<Reminder>();
Cursor c = this.mDatabase.query("SELECT r.minutes AS remind, a.* FROM " + CondroidDatabase.REMINDER_TABLE + " r JOIN " + CondroidDatabase.ANNOTATION_TABLE + " a USING (pid) ORDER by startTime ASC LIMIT 20");
if (c != null) {
if (c.getCount() > 0)
do {
Reminder reminder = new Reminder();
reminder.annotation = this.readAnnotation(c);
reminder.reminder = c.getInt(c.getColumnIndex("remind"));
r.add(reminder);
} while (c.moveToNext());
c.close();
}
return r;
}
public int getAnnotationsCount() {
Cursor c = this.mDatabase.query("SELECT count(*) FROM annotations", null);
int count = 0;
if (c.getCount() > 0) {
count = c.getInt(0);
}
c.close();
return count;
}
}
|
package de.lmu.ifi.dbs.database;
import de.lmu.ifi.dbs.utilities.UnableToComplyException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* TODO comment
*
* @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>)
*/
public abstract class AbstractDatabase implements Database {
/**
* Map to hold association maps.
*/
private final Map<String, Map<Integer, Object>> associations;
/**
* Counter to provide a new Integer id.
*/
private int counter;
private List<Integer> reusableIDs;
private boolean reachedLimit;
/**
* @see de.lmu.ifi.dbs.database.Database#associate(java.lang.String, java.lang.Integer, java.lang.Object)
*/
public void associate(String associationID, Integer objectID, Object association) {
if (!associations.containsKey(associationID)) {
associations.put(associationID, new Hashtable<Integer, Object>());
}
associations.get(associationID).put(objectID, association);
}
/**
* @see de.lmu.ifi.dbs.database.Database#getAssociation(java.lang.String, java.lang.Integer)
*/
public Object getAssociation(String associationID, Integer objectID) {
if (associations.containsKey(associationID)) {
return associations.get(associationID).get(objectID);
}
else {
return null;
}
}
protected AbstractDatabase() {
associations = new Hashtable<String, Map<Integer, Object>>();
counter = Integer.MIN_VALUE;
reachedLimit = false;
reusableIDs = new ArrayList<Integer>();
}
protected Integer newID() throws UnableToComplyException {
if (reachedLimit && reusableIDs.size() == 0) {
throw new UnableToComplyException("Database reached limit of storage.");
}
else {
Integer id = new Integer(counter);
if (counter < Integer.MAX_VALUE && !reachedLimit) {
counter++;
}
else {
if (reusableIDs.size() > 0) {
counter = reusableIDs.remove(0).intValue();
}
else {
reachedLimit = true;
}
}
return id;
}
}
protected void restoreID(Integer id) {
{
reusableIDs.add(id);
}
}
}
|
package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import gov.nih.nci.ncicb.cadsr.common.dto.FormTransferObject;
import gov.nih.nci.ncicb.cadsr.common.dto.FormV2TransferObject;
import gov.nih.nci.ncicb.cadsr.common.dto.ModuleTransferObject;
import gov.nih.nci.ncicb.cadsr.common.resource.FormV2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author yangs8
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath:/applicationContext-service-test-db.xml"})
@ContextConfiguration(locations = {"classpath:/applicationContext-jdbcdao-test.xml"})
public class JDBCFormV2DAOTest {
@Autowired
JDBCFormDAOV2 formV2Dao;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* Test method for {@link gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc.JDBCFormDAOV2#getVersionsByPublicIds(java.util.List)}.
*/
@Test
public void testGetVersionsByPublicIds() {
List<String> ids = new ArrayList<String>();
//ids.add("3641027");
ids.add("3636260");
ids.add("3636081");
ids.add("3636123");
ids.add("3460365");
ids.add("1234567"); //bogus
List<FormV2> forms = formV2Dao.getExistingVersionsForPublicIds(ids);
assertNotNull(forms);
assertTrue(forms.size() > 3);
for (FormV2 form : forms) {
if ("1234567".equals(form.getPublicId()))
fail("Bogus public id returns a record. That's fishy.");
}
}
@Test
public void testGetModulesInAForm() {
//public id:3193449
String formSeqId = "9D1F6BBF-433E-0B69-E040-BB89AD436323";
List<ModuleTransferObject> module = formV2Dao.getModulesInAForm(formSeqId);
assertNotNull(module);
assertTrue(module.size() == 3);
}
@Test
public void testCreateFormComponent() {
FormV2TransferObject newform = new FormV2TransferObject();
HashMap<String, String> conteMap = formV2Dao.getAllContextSeqIds();
newform.setVersion((float)1.0);
newform.setAslName("DRAFT NEW");
newform.setLongName("SY Test");
newform.setConteIdseq(conteMap.get("CTEP"));
newform.setCreatedBy("FORMBUILDER");
newform.setFormType("CRF");
newform.setPreferredDefinition("SY- CALGB: 40101 HER-2/neu TESTING FORM");
newform.setFormCategory("Treatment");
newform.setChangeNote("Adding a change note");
String seq = formV2Dao.createFormComponent(newform);
assertNotNull(seq);
assertTrue(seq.length() > 0);
System.out.println("Inserted a new form: " + seq);
}
@Test
public void testGetProtocolSeqidsByIds() {
List<String> protoIds = new ArrayList<String>();
protoIds.add("ACOSOG-Z4099");
protoIds.add("DCLS001");
HashMap<String, String> protoMap = formV2Dao.getProtocolSeqidsByIds(protoIds);
assertNotNull(protoMap);
String key = protoMap.get("DCLS001");
assertTrue(key.equals("C118C152-222D-6D05-E034-0003BA12F5E7"));
}
@Test
public void testFormProtocolExists() {
String formSeqId = "9D1F6BBF-433E-0B69-E040-BB89AD436323";
String proto_idseq = "97782209-606A-AFBF-E040-BB89AD43078F";
boolean proto = formV2Dao.formProtocolExists(formSeqId, proto_idseq);
assertTrue(proto);
proto_idseq = "afagasgaeageagae";
proto = formV2Dao.formProtocolExists(formSeqId, proto_idseq);
assertFalse(proto);
}
@Test
public void testGetFormHeadersBySeqids() {
List<String> seqids = new ArrayList<String>();
seqids.add("E49101B2-1B33-BA26-E040-BB8921B61DC6");
seqids.add("E49101B2-1B33-BA26-E040-BB8921B61DC6");
String formSeqId = "9D1F6BBF-433E-0B69-E040-BB89AD436323";
List<FormV2TransferObject> forms = formV2Dao.getFormHeadersBySeqids(seqids);
assertNotNull(forms);
assertTrue(forms.size() >= 2);
}
@Test
public void testGetLatestVersionForForm() {
float latest = formV2Dao.getLatestVersionForForm(3643954);
assertTrue(latest >= 67.0);
}
@Test
public void testUpdateLatestVersionIndicator() {
int res = formV2Dao.updateLatestVersionIndicator("E9FA3574-4D30-3253-E040-BB8921B6498C", "Yes", "FORMLOADER");
assertTrue(res > 0);
}
@Test
public void testUpdateLatestVersionIndicatorByPublicIdAndVersion() {
int res = formV2Dao.updateLatestVersionIndicatorByPublicIdAndVersion(3643954, (float)10.0, "No", "FORMLOADER");
assertTrue(res > 0);
}
@Test
public void testGetLatestVersionIndicatorForForm() {
boolean yesno = formV2Dao.isLatestVersionForForm("A7294BEF-41E2-2FCE-E034-0003BA0B1A09");
assertTrue(yesno);
yesno = formV2Dao.isLatestVersionForForm("9FDEC391-8EA4-89A0-E040-BB89AD432639");
assertFalse(yesno);
yesno = formV2Dao.isLatestVersionForForm("EA720B73-E5CC-2B18-E040-BB8921B62F5C");
assertTrue(yesno);
}
}
|
package de.ptb.epics.eve.viewer.views;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.part.ViewPart;
import de.ptb.epics.eve.data.scandescription.Axis;
import de.ptb.epics.eve.data.scandescription.Chain;
import de.ptb.epics.eve.data.scandescription.Channel;
import de.ptb.epics.eve.data.scandescription.ScanModul;
import de.ptb.epics.eve.ecp1.client.interfaces.IConnectionStateListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IErrorListener;
import de.ptb.epics.eve.ecp1.client.model.Error;
import de.ptb.epics.eve.ecp1.intern.EngineStatus;
import de.ptb.epics.eve.ecp1.intern.ErrorType;
import de.ptb.epics.eve.preferences.PreferenceConstants;
import de.ptb.epics.eve.viewer.Activator;
import de.ptb.epics.eve.viewer.IUpdateListener;
/**
* A simple view implementation, which only displays a label.
*
* @author Hartmut Scherr
*/
public final class EngineView extends ViewPart implements IUpdateListener, IConnectionStateListener, IErrorListener {
private Composite top = null;
private Label engineLabel;
private Composite engineComposite;
private Button startButton;
private Button killButton;
private Button connectButton;
private Button disconnectButton;
private Label statusLabel;
private Label scanLabel;
private Composite scanComposite;
private Button playButton;
private Button pauseButton;
private Button stopButton;
private Button skipButton;
private Button haltButton;
private Button autoPlayOnButton;
private Button autoPlayOffButton;
private Label repeatCountLabel;
private Text repeatCountText;
private Label loadedScmlLabel;
private Text loadedScmlText;
private Label chainFilenameLabel;
private Text filenameText;
private Label commentLabel;
private Text commentText;
private Button commentSendButton;
private Table statusTable;
private Shell shellTable[] = new Shell[10];
/**
* {@inheritDoc}
*/
@Override
public void createPartControl( final Composite parent ) {
final Image playIcon = Activator.getDefault().getImageRegistry().get("PLAY16");
final Image pauseIcon = Activator.getDefault().getImageRegistry().get("PAUSE16");
final Image stopIcon = Activator.getDefault().getImageRegistry().get("STOP16");
final Image skipIcon = Activator.getDefault().getImageRegistry().get("SKIP16");
final Image haltIcon = Activator.getDefault().getImageRegistry().get("HALT16");
final Image autoPlayIcon = Activator.getDefault().getImageRegistry().get("PLAYALL16");
parent.setLayout( new FillLayout() );
GridLayout gridLayout;
GridData gridData;
this.top = new Composite( parent, SWT.NONE );
gridLayout = new GridLayout();
gridLayout.numColumns = 4;
this.top.setLayout(gridLayout);
this.engineLabel = new Label( this.top, SWT.NONE );
this.engineLabel.setText("ENGINE:");
this.engineComposite = new Composite( this.top, SWT.NONE );
gridLayout = new GridLayout();
gridLayout.numColumns = 4;
this.engineComposite.setLayout(gridLayout);
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 3;
this.engineComposite.setLayoutData( gridData );
this.startButton = new Button( this.engineComposite, SWT.PUSH );
this.startButton.setText("start");
this.startButton.setToolTipText( "Start engine" );
this.startButton.addSelectionListener( new StartButtonSelectionListener());
this.killButton = new Button( this.engineComposite, SWT.PUSH );
this.killButton.setText("kill");
this.killButton.setToolTipText( "Kill engine" );
this.killButton.addSelectionListener( new KillButtonSelectionListener());
this.connectButton = new Button( this.engineComposite, SWT.PUSH );
this.connectButton.setText("connect");
this.connectButton.setToolTipText( "Connect to Engine" );
this.connectButton.addSelectionListener( new ConnectButtonSelectionListener());
this.disconnectButton = new Button( this.engineComposite, SWT.PUSH );
this.disconnectButton.setText("disconnect");
this.disconnectButton.setToolTipText( "Disconnect Engine" );
this.disconnectButton.addSelectionListener( new DisconnectButtonSelectionListener());
this.statusLabel = new Label( this.engineComposite, SWT.NONE );
this.statusLabel.setText("not connected");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 4;
this.statusLabel.setLayoutData( gridData );
this.scanLabel = new Label( this.top, SWT.NONE );
this.scanLabel.setText("SCAN:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 1;
this.scanLabel.setLayoutData( gridData );
this.scanComposite = new Composite( this.top, SWT.NONE );
gridLayout = new GridLayout();
gridLayout.numColumns = 9;
this.scanComposite.setLayout(gridLayout);
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 3;
this.scanComposite.setLayoutData( gridData );
this.playButton = new Button( this.scanComposite, SWT.PUSH );
this.playButton.setImage(playIcon);
this.playButton.setToolTipText( "Play" );
this.playButton.addSelectionListener( new PlayButtonSelectionListener());
this.pauseButton = new Button( this.scanComposite, SWT.PUSH );
this.pauseButton.setImage(pauseIcon);
this.pauseButton.setToolTipText( "Pause" );
this.pauseButton.addSelectionListener( new PauseButtonSelectionListener());
this.stopButton = new Button( this.scanComposite, SWT.PUSH );
this.stopButton.setImage(stopIcon);
this.stopButton.setToolTipText( "Stop" );
this.stopButton.addSelectionListener( new StopButtonSelectionListener());
this.skipButton = new Button( this.scanComposite, SWT.PUSH );
this.skipButton.setImage(skipIcon);
this.skipButton.setToolTipText( "Skip" );
this.skipButton.addSelectionListener( new SkipButtonSelectionListener());
this.haltButton = new Button( this.scanComposite, SWT.PUSH );
this.haltButton.setImage(haltIcon);
this.haltButton.setToolTipText( "Halt" );
this.haltButton.addSelectionListener( new HaltButtonSelectionListener());
this.autoPlayOnButton = new Button( this.scanComposite, SWT.TOGGLE );
this.autoPlayOnButton.setImage(autoPlayIcon);
this.autoPlayOnButton.setToolTipText( "AutoPlayOn" );
this.autoPlayOnButton.addSelectionListener( new AutoPlayOnButtonSelectionListener());
this.autoPlayOffButton = new Button( this.scanComposite, SWT.TOGGLE );
this.autoPlayOffButton.setImage(autoPlayIcon);
this.autoPlayOffButton.setToolTipText( "AutoPlayOff" );
this.autoPlayOffButton.addSelectionListener( new AutoPlayOffButtonSelectionListener());
this.repeatCountLabel = new Label( this.scanComposite, SWT.NONE );
this.repeatCountLabel.setText("repeat count:");
this.repeatCountText = new Text( this.scanComposite, SWT.BORDER );
// TODO: sobald repeat Count funktioniert wird die Eingabe auch erlaubt
this.repeatCountText.setEnabled(false);
this.loadedScmlLabel = new Label( this.top, SWT.NONE );
this.loadedScmlLabel.setText("loaded File:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
this.loadedScmlLabel.setLayoutData( gridData );
this.loadedScmlText = new Text( this.top, SWT.BORDER );
this.loadedScmlText.setEditable( false );
gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
this.loadedScmlText.setLayoutData( gridData );
this.chainFilenameLabel = new Label( this.top, SWT.NONE );
this.chainFilenameLabel.setText("Filename:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
this.chainFilenameLabel.setLayoutData( gridData );
this.filenameText = new Text( this.top, SWT.BORDER | SWT.TRAIL);
this.filenameText.setEditable( false );
gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
this.filenameText.setLayoutData( gridData );
this.commentLabel = new Label( this.top, SWT.NONE );
this.commentLabel.setText("live Comment:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
this.commentLabel.setLayoutData( gridData );
this.commentText = new Text( this.top, SWT.BORDER);
gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
gridData.horizontalSpan = 1;
this.commentText.setLayoutData( gridData );
this.commentSendButton = new Button( this.top, SWT.NONE);
this.commentSendButton.setText( "Send to File" );
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
this.commentSendButton.setEnabled(false);
this.commentSendButton.setLayoutData( gridData );
this.commentSendButton.addSelectionListener(new CommentSendButtonSelectionListener());
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 10;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
this.statusTable = new Table(top, SWT.NONE);
this.statusTable.setHeaderVisible(true);
this.statusTable.setLinesVisible(true);
this.statusTable.setLayoutData(gridData);
TableColumn tableColumn = new TableColumn(this.statusTable, SWT.NONE);
tableColumn.setWidth(50);
tableColumn.setText("Chain");
TableColumn tableColumn1 = new TableColumn(this.statusTable, SWT.NONE);
tableColumn1.setWidth(100);
tableColumn1.setText("Scan Module");
TableColumn tableColumn2 = new TableColumn(this.statusTable, SWT.NONE);
tableColumn2.setWidth(80);
tableColumn2.setText("Status");
TableColumn tableColumn3 = new TableColumn(this.statusTable, SWT.NONE);
tableColumn3.setWidth(120);
tableColumn3.setText("remaining Time");
// SelectionListener um zu erkennen, wann eine Zeile selektiert wird
this.statusTable.addSelectionListener(new StatusTableSelectionListener());
Activator.getDefault().getChainStatusAnalyzer().addUpdateLisner( this );
Activator.getDefault().getEcp1Client().addErrorListener(this);
this.rebuildText(0);
Activator.getDefault().getEcp1Client().addConnectionStateListener( this );
// If Ecp1Client running (connected), enable disconnect and kill
// else enable connect and start Button
if (Activator.getDefault().getEcp1Client().isRunning()) {
this.connectButton.setEnabled(false);
this.startButton.setEnabled(false);
this.disconnectButton.setEnabled(true);
this.killButton.setEnabled(true);
} else {
this.disconnectButton.setEnabled(false);
this.connectButton.setEnabled(true);
this.killButton.setEnabled(false);
this.startButton.setEnabled(true);
// disable scan buttons if engine disconnected
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(false);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setFocus() {
}
public void updateOccured(int remainTime) {
this.rebuildText(remainTime);
}
public void clearStatusTable() {
// die Tabelle mit den Statusanzeigen wird geleert
this.statusTable.getDisplay().syncExec( new Runnable() {
public void run() {
statusTable.removeAll();
}
});
}
public void disableSendToFile() {
// send to File wird verboten
this.commentSendButton.getDisplay().syncExec( new Runnable() {
public void run() {
commentSendButton.setEnabled(false);
}
});
}
public void fillStatusTable(final int chainId, final int scanModuleId, final String statString, final int remainTime) {
this.statusTable.getDisplay().syncExec( new Runnable() {
public void run() {
final TableItem[] rows = statusTable.getItems();
boolean neu = true;
for ( int i=0; i<rows.length; i++) {
String text0 = rows[i].getText(0).toString().trim();
String text1 = rows[i].getText(1).toString().trim();
int cell0 = Integer.parseInt(text0);
int cell1;
if (text1.equals("")) {
// smid-Feld ist leer, cell1 wird auf -1 gesetzt
cell1 = -1;
}
else {
cell1 = Integer.parseInt(text1.trim());
}
if ( (chainId == cell0) && (scanModuleId == cell1)) {
neu = false;
rows[i].setText(2, statString);
if (cell1 == -1) {
rows[i].setText(3, ""+remainTime);
}
}
};
if (neu) {
TableItem tableItem = new TableItem( statusTable, 0 );
tableItem.setText( 0, " "+chainId);
if (scanModuleId == -1) {
tableItem.setText( 1, " ");
tableItem.setText( 3, ""+remainTime);
}
else {
tableItem.setText( 1, " "+scanModuleId);
}
tableItem.setText( 2, statString);
}
}
});
}
private void rebuildText(int remainTime) {
if( Activator.getDefault().getCurrentScanDescription() != null ) {
final Iterator< Chain > it = Activator.getDefault().getCurrentScanDescription().getChains().iterator();
while( it.hasNext() ) {
final Chain currentChain = it.next();
if( Activator.getDefault().getChainStatusAnalyzer().getRunningChains().contains( currentChain ) ) {
fillStatusTable(currentChain.getId(), -1, "running", remainTime);
} else if( Activator.getDefault().getChainStatusAnalyzer().getExitedChains().contains( currentChain ) ) {
fillStatusTable(currentChain.getId(), -1, "exited", remainTime);
} else {
fillStatusTable(currentChain.getId(), -1, "idle", remainTime);
}
final List< ScanModul > scanModules = currentChain.getScanModuls();
final List< ScanModul > running = Activator.getDefault().getChainStatusAnalyzer().getExecutingScanModules();
for( final ScanModul scanModule : running ) {
if( scanModules.contains( scanModule ) ) {
fillStatusTable(currentChain.getId(), scanModule.getId(), "running", remainTime);
}
}
final List< ScanModul > exited = Activator.getDefault().getChainStatusAnalyzer().getExitingScanModules();
for( final ScanModul scanModule : exited ) {
if( scanModules.contains( scanModule ) ) {
fillStatusTable(currentChain.getId(), scanModule.getId(), "exited", remainTime);
}
}
final List< ScanModul > initialized = Activator.getDefault().getChainStatusAnalyzer().getInitializingScanModules();
for( final ScanModul scanModule : initialized ) {
if( scanModules.contains( scanModule ) ) {
fillStatusTable(currentChain.getId(), scanModule.getId(), "initialized", remainTime);
}
}
final List< ScanModul > paused = Activator.getDefault().getChainStatusAnalyzer().getPausedScanModules();
for( final ScanModul scanModule : paused ) {
if( scanModules.contains( scanModule ) ) {
fillStatusTable(currentChain.getId(), scanModule.getId(), "paused", remainTime);
}
}
final List< ScanModul > waiting = Activator.getDefault().getChainStatusAnalyzer().getWaitingScanModules();
for( final ScanModul scanModule : waiting ) {
if( scanModules.contains( scanModule ) ) {
fillStatusTable(currentChain.getId(), scanModule.getId(), "waiting for trigger", remainTime);
}
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void stackConnected() {
this.connectButton.setEnabled(false);
this.startButton.setEnabled(false);
this.disconnectButton.setEnabled(true);
this.killButton.setEnabled(true);
// Output connected to host.
final String engineString = de.ptb.epics.eve.preferences.Activator.getDefault().getPreferenceStore().getString( PreferenceConstants.P_DEFAULT_ENGINE_ADDRESS );
this.statusLabel.getDisplay().syncExec( new Runnable() {
public void run() {
statusLabel.setText("connected to " + engineString);
}
});
// Wie ist der EngineStatus?
// Activator.getDefault().getEcp1Client().
}
/**
* {@inheritDoc}
*/
@Override
public void stackDisconnected() {
if (!this.loadedScmlText.isDisposed()) this.loadedScmlText.getDisplay().syncExec( new Runnable() {
public void run() {
if (!loadedScmlText.isDisposed()) {
disconnectButton.setEnabled(false);
connectButton.setEnabled(true);
killButton.setEnabled(false);
startButton.setEnabled(true);
statusLabel.setText("not connected");
// disable scan buttons if engine disconnected
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(false);
}
}
});
}
/**
* {@inheritDoc}
*/
public void setLoadedScmlFile(final String filename) {
// der Name des geladenen scml-Files wird angezeigt
this.loadedScmlText.getDisplay().syncExec( new Runnable() {
public void run() {
loadedScmlText.setText(filename);
}
});
}
public void setActualFilename(final String filename) {
// der Name des geladenen scml-Files wird angezeigt
this.filenameText.getDisplay().syncExec(new Runnable() {
public void run() {
filenameText.setText(filename);
}
});
}
@Override
public void fillEngineStatus(EngineStatus engineStatus) {
switch(engineStatus) {
case IDLE_NO_XML_LOADED:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(false);
}
});
break;
case IDLE_XML_LOADED:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(true);
for ( int j=0; j<10; j++) {
if (shellTable[j] != null) {
if (!shellTable[j].isDisposed())
shellTable[j].dispose();
}
}
}
});
break;
case EXECUTING:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
skipButton.setEnabled(true);
haltButton.setEnabled(true);
}
});
break;
case PAUSED:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
skipButton.setEnabled(true);
haltButton.setEnabled(true);
}
});
break;
case STOPPED:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(false);
}
});
break;
case HALTED:
this.playButton.getDisplay().syncExec( new Runnable() {
public void run() {
playButton.setEnabled(false);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
skipButton.setEnabled(false);
haltButton.setEnabled(false);
}
});
break;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setAutoPlayStatus(final boolean autoPlayStatus) {
this.autoPlayOnButton.getDisplay().syncExec( new Runnable() {
public void run() {
if (autoPlayStatus == true) {
autoPlayOnButton.setEnabled(false);
autoPlayOffButton.setEnabled(true);
} else {
autoPlayOnButton.setEnabled(true);
autoPlayOffButton.setEnabled(false);
}
}
});
}
// Wenn eine Zeile in der Tabelle der Chains und ScanModule angeklickt wird,
// Beim nochmaligen anklicken wird das Fenster wieder entfernt.
/**
*
* @author scherr
*
*/
class StatusTableSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
// TODO Auto-generated method stub
// mit den Details der Chain oder des ScanModuls
int selection = statusTable.getSelectionIndex();
// Wenn ja, Info wieder wegnehmen.
if (shellTable[selection] != null) {
// Info ist vorhanden, da shellTable gesetzt
if (!shellTable[selection].isDisposed()) {
shellTable[selection].dispose();
shellTable[selection] = null;
return;
}
}
final TableItem[] rows = statusTable.getItems();
int aktChain = Integer.parseInt(rows[selection].getText(0).trim());
int aktSM;
if (rows[selection].getText(1).trim().equals("")) {
aktSM = 0;
}
else {
aktSM = Integer.parseInt(rows[selection].getText(1).trim());
}
Chain displayChain = Activator.getDefault().getCurrentScanDescription().getChain(aktChain);
if (aktSM > 0) {
Display display = Activator.getDefault().getWorkbench().getDisplay();
Shell chainShell = new Shell(display);
chainShell.setSize(600,400);
chainShell.setText("Scan Module Info");
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
GridData gridData;
chainShell.setLayout(gridLayout);
Label chainLabel = new Label(chainShell,SWT.NONE);
chainLabel.setText("Chain ID:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
chainLabel.setLayoutData(gridData);
Label chainText = new Label(chainShell,SWT.NONE);
chainText.setText(rows[selection].getText(0));
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
chainText.setLayoutData(gridData);
Label smLabel = new Label(chainShell,SWT.NONE);
smLabel.setText("Scan Module ID:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
smLabel.setLayoutData(gridData);
Label smText = new Label(chainShell,SWT.NONE);
smText.setText(rows[selection].getText(1));
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
smText.setLayoutData(gridData);
Label trigDelLabel = new Label(chainShell,SWT.NONE);
trigDelLabel.setText("Trigger delay:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
trigDelLabel.setLayoutData(gridData);
Label trigDelText = new Label(chainShell,SWT.NONE);
trigDelText.setText(""+displayChain.getScanModulById(aktSM).getTriggerdelay());
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
trigDelText.setLayoutData(gridData);
Label settleLabel = new Label(chainShell,SWT.NONE);
settleLabel.setText("Settletime:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
settleLabel.setLayoutData(gridData);
Label settleText = new Label(chainShell,SWT.NONE);
settleText.setText(""+displayChain.getScanModulById(aktSM).getSettletime());
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
settleText.setLayoutData(gridData);
Label confLabel = new Label(chainShell,SWT.NONE);
confLabel.setText("Confirm Trigger:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
confLabel.setLayoutData(gridData);
Label confText = new Label(chainShell,SWT.NONE);
if (displayChain.getScanModulById(aktSM).isTriggerconfirm()) {
confText.setText(" YES ");
}
else {
confText.setText(" NO ");
}
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
confText.setLayoutData(gridData);
Label saveMotLabel = new Label(chainShell,SWT.NONE);
saveMotLabel.setText("Save all motorpositions:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
saveMotLabel.setLayoutData(gridData);
Label saveMotText = new Label(chainShell,SWT.NONE);
saveMotText.setText(displayChain.getScanModulById(aktSM).getSaveAxisPositions().toString());
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
saveMotText.setLayoutData(gridData);
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
Table motTable = new Table(chainShell, SWT.NONE);
motTable.setHeaderVisible(true);
motTable.setLinesVisible(true);
motTable.setLayoutData(gridData);
TableColumn motColumn = new TableColumn(motTable, SWT.NONE);
motColumn.setWidth(250);
motColumn.setText("Motor Axis");
TableColumn motColumn1 = new TableColumn(motTable, SWT.NONE);
motColumn1.setWidth(100);
motColumn1.setText("Start");
TableColumn motColumn2 = new TableColumn(motTable, SWT.NONE);
motColumn2.setWidth(100);
motColumn2.setText("Stop");
TableColumn motColumn3 = new TableColumn(motTable, SWT.NONE);
motColumn3.setWidth(100);
motColumn3.setText("Stepwidth");
Axis[] axis = displayChain.getScanModulById(aktSM).getAxis();
for (int i=0; i<axis.length; i++) {
TableItem tableItem = new TableItem( motTable, 0 );
tableItem.setText( 0, axis[i].getAbstractDevice().getFullIdentifyer());
tableItem.setText( 1, axis[i].getStart());
tableItem.setText( 2, axis[i].getStop());
tableItem.setText( 3, axis[i].getStepwidth());
}
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
Table detTable = new Table(chainShell, SWT.NONE);
detTable.setHeaderVisible(true);
detTable.setLinesVisible(true);
detTable.setLayoutData(gridData);
TableColumn detColumn = new TableColumn(detTable, SWT.NONE);
detColumn.setWidth(250);
detColumn.setText("Detector Channel");
TableColumn detColumn1 = new TableColumn(detTable, SWT.NONE);
detColumn1.setWidth(100);
detColumn1.setText("Average");
Channel[] channels = displayChain.getScanModulById(aktSM).getChannels();
for (int i=0; i<channels.length; i++) {
TableItem tableItem = new TableItem( detTable, 0 );
tableItem.setText( 0, channels[i].getAbstractDevice().getFullIdentifyer());
tableItem.setText( 1, "" + channels[i].getAverageCount());
}
chainShell.open();
shellTable[selection] = chainShell;
}
else {
// Chain Infos anzeigen
Display display = Activator.getDefault().getWorkbench().getDisplay();
Shell chainShell = new Shell(display);
chainShell.setSize(500,200);
chainShell.setText("Chain Info");
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
GridData gridData;
chainShell.setLayout(gridLayout);
Label chainLabel = new Label(chainShell,SWT.NONE);
chainLabel.setText("Chain ID:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
chainLabel.setLayoutData(gridData);
Label chainText = new Label(chainShell,SWT.NONE);
chainText.setText(rows[selection].getText(0));
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
chainText.setLayoutData(gridData);
Label descLabel = new Label(chainShell,SWT.NONE);
descLabel.setText("Save Scan-Description:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
descLabel.setLayoutData(gridData);
Label descText = new Label(chainShell,SWT.NONE);
if (displayChain.isSaveScanDescription()) {
descText.setText(" YES ");
}
else {
descText.setText(" NO ");
}
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
descText.setLayoutData(gridData);
Label confLabel = new Label(chainShell,SWT.NONE);
confLabel.setText("Confirm Save:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
confLabel.setLayoutData(gridData);
Label confText = new Label(chainShell,SWT.NONE);
if (displayChain.isConfirmSave()) {
confText.setText(" YES ");
}
else {
confText.setText(" NO ");
}
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
confText.setLayoutData(gridData);
Label autoincrLabel = new Label(chainShell,SWT.NONE);
autoincrLabel.setText("Add Autoincrementing Number to Filename:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
autoincrLabel.setLayoutData(gridData);
Label autoincrText = new Label(chainShell,SWT.NONE);
if (displayChain.isAutoNumber()) {
autoincrText.setText(" YES ");
}
else {
autoincrText.setText(" NO ");
}
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
autoincrText.setLayoutData(gridData);
Label commentLabel = new Label(chainShell,SWT.NONE);
commentLabel.setText("Comment:");
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
commentLabel.setLayoutData(gridData);
Label commentText = new Label(chainShell,SWT.NONE);
commentText.setText(displayChain.getComment());
gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
commentText.setLayoutData(gridData);
chainShell.open();
shellTable[selection] = chainShell;
}
}
}
@Override
public void errorOccured(Error error) {
if (error.getErrorType() == ErrorType.FILENAME) {
// Aktueller Filename wird gesetzt
setActualFilename(error.getText());
// send to File wird erlaubt
this.commentSendButton.getDisplay().syncExec( new Runnable() {
public void run() {
commentSendButton.setEnabled(true);
}
});
}
}
// Hier kommen jetzt die verschiedenen Listener Klassen
/**
* <code>SelectionListener</code> of Play Button from
* <code>EngineView</code>
*/
class PlayButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected( final SelectionEvent e ) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected( final SelectionEvent e ) {
System.out.println("Play Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayController().start();
}
}
/**
* <code>SelectionListener</code> of Pause Button from
* <code>EngineView</code>
*/
class PauseButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Pause Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayController().pause();
}
}
/**
* <code>SelectionListener</code> of Stop Button from
* <code>EngineView</code>
*/
class StopButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Stop Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayController().stop();
}
}
/**
* <code>SelectionListener</code> of Skip Button from
* <code>EngineView</code>
*/
class SkipButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Skip Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayController().breakExecution();
}
}
/**
* <code>SelectionListener</code> of Halt Button from
* <code>EngineView</code>
*/
class HaltButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Halt Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayController().halt();
}
}
/**
* <code>SelectionListener</code> of Start Button from
* <code>EngineView</code>
*/
class StartButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
// die Engine dann startet.
MessageDialog.openWarning(null, "Warning", "Start löst noch keine Aktion aus!");
}
}
/**
* <code>SelectionListener</code> of Kill Button from
* <code>EngineView</code>
*/
class KillButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
Activator.getDefault().getEcp1Client().getPlayController().shutdownEngine();
}
}
/**
* <code>SelectionListener</code> of Connect Button from
* <code>EngineView</code>
*/
class ConnectButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
if( !Activator.getDefault().getEcp1Client().isRunning()) {
// start ecp1Client
IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
try {
handlerService.executeCommand("de.ptb.epics.eve.viewer.connectCommand", null);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
}
/**
* <code>SelectionListener</code> of Disconnect Button from
* <code>EngineView</code>
*/
class DisconnectButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
if( Activator.getDefault().getEcp1Client().isRunning()) {
// start ecp1Client
IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getService(IHandlerService.class);
try {
handlerService.executeCommand("de.ptb.epics.eve.viewer.disconnectCommand", null);
} catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
}
/**
* <code>SelectionListener</code> of AutoPlayOn Button from
* <code>EngineView</code>
*/
class AutoPlayOnButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected( final SelectionEvent e ) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected( final SelectionEvent e ) {
System.out.println("AutoPlayOn Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayListController().setAutoplay(true);
}
}
/**
* <code>SelectionListener</code> of AutoPlayOff Button from
* <code>EngineView</code>
*/
class AutoPlayOffButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected( final SelectionEvent e ) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected( final SelectionEvent e ) {
System.out.println("AutoPlayOff Knopf im Engine Window gedrückt!");
Activator.getDefault().getEcp1Client().getPlayListController().setAutoplay(false);
}
}
/**
* <code>SelectionListener</code> of SendtoFile Button from
* <code>EngineView</code>
*/
class CommentSendButtonSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
// TODO Auto-generated method stub
Activator.getDefault().getEcp1Client().getPlayController().addLiveComment(commentText.getText());
}
}
}
|
// 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,
// persons to whom the Software is furnished to do so, subject to the
// notice shall be included in all copies or substantial portions of the
// Software.
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// 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 phasereditor.scene.ui.editor.interactive;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.wb.swt.SWTResourceManager;
import phasereditor.scene.core.ObjectModel;
import phasereditor.scene.core.OriginComponent;
import phasereditor.scene.core.TransformComponent;
import phasereditor.scene.ui.editor.SceneEditor;
import phasereditor.scene.ui.editor.undo.SingleObjectSnapshotOperation;
import phasereditor.ui.PhaserEditorUI;
/**
* @author arian
*
*/
@SuppressWarnings("boxing")
public class ScaleTool extends InteractiveTool {
private static final int BOX = 14;
private int _globalX;
private int _globalY;
private boolean _changeX;
private boolean _changeY;
private boolean _hightlights;
public ScaleTool(SceneEditor editor, boolean changeX, boolean changeY) {
super(editor);
_changeX = changeX;
_changeY = changeY;
}
@Override
protected boolean canEdit(ObjectModel model) {
return model instanceof TransformComponent;
}
@Override
public void render(GC gc) {
var renderer = getRenderer();
var centerGlobalX = 0;
var centerGlobalY = 0;
var globalX = 0;
var globalY = 0;
var globalAngle = 0f;
for (var model : getModels()) {
var size = getRenderer().getObjectSize(model);
var modelX = size[0];
var modelY = size[1];
var globalXY = renderer.localToScene(model, modelX, modelY);
centerGlobalX += globalXY[0];
centerGlobalY += globalXY[1];
globalAngle += renderer.globalAngle(model);
if (_changeX && _changeY) {
globalX = centerGlobalX;
globalY = centerGlobalY;
} else {
var xy = renderer.localToScene(model, _changeX ? size[0] : size[0] / 2,
_changeY ? size[1] : size[1] / 2);
globalX += (int) xy[0];
globalY += (int) xy[1];
}
}
var size = getModels().size();
globalX = globalX / size;
globalY = globalY / size;
centerGlobalX = centerGlobalX / size;
centerGlobalY = centerGlobalY / size;
globalAngle = globalAngle / size;
_globalX = globalX;
_globalY = globalY;
// paint
if (doPaint()) {
if (_changeX && _changeY) {
fillRect(gc, globalX, globalY, globalAngle, BOX,
SWTResourceManager.getColor(_hightlights ? SWT.COLOR_WHITE : SWT.COLOR_YELLOW));
} else {
gc.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
gc.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
var color = SWTResourceManager
.getColor(_hightlights ? SWT.COLOR_WHITE : (_changeX ? SWT.COLOR_RED : SWT.COLOR_GREEN));
gc.setBackground(color);
gc.setForeground(color);
fillRect(gc, globalX, globalY, globalAngle + (_changeY ? 90 : 0), BOX, color);
}
}
}
@Override
public boolean contains(int sceneX, int sceneY) {
if (_dragging) {
return true;
}
var contains = PhaserEditorUI.distance(sceneX, sceneY, _globalX, _globalY) <= BOX;
_hightlights = contains;
return contains;
}
@Override
public void mouseMove(MouseEvent e) {
if (_dragging && contains(e.x, e.y)) {
var renderer = getRenderer();
for (var model : getModels()) {
var matrix = (float[]) model.get("initial-matrix");
var localCursor = renderer.sceneToLocal(matrix, e.x, e.y);
var initialLocalCursor = (float[]) model.get("initial-cursor-local-xy");
var localDX = localCursor[0] - initialLocalCursor[0];
var localDY = localCursor[1] - initialLocalCursor[1];
var size = getRenderer().getObjectSize(model);
var scaleX = (float) model.get("initial-scaleX");
var scaleY = (float) model.get("initial-scaleY");
var scaleDX = localDX / size[0] * scaleX;
var scaleDY = localDY / size[1] * scaleY;
var newScaleX = scaleX + scaleDX;
var newScaleY = scaleY + scaleDY;
var x = (float) model.get("initial-x") + localDX * scaleX * OriginComponent.get_originX(model);
var y = (float) model.get("initial-y") + localDY * scaleY * OriginComponent.get_originY(model);
if (_changeX) {
TransformComponent.set_scaleX(model, newScaleX);
TransformComponent.set_x(model, x);
}
if (_changeY) {
TransformComponent.set_scaleY(model, newScaleY);
TransformComponent.set_y(model, y);
}
model.setDirty(true);
}
getEditor().updatePropertyPagesContentWithSelection();
}
}
@Override
public void mouseDown(MouseEvent e) {
if (contains(e.x, e.y)) {
_dragging = true;
var renderer = getRenderer();
for (var model : getModels()) {
var scaleX = TransformComponent.get_scaleX(model);
var scaleY = TransformComponent.get_scaleY(model);
model.put("initial-scaleX", scaleX);
model.put("initial-scaleY", scaleY);
model.put("initial-x", TransformComponent.get_x(model));
model.put("initial-y", TransformComponent.get_y(model));
model.put("initial-cursor-local-xy", renderer.sceneToLocal(model, e.x, e.y));
model.put("initial-matrix", renderer.getObjectMatrix(model));
}
}
}
@Override
public void mouseUp(MouseEvent e) {
if (_dragging) {
var editor = getEditor();
getModels().forEach(model -> {
model.put("final-scaleX", TransformComponent.get_scaleX(model));
model.put("final-scaleY", TransformComponent.get_scaleY(model));
model.put("final-x", TransformComponent.get_x(model));
model.put("final-y", TransformComponent.get_y(model));
TransformComponent.set_scaleX(model, (float) model.get("initial-scaleX"));
TransformComponent.set_scaleY(model, (float) model.get("initial-scaleY"));
TransformComponent.set_x(model, (float) model.get("initial-x"));
TransformComponent.set_y(model, (float) model.get("initial-y"));
});
var before = SingleObjectSnapshotOperation.takeSnapshot(getModels());
getModels().forEach(model -> {
TransformComponent.set_scaleX(model, (float) model.get("final-scaleX"));
TransformComponent.set_scaleY(model, (float) model.get("final-scaleY"));
TransformComponent.set_x(model, (float) model.get("final-x"));
TransformComponent.set_y(model, (float) model.get("final-y"));
});
var after = SingleObjectSnapshotOperation.takeSnapshot(getModels());
editor.executeOperation(new SingleObjectSnapshotOperation(before, after, "Set scale.", true));
editor.setDirty(true);
if (editor.getOutline() != null) {
editor.refreshOutline_basedOnId();
}
getScene().redraw();
}
_dragging = false;
}
}
|
package de.st_ddt.crazylogin.crypt;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.bukkit.configuration.ConfigurationSection;
import de.st_ddt.crazylogin.LoginPlugin;
import de.st_ddt.crazylogin.data.LoginData;
import de.st_ddt.crazyplugin.exceptions.CrazyCommandException;
import de.st_ddt.crazyplugin.exceptions.CrazyException;
public final class EncryptHelper
{
private static final char[] CRYPTCHARS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final Map<String, Class<? extends Encryptor>> encryptors = new TreeMap<String, Class<? extends Encryptor>>(String.CASE_INSENSITIVE_ORDER);
protected EncryptHelper()
{
super();
}
public static Encryptor getEncryptor(final LoginPlugin<? extends LoginData> plugin, final ConfigurationSection config)
{
if (config == null)
return null;
final String algorithm = config.getString("name");
Class<? extends Encryptor> clazz = null;
if (algorithm != null)
clazz = encryptors.get(algorithm.toLowerCase());
if (clazz == null)
{
final String type = config.getString("type");
if (type != null)
try
{
clazz = Class.forName(type).asSubclass(Encryptor.class);
}
catch (final ClassNotFoundException e)
{}
}
if (clazz == null)
return null;
try
{
return clazz.getConstructor(LoginPlugin.class, ConfigurationSection.class).newInstance(plugin, config);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* Required for updating Encryptor names in new Version!
*/
public static Encryptor getEncryptor(final LoginPlugin<? extends LoginData> plugin, final String algorithm, final ConfigurationSection config)
{
final Class<? extends Encryptor> clazz = encryptors.get(algorithm.toLowerCase());
if (clazz == null)
return null;
try
{
return clazz.getConstructor(LoginPlugin.class, ConfigurationSection.class).newInstance(plugin, config);
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
public static Encryptor getEncryptor(final LoginPlugin<? extends LoginData> plugin, final String algorithm, final String[] args) throws CrazyException
{
final Class<? extends Encryptor> clazz = encryptors.get(algorithm.toLowerCase());
if (clazz == null)
return null;
try
{
return clazz.getConstructor(LoginPlugin.class, String[].class).newInstance(plugin, args);
}
catch (final InvocationTargetException e)
{
final Throwable t = e.getCause();
if (t instanceof CrazyCommandException)
((CrazyCommandException) t).addCommandPrefix(algorithm);
if (t instanceof CrazyException)
throw (CrazyException) t;
e.printStackTrace();
return null;
}
catch (final Exception e)
{
e.printStackTrace();
return null;
}
}
public static void registerAlgorithm(final String algorithm, final Class<? extends Encryptor> clazz)
{
encryptors.put(algorithm.toLowerCase(), clazz);
}
public static Set<String> getAlgorithms()
{
return encryptors.keySet();
}
public static String byteArrayToHexString(final byte... args)
{
final char[] chars = new char[args.length * 2];
for (int i = 0; i < args.length; i++)
{
chars[i * 2] = CRYPTCHARS[(args[i] >> 4) & 0xF];
chars[i * 2 + 1] = CRYPTCHARS[(args[i]) & 0xF];
}
return new String(chars);
}
}
|
package org.rstudio.studio.client.workbench.views.source.editors.profiler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.rstudio.core.client.CodeNavigationTarget;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.FilePosition;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.events.EnsureHeightHandler;
import org.rstudio.core.client.events.EnsureVisibleHandler;
import org.rstudio.core.client.events.HasSelectionCommitHandlers;
import org.rstudio.core.client.events.SelectionCommitHandler;
import org.rstudio.core.client.files.FileSystemContext;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.widget.OperationWithInput;
import org.rstudio.core.client.widget.ProgressIndicator;
import org.rstudio.core.client.widget.ProgressOperationWithInput;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.FileDialogs;
import org.rstudio.studio.client.common.GlobalDisplay;
import org.rstudio.studio.client.common.ReadOnlyValue;
import org.rstudio.studio.client.common.SimpleRequestCallback;
import org.rstudio.studio.client.common.Value;
import org.rstudio.studio.client.common.filetypes.FileIconResources;
import org.rstudio.studio.client.common.filetypes.FileType;
import org.rstudio.studio.client.common.filetypes.ProfilerType;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.RemoteFileSystemContext;
import org.rstudio.studio.client.workbench.views.source.SourceWindowManager;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfileOperationRequest;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfileOperationResponse;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfilerContents;
import org.rstudio.studio.client.workbench.views.source.editors.profiler.model.ProfilerServerOperations;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.events.CollabEditStartParams;
import org.rstudio.studio.client.workbench.views.source.events.DocWindowChangedEvent;
import org.rstudio.studio.client.workbench.views.source.events.PopoutDocEvent;
import org.rstudio.studio.client.workbench.views.source.events.SourceNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.DocTabDragParams;
import org.rstudio.studio.client.workbench.views.source.model.SourceDocument;
import org.rstudio.studio.client.workbench.views.source.model.SourceNavigation;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
import org.rstudio.studio.client.workbench.views.source.model.SourceServerOperations;
import java.util.HashMap;
import java.util.HashSet;
public class ProfilerEditingTarget implements EditingTarget,
HasSelectionCommitHandlers<CodeNavigationTarget>
{
interface MyCommandBinder
extends CommandBinder<Commands, ProfilerEditingTarget>
{
}
private static final MyCommandBinder commandBinder =
GWT.create(MyCommandBinder.class);
@Inject
public ProfilerEditingTarget(ProfilerPresenter presenter,
Commands commands,
EventBus events,
ProfilerServerOperations server,
GlobalDisplay globalDisplay,
Provider<SourceWindowManager> pSourceWindowManager,
FileDialogs fileDialogs,
RemoteFileSystemContext fileContext,
WorkbenchContext workbenchContext,
EventBus eventBus,
SourceServerOperations sourceServer)
{
presenter_ = presenter;
commands_ = commands;
events_ = events;
server_ = server;
globalDisplay_ = globalDisplay;
pSourceWindowManager_ = pSourceWindowManager;
fileDialogs_ = fileDialogs;
fileContext_ = fileContext;
workbenchContext_ = workbenchContext;
eventBus_ = eventBus;
sourceServer_ = sourceServer;
if (!initializedEvents_)
{
initializedEvents_ = true;
initializeEvents();
}
}
public String getId()
{
return doc_.getId();
}
@Override
public void adaptToExtendedFileType(String extendedType)
{
}
@Override
public String getExtendedFileType()
{
return null;
}
public HasValue<String> getName()
{
return name_;
}
public String getTitle()
{
return name_.getValue();
}
public String getContext()
{
return null;
}
public ImageResource getIcon()
{
return FileIconResources.INSTANCE.iconProfiler();
}
@Override
public TextFileType getTextFileType()
{
return null;
}
public String getTabTooltip()
{
return "R Profiler";
}
public HashSet<AppCommand> getSupportedCommands()
{
HashSet<AppCommand> commands = fileType_.getSupportedCommands(commands_);
if (SourceWindowManager.isMainSourceWindow())
commands.add(commands_.popoutDoc());
else
commands.add(commands_.returnDocToMain());
return commands;
}
@Override
public boolean canCompilePdf()
{
return false;
}
@Override
public void verifyCppPrerequisites()
{
}
@Override
public Position search(String regex)
{
return null;
}
@Override
public Position search(Position startPos, String regex)
{
return null;
}
@Override
public void forceLineHighlighting()
{
}
public void focus()
{
}
public void onActivate()
{
commands_.saveProfileAs().setEnabled(true);
if (!htmlPathInitialized_) {
htmlPathInitialized_ = true;
String htmlPath = getContents().getHtmlPath();
if (htmlPath == null)
{
buildHtmlPath(new OperationWithInput<String>()
{
@Override
public void execute(String newHtmlPath)
{
persistHtmlPath(newHtmlPath);
view_.showProfilePage(newHtmlPath);
pSourceWindowManager_.get().maximizeSourcePaneIfNecessary();
}
});
}
else
{
view_.showProfilePage(htmlPath);
}
}
// If we're already hooked up for some reason, unhook.
// This shouldn't happen though.
if (commandHandlerReg_ != null)
{
Debug.log("Warning: onActivate called twice without intervening onDeactivate");
commandHandlerReg_.removeHandler();
commandHandlerReg_ = null;
}
commandHandlerReg_ = commandBinder.bind(commands_, this);
}
public void onDeactivate()
{
commands_.saveProfileAs().setEnabled(false);
recordCurrentNavigationPosition();
commandHandlerReg_.removeHandler();
commandHandlerReg_ = null;
}
@Override
public void onInitiallyLoaded()
{
}
@Override
public void recordCurrentNavigationPosition()
{
events_.fireEvent(new SourceNavigationEvent(
SourceNavigation.create(
getId(),
getPath(),
SourcePosition.create(0, 0))));
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent,
boolean highlightLine)
{
}
@Override
public void restorePosition(SourcePosition position)
{
}
@Override
public SourcePosition currentPosition()
{
return null;
}
@Override
public void setCursorPosition(Position position)
{
}
@Override
public void ensureCursorVisible()
{
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
// always true because profiler docs don't have the
// concept of a position
return true;
}
@Override
public void highlightDebugLocation(SourcePosition startPos,
SourcePosition endPos,
boolean executing)
{
}
@Override
public void endDebugHighlighting()
{
}
@Override
public void beginCollabSession(CollabEditStartParams params)
{
}
@Override
public void endCollabSession()
{
}
public boolean onBeforeDismiss()
{
return true;
}
public ReadOnlyValue<Boolean> dirtyState()
{
return neverDirtyState_;
}
@Override
public boolean isSaveCommandActive()
{
return dirtyState().getValue();
}
@Override
public void forceSaveCommandActive()
{
}
public void save(Command onCompleted)
{
onCompleted.execute();
}
public void saveWithPrompt(Command onCompleted, Command onCancelled)
{
onCompleted.execute();
}
public void revertChanges(Command onCompleted)
{
onCompleted.execute();
}
private String getAndSetInitialName()
{
String name = getContents().getName();
boolean createProfile = getContents().getCreateProfile();
if (!StringUtil.isNullOrEmpty(name)) {
return name;
}
else if (createProfile) {
String defaultName = defaultNameProvider_.get();
persistDocumentProperty("name", defaultName);
return defaultName;
}
else {
String nameFromFile = FileSystemItem.getNameFromPath(getPath());
persistDocumentProperty("name", nameFromFile);
return nameFromFile;
}
}
public void initialize(SourceDocument document,
FileSystemContext fileContext,
FileType type,
Provider<String> defaultNameProvider)
{
// initialize doc, view, and presenter
doc_ = document;
view_ = new ProfilerEditingTargetWidget(commands_);
defaultNameProvider_ = defaultNameProvider;
getName().setValue(getAndSetInitialName());
presenter_.attatch(doc_, view_);
}
public void onDismiss(int dismissType)
{
presenter_.detach();
}
public long getFileSizeLimit()
{
return Long.MAX_VALUE;
}
public long getLargeFileSize()
{
return Long.MAX_VALUE;
}
public Widget asWidget()
{
return view_.asWidget();
}
public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler)
{
return new HandlerRegistration()
{
public void removeHandler()
{
}
};
}
public HandlerRegistration addEnsureHeightHandler(EnsureHeightHandler handler)
{
return new HandlerRegistration()
{
public void removeHandler()
{
}
};
}
@Override
public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler)
{
return new HandlerRegistration()
{
public void removeHandler()
{
}
};
}
public void fireEvent(GwtEvent<?> event)
{
assert false : "Not implemented";
}
public String getPath()
{
return getContents().getPath();
}
@Override
public HandlerRegistration addSelectionCommitHandler(SelectionCommitHandler<CodeNavigationTarget> handler)
{
return null;
}
@Handler
void onSaveSourceDocAs()
{
saveNewFile(getPath());
}
private void savePropertiesWithPath(String path)
{
String name = FileSystemItem.getNameFromPath(path);
persistDocumentProperty("name", name);
persistDocumentProperty("path", path);
getName().setValue(name, true);
name_.fireChangeEvent();
}
private ProfilerContents getContents()
{
return doc_.getProperties().cast();
}
private void buildHtmlPath(final OperationWithInput<String> continuation)
{
ProfileOperationRequest request = ProfileOperationRequest
.create(getPath());
server_.openProfile(request,
new ServerRequestCallback<ProfileOperationResponse>()
{
@Override
public void onResponseReceived(ProfileOperationResponse response)
{
if (response.getErrorMessage() != null)
{
globalDisplay_.showErrorMessage("Profiler Error",
response.getErrorMessage());
return;
}
continuation.execute(response.getHtmlFile());
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showErrorMessage("Failed to Open Profile",
error.getMessage());
}
});
}
private void persistHtmlPath(String htmlPath)
{
persistDocumentProperty("htmlPath", htmlPath);
}
private void persistDocumentProperty(String property, String value)
{
HashMap<String, String> props = new HashMap<String, String>();
props.put(property, value);
sourceServer_.modifyDocumentProperties(
doc_.getId(),
props,
new SimpleRequestCallback<Void>("Error")
{
@Override
public void onResponseReceived(Void response)
{
}
@Override
public void onError(ServerError error)
{
globalDisplay_.showErrorMessage("Failed to Save Profile Properties",
error.getMessage());
}
});
}
private void saveNewFile(final String suggestedPath)
{
FileSystemItem fsi;
if (suggestedPath != null)
fsi = FileSystemItem.createFile(suggestedPath).getParentPath();
else
fsi = workbenchContext_.getDefaultFileDialogDir();
fileDialogs_.saveFile(
"Save File - " + getName().getValue(),
fileContext_,
fsi,
fileType_.getDefaultExtension(),
false,
new ProgressOperationWithInput<FileSystemItem>()
{
public void execute(final FileSystemItem saveItem,
final ProgressIndicator indicator)
{
if (saveItem == null)
return;
workbenchContext_.setDefaultFileDialogDir(
saveItem.getParentPath());
final String toPath = saveItem.getPath();
server_.copyProfile(
getPath(),
toPath,
new ServerRequestCallback<JavaScriptObject>() {
@Override
public void onResponseReceived(JavaScriptObject response)
{
savePropertiesWithPath(saveItem.getPath());
indicator.onCompleted();
}
@Override
public void onError(ServerError error)
{
indicator.onCompleted();
globalDisplay_.showErrorMessage("Failed to Save Profile",
error.getMessage());
}
});
}
});
}
private Command postSaveProfileCommand()
{
return new Command()
{
public void execute()
{
}
};
}
private static void onMessage(String message, String file, int line)
{
if (message == "sourcefile")
{
FilePosition filePosition = FilePosition.create(line, 0);
CodeNavigationTarget navigationTarget = new CodeNavigationTarget(file, filePosition);
RStudioGinjector.INSTANCE.getFileTypeRegistry().editFile(
FileSystemItem.createFile(navigationTarget.getFile()),
filePosition);
}
}
@Handler
void onPopoutDoc()
{
events_.fireEvent(new PopoutDocEvent(getId(), currentPosition()));
}
@Handler
void onReturnDocToMain()
{
events_.fireEventToMainWindow(new DocWindowChangedEvent(
getId(), SourceWindowManager.getSourceWindowId(), "",
DocTabDragParams.create(getId(), currentPosition()),
null, 0));
}
private static native void initializeEvents() /*-{
var handler = $entry(function(e) {
if (typeof e.data != 'object')
return;
if (!e.origin.startsWith($wnd.location.origin))
return;
if (e.data.source != "profvis")
return;
@org.rstudio.studio.client.workbench.views.source.editors.profiler.ProfilerEditingTarget::onMessage(Ljava/lang/String;Ljava/lang/String;I)(e.data.message, e.data.file, e.data.line);
});
$wnd.addEventListener("message", handler, true);
}-*/;
private SourceDocument doc_;
private ProfilerEditingTargetWidget view_;
private final ProfilerPresenter presenter_;
private final Value<Boolean> neverDirtyState_ = new Value<Boolean>(false);
private final EventBus events_;
private final Commands commands_;
private final ProfilerServerOperations server_;
private final SourceServerOperations sourceServer_;
private final GlobalDisplay globalDisplay_;
private Provider<SourceWindowManager> pSourceWindowManager_;
private final FileDialogs fileDialogs_;
private final RemoteFileSystemContext fileContext_;
private final WorkbenchContext workbenchContext_;
private final EventBus eventBus_;
private Provider<String> defaultNameProvider_;
private ProfilerType fileType_ = new ProfilerType();
private HandlerRegistration commandHandlerReg_;
private boolean htmlPathInitialized_;
private static boolean initializedEvents_;
private Value<String> name_ = new Value<String>(null);
private String tempName_;
}
|
package com.infinityraider.infinitylib.crafting.dynamictexture;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.infinityraider.infinitylib.InfinityLib;
import com.infinityraider.infinitylib.crafting.IInfIngredientSerializer;
import com.infinityraider.infinitylib.item.BlockItemDynamicTexture;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tags.ITag;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.crafting.IIngredientSerializer;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
import java.util.Optional;
import java.util.stream.Stream;
public class DynamicTextureParentIngredient extends Ingredient implements IDynamicTextureIngredient {
public static final ResourceLocation ID = new ResourceLocation(InfinityLib.instance.getModId(), "dynamic_material_parent");
public static final Serializer SERIALIZER = new Serializer();
private final ItemStack parent;
private final DynamicTextureIngredient.BlockTagList tagList;
protected DynamicTextureParentIngredient(ItemStack parent, ResourceLocation tagId) {
this(parent, new DynamicTextureIngredient.BlockTagList((tagId)));
}
protected DynamicTextureParentIngredient(ItemStack parent, DynamicTextureIngredient.BlockTagList tagList) {
super(Stream.of(new Ingredient.SingleItemList(parent)));
this.parent = parent;
this.tagList = tagList;
}
public ItemStack getParent() {
return this.parent;
}
@Override
public ResourceLocation getTagId() {
return this.tagList.getTagId();
}
@Override
public ITag<Block> getTag() {
return this.tagList.getTag();
}
@Override
public ItemStack asStackWithMaterial(ItemStack material) {
ItemStack stack = this.getParent().copy();
if(stack.getItem() instanceof BlockItemDynamicTexture) {
((BlockItemDynamicTexture) stack.getItem()).setMaterial(stack, material);
}
return stack;
}
@Override
public boolean test(@Nullable ItemStack stack) {
return stack != null
&& !stack.isEmpty()
&& stack.getItem() instanceof BlockItemDynamicTexture;
}
@Override
public IIngredientSerializer<? extends Ingredient> getSerializer() {
return SERIALIZER;
}
private static final class Serializer implements IInfIngredientSerializer<DynamicTextureParentIngredient> {
@Override
public ResourceLocation getId() {
return ID;
}
@Override
public DynamicTextureParentIngredient parse(PacketBuffer buffer) {
return new DynamicTextureParentIngredient(buffer.readItemStack(), buffer.readResourceLocation());
}
@Override
public DynamicTextureParentIngredient parse(JsonObject json) {
if(!json.has("parent")) {
throw new JsonParseException("com.infinityraider.infinitylib.crafting.DynamicTextureParentIngredient requires a parent element");
}
if(!json.has("material")) {
throw new JsonParseException("com.infinityraider.infinitylib.crafting.DynamicTextureParentIngredient requires a material element");
}
ResourceLocation rl = new ResourceLocation(JSONUtils.getString(json, "parent"));
Item parent = Optional.ofNullable(ForgeRegistries.ITEMS.getValue(rl)).orElseThrow(() ->
new JsonSyntaxException("Unknown item '" + rl + "'"));
return new DynamicTextureParentIngredient(new ItemStack(parent), new ResourceLocation(JSONUtils.getString(json, "material")));
}
@Override
public void write(PacketBuffer buffer, DynamicTextureParentIngredient ingredient) {
buffer.writeItemStack(ingredient.getParent());
buffer.writeResourceLocation(ingredient.getTagId());
}
}
}
|
package dr.app.tools;
import dr.app.util.Arguments;
import dr.evolution.coalescent.CoalescentSimulator;
import dr.evolution.coalescent.ConstantPopulation;
import dr.evolution.coalescent.DemographicFunction;
import dr.evolution.coalescent.ExponentialGrowth;
import dr.evolution.tree.*;
import dr.evolution.util.Date;
import dr.evolution.util.Taxon;
import dr.evolution.util.Units;
import dr.evomodel.epidemiology.LogisticGrowthN0;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/**
* Simulated a virus tree given a transmission tree and dates of sampling
*
* @author mhall
*/
public class TransmissionTreeToVirusTree {
protected static PrintStream progressStream = System.out;
private enum ModelType{CONSTANT, EXPONENTIAL, LOGISTIC}
public static final String HELP = "help";
public static final String DEMOGRAPHIC_MODEL = "demoModel";
public static final String[] demographics = {"Constant", "Exponential", "Logistic"};
public static final String STARTING_POPULATION_SIZE = "N0";
public static final String GROWTH_RATE = "growthRate";
public static final String T50 = "t50";
private DemographicFunction demFunct;
private ArrayList<InfectedUnit> units;
private HashMap<String, InfectedUnit> idMap;
private String outputFileRoot;
private double coalescentProbability;
public TransmissionTreeToVirusTree(String fileName,
DemographicFunction demFunct, String outputFileRoot){
this.demFunct = demFunct;
units = new ArrayList<InfectedUnit>();
idMap = new HashMap<String, InfectedUnit>();
this.outputFileRoot = outputFileRoot;
coalescentProbability = 1;
try {
readInfectionEvents(fileName);
readSamplingEvents(fileName);
} catch(IOException e){
e.printStackTrace();
}
}
public TransmissionTreeToVirusTree(String sampFileName, String transFileName,
DemographicFunction demFunct, String outputFileRoot){
this.demFunct = demFunct;
units = new ArrayList<InfectedUnit>();
idMap = new HashMap<String, InfectedUnit>();
this.outputFileRoot = outputFileRoot;
try {
readInfectionEvents(transFileName);
readSamplingEvents(sampFileName);
} catch(IOException e){
e.printStackTrace();
}
}
private enum EventType{
INFECTION, SAMPLE
}
private void run() throws IOException{
ArrayList<FlexibleTree> detailedTrees = makeTrees();
ArrayList<FlexibleTree> simpleTrees = new ArrayList<FlexibleTree>();
for(FlexibleTree tree : detailedTrees) {
FlexibleTree wbTree = makeWellBehavedTree(tree);
wbTree.setAttribute("firstCase", tree.getAttribute("firstCase"));
simpleTrees.add(wbTree);
}
for(FlexibleTree tree: detailedTrees){
NexusExporter exporter = new NexusExporter(new PrintStream(outputFileRoot
+ tree.getAttribute("firstCase") + "_detailed.nex"));
exporter.exportTree(tree);
}
for(FlexibleTree tree: simpleTrees){
NexusExporter exporter = new NexusExporter(new PrintStream(outputFileRoot
+ tree.getAttribute("firstCase") + "_simple.nex"));
exporter.exportTree(tree);
}
}
private void readInfectionEvents(String fileName) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
ArrayList<String[]> keptLines = new ArrayList<String[]>();
reader.readLine();
String line = reader.readLine();
while(line!=null){
String[] entries = line.split(",");
keptLines.add(entries);
InfectedUnit unit = new InfectedUnit("ID_"+entries[1]);
units.add(unit);
idMap.put("ID_"+entries[1], unit);
line = reader.readLine();
}
for(String[] repeatLine: keptLines){
InfectedUnit infectee = idMap.get("ID_"+repeatLine[1]);
if(!repeatLine[2].equals("-1")){
InfectedUnit infector = idMap.get("ID_"+repeatLine[2]);
Event infection = new Event(EventType.INFECTION, Double.parseDouble(repeatLine[3]), infector, infectee);
infector.addInfectionEvent(infection);
infectee.setInfectionEvent(infection);
infectee.parent = infector;
} else {
Event infection = new Event(EventType.INFECTION, Double.parseDouble(repeatLine[3]), null, infectee);
infectee.setInfectionEvent(infection);
}
}
}
private void readSamplingEvents(String fileName) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(fileName));
reader.readLine();
String line = reader.readLine();
while(line!=null){
String[] entries = line.split(",");
if(!entries[7].equals("NA")) {
if (!idMap.containsKey("ID_"+entries[1])) {
throw new RuntimeException("Trying to add a sampling event to unit " + entries[2] + " but this " +
"unit not previously defined");
}
InfectedUnit unit = idMap.get("ID_"+entries[1]);
unit.addSamplingEvent(Double.parseDouble(entries[7]));
}
line = reader.readLine();
}
}
// events are only relevant if there is a sampling event somewhere further up the tree
private FlexibleTree makeTreelet(InfectedUnit unit, ArrayList<Event> relevantEvents){
if(relevantEvents.size()==0){
return null;
}
ArrayList<SimpleNode> nodes = new ArrayList<SimpleNode>();
unit.sortEvents();
double lastRelevantEventTime = Double.NEGATIVE_INFINITY;
for(Event event : relevantEvents){
if(event.time > lastRelevantEventTime){
lastRelevantEventTime = event.time;
}
}
double activeTime = lastRelevantEventTime - unit.infectionEvent.time;
for(Event event : relevantEvents){
Taxon taxon;
if(event.type == EventType.INFECTION){
taxon = new Taxon(event.infectee.id+"_infected_by_"+event.infector.id+"_"+event.time);
} else {
taxon = new Taxon(unit.id+"_sampled_"+event.time);
}
taxon.setDate(new Date(event.time - unit.infectionEvent.time, Units.Type.YEARS, false));
SimpleNode node = new SimpleNode();
node.setTaxon(taxon);
nodes.add(node);
node.setHeight(unit.infectionEvent.time - event.time);
node.setAttribute("Event", event);
}
FlexibleNode treeletRoot;
if(nodes.size()>1){
treeletRoot = simulateCoalescent(nodes, demFunct, activeTime);
} else {
treeletRoot = new FlexibleNode(new SimpleTree(nodes.get(0)), nodes.get(0), true);
treeletRoot.setHeight(0);
}
// add the root branch length
FlexibleNode infectionNode = new FlexibleNode();
infectionNode.setHeight(activeTime);
infectionNode.addChild(treeletRoot);
treeletRoot.setLength(activeTime - treeletRoot.getHeight());
infectionNode.setAttribute("Event", unit.infectionEvent);
FlexibleTree outTree = new FlexibleTree(infectionNode);
for(int i=0; i<outTree.getNodeCount(); i++){
FlexibleNode node = (FlexibleNode)outTree.getNode(i);
node.setAttribute("Unit", unit.id);
}
return outTree;
}
private ArrayList<FlexibleTree> makeTrees(){
// find the first case
ArrayList<InfectedUnit> introducedCases = new ArrayList<InfectedUnit>();
for(InfectedUnit unit : units){
if(unit.parent==null){
introducedCases.add(unit);
}
}
if(introducedCases.size()==0){
throw new RuntimeException("Can't find a first case");
}
ArrayList<FlexibleTree> out = new ArrayList<FlexibleTree>();
for(InfectedUnit introduction : introducedCases) {
coalescentProbability = 1;
System.out.println("Building tree for descendants of " + introduction.id);
FlexibleNode outTreeRoot = makeSubtree(introduction);
if (outTreeRoot != null) {
FlexibleTree finalTree = new FlexibleTree(outTreeRoot, false, true);
finalTree.setAttribute("firstCase", introduction.id);
out.add(finalTree);
if(coalescentProbability<0.9){
progressStream.println("WARNING: any phylogeny for descendants of "+introduction.id+" is quite " +
"improbable (p<"+(coalescentProbability)+") given this demographic function. Consider " +
"another.");
}
} else {
progressStream.println("This individual has no sampled descendants");
}
System.out.println();
}
return out;
}
// make the tree from this unit up
private FlexibleNode makeSubtree(InfectedUnit unit){
HashMap<Event, FlexibleNode> eventToSubtreeRoot = new HashMap<Event, FlexibleNode>();
ArrayList<Event> relevantEvents = new ArrayList<Event>();
for(Event event : unit.childEvents){
if(event.type == EventType.INFECTION){
FlexibleNode childSubtreeRoot = makeSubtree(event.infectee);
if(childSubtreeRoot!=null){
relevantEvents.add(event);
eventToSubtreeRoot.put(event, childSubtreeRoot);
}
} else if(event.type==EventType.SAMPLE) {
relevantEvents.add(event);
}
}
FlexibleTree unitTreelet = makeTreelet(unit, relevantEvents);
if(unitTreelet==null){
return null;
}
for(int i=0; i<unitTreelet.getExternalNodeCount(); i++){
FlexibleNode tip = (FlexibleNode)unitTreelet.getExternalNode(i);
Event tipEvent = (Event)unitTreelet.getNodeAttribute(tip, "Event");
if(tipEvent.type == EventType.INFECTION){
FlexibleNode subtreeRoot = eventToSubtreeRoot.get(tipEvent);
FlexibleNode firstSubtreeSplit = subtreeRoot.getChild(0);
subtreeRoot.removeChild(firstSubtreeSplit);
tip.addChild(firstSubtreeSplit);
}
}
return (FlexibleNode)unitTreelet.getRoot();
}
private FlexibleNode simulateCoalescent(ArrayList<SimpleNode> nodes, DemographicFunction demogFunct,
double maxHeight){
double earliestNodeHeight = Double.NEGATIVE_INFINITY;
for(SimpleNode node : nodes){
if(node.getHeight()>earliestNodeHeight){
earliestNodeHeight = node.getHeight();
}
}
double maxLastInterval = earliestNodeHeight;
double probNoCoalesenceInTime = Math.exp(demogFunct.getIntensity(maxLastInterval));
coalescentProbability *= (1-probNoCoalesenceInTime);
CoalescentSimulator simulator = new CoalescentSimulator();
SimpleNode root;
SimpleNode[] simResults;
int failCount = 0;
do {
simResults = simulator.simulateCoalescent(nodes.toArray(new SimpleNode[nodes.size()]),
demogFunct, -maxHeight, 0, true);
if(simResults.length>1){
failCount++;
System.out.println("Failed to coalesce lineages: "+failCount);
}
} while(simResults.length!=1);
root = simResults[0];
SimpleTree simpleTreelet = new SimpleTree(root);
for (int i=0; i<simpleTreelet.getNodeCount(); i++) {
SimpleNode node = (SimpleNode)simpleTreelet.getNode(i);
node.setHeight(node.getHeight() + maxHeight);
}
return new FlexibleNode(simpleTreelet, root, true);
}
private FlexibleTree makeWellBehavedTree(FlexibleTree tree){
FlexibleTree newPhylogeneticTree = new FlexibleTree(tree, false);
newPhylogeneticTree.beginTreeEdit();
for(int i=0; i<newPhylogeneticTree.getInternalNodeCount(); i++){
FlexibleNode node = (FlexibleNode)newPhylogeneticTree.getInternalNode(i);
if(newPhylogeneticTree.getChildCount(node)==1){
FlexibleNode parent = (FlexibleNode)newPhylogeneticTree.getParent(node);
FlexibleNode child = (FlexibleNode)newPhylogeneticTree.getChild(node, 0);
if(parent!=null){
double childHeight = newPhylogeneticTree.getNodeHeight(child);
newPhylogeneticTree.removeChild(parent, node);
newPhylogeneticTree.addChild(parent, child);
newPhylogeneticTree.setNodeHeight(child, childHeight);
} else {
child.setParent(null);
newPhylogeneticTree.setRoot(child);
}
}
}
newPhylogeneticTree.endTreeEdit();
return new FlexibleTree(newPhylogeneticTree, true);
}
private class InfectedUnit{
private String id;
private ArrayList<Event> childEvents;
private Event infectionEvent;
private InfectedUnit parent;
private InfectedUnit(String id){
this.id = id;
parent = null;
childEvents = new ArrayList<Event>();
}
private void addSamplingEvent(double time){
if(time < infectionEvent.time){
throw new RuntimeException("Adding an event to case "+id+" before its infection time");
}
childEvents.add(new Event(EventType.SAMPLE, time));
}
private void setInfectionEvent(double time, InfectedUnit infector){
setInfectionEvent(new Event(EventType.INFECTION, time, infector, this));
}
private void setInfectionEvent(Event event){
for(Event childEvent : childEvents){
if(event.time > childEvent.time){
throw new RuntimeException("Setting infection time for case "+id+" after an existing child event");
}
}
infectionEvent = event;
}
private void addChildInfectionEvent(double time, InfectedUnit infectee){
addInfectionEvent(new Event(EventType.INFECTION, time, this, infectee));
}
private void addInfectionEvent(Event event){
if(infectionEvent!=null && event.time < infectionEvent.time){
throw new RuntimeException("Adding an infection event to case "+id+" at "+event.time+" before its " +
"infection time at "+infectionEvent.time);
}
childEvents.add(event);
}
private void sortEvents(){
Collections.sort(childEvents);
Collections.reverse(childEvents);
}
}
private class Event implements Comparable<Event>{
private EventType type;
private double time;
private InfectedUnit infector;
private InfectedUnit infectee;
private Event(EventType type, double time){
this.type = type;
this.time = time;
}
private Event(EventType type, double time, InfectedUnit infector, InfectedUnit infectee){
this.type = type;
this.time = time;
this.infector = infector;
this.infectee = infectee;
}
public int compareTo(Event event) {
return Double.compare(time, event.time);
}
}
public static void printUsage(Arguments arguments) {
arguments.printUsage("virusTreeBuilder", "<infections-file-name> <sample-file-name> <output-file-name-root>");
}
public static void main(String[] args){
ModelType model = ModelType.CONSTANT;
double startNe = 1;
double growthRate = 0;
double t50 = 0;
Arguments arguments = new Arguments(
new Arguments.Option[]{
new Arguments.StringOption(DEMOGRAPHIC_MODEL, demographics, false, "The type of within-host" +
" demographic function to use, default = constant"),
new Arguments.RealOption(STARTING_POPULATION_SIZE,"The effective population size at time zero" +
" (used in all models), default = 1"),
new Arguments.RealOption(GROWTH_RATE,"The effective population size growth rate (used in" +
" exponential and logistic models), default = 0"),
new Arguments.RealOption(T50,"The time point, relative to the time of infection in backwards " +
"time, at which the population is equal to half its final asymptotic value, in the " +
"logistic model default = 0")
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
System.out.println(ae);
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption(HELP)) {
printUsage(arguments);
System.exit(0);
}
if (arguments.hasOption(DEMOGRAPHIC_MODEL)) {
String modelString = arguments.getStringOption(DEMOGRAPHIC_MODEL);
if(modelString.toLowerCase().startsWith("c")){
model = ModelType.CONSTANT;
} else if(modelString.toLowerCase().startsWith("e")){
model = ModelType.EXPONENTIAL;
} else if(modelString.toLowerCase().startsWith("l")){
model = ModelType.LOGISTIC;
} else {
progressStream.print("Unrecognised demographic model type");
System.exit(1);
}
}
if(arguments.hasOption(STARTING_POPULATION_SIZE)){
startNe = arguments.getRealOption(STARTING_POPULATION_SIZE);
}
if(arguments.hasOption(GROWTH_RATE) && model!=ModelType.CONSTANT){
growthRate = arguments.getRealOption(GROWTH_RATE);
}
if(arguments.hasOption(T50) && model==ModelType.LOGISTIC){
t50 = arguments.getRealOption(T50);
}
DemographicFunction demoFunction = null;
switch(model){
case CONSTANT: {
demoFunction = new ConstantPopulation(Units.Type.YEARS);
((ConstantPopulation)demoFunction).setN0(startNe);
}
case EXPONENTIAL: {
demoFunction = new ExponentialGrowth(Units.Type.YEARS);
((ExponentialGrowth)demoFunction).setN0(startNe);
((ExponentialGrowth)demoFunction).setGrowthRate(growthRate);
}
case LOGISTIC: {
demoFunction = new LogisticGrowthN0(Units.Type.YEARS);
((LogisticGrowthN0)demoFunction).setN0(startNe);
((LogisticGrowthN0)demoFunction).setGrowthRate(growthRate);
((LogisticGrowthN0)demoFunction).setT50(t50);
}
}
final String[] args2 = arguments.getLeftoverArguments();
if(args2.length!=3){
printUsage(arguments);
System.exit(1);
}
String infectionsFileName = args2[0];
String samplesFileName = args2[1];
String outputFileRoot = args2[2];
TransmissionTreeToVirusTree instance = new TransmissionTreeToVirusTree(samplesFileName,
infectionsFileName, demoFunction, outputFileRoot);
try{
instance.run();
} catch (IOException e){
e.printStackTrace();
}
}
}
|
package dr.evomodel.continuous;
import dr.inference.model.*;
import dr.math.matrixAlgebra.Matrix;
import dr.util.Citable;
import dr.util.Citation;
import java.util.List;
/**
* @author Max Tolkoff
* @author Marc Suchard
*/
public class LatentFactorModel extends AbstractModelLikelihood implements Citable {
// private Matrix data;
// private Matrix factors;
// private Matrix loadings;
private final MatrixParameter data;
private final MatrixParameter factors;
private final MatrixParameter loadings;
private MatrixParameter sData;
private final DiagonalMatrix rowPrecision;
private final DiagonalMatrix colPrecision;
private final Parameter continuous;
private final boolean scaleData;
private final int dimFactors;
private final int dimData;
private final int nTaxa;
private boolean likelihoodKnown = false;
private boolean isDataScaled=false;
private boolean storedLikelihoodKnown;
private boolean residualKnown=false;
private boolean LxFKnown=false;
private boolean storedResidualKnown=false;
private boolean storedLxFKnown;
private boolean traceKnown=false;
private boolean storedTraceKnown;
private boolean logDetColKnown=false;
private boolean storedLogDetColKnown;
private double trace;
private double storedTrace;
private double logLikelihood;
private double storedLogLikelihood;
private double logDetCol;
private double storedLogDetCol;
private double[] residual;
private double[] LxF;
private double[] storedResidual;
private double[] storedLxF;
public LatentFactorModel(MatrixParameter data, MatrixParameter factors, MatrixParameter loadings,
DiagonalMatrix rowPrecision, DiagonalMatrix colPrecision,
boolean scaleData, Parameter continuous
) {
super("");
// data = new Matrix(dataIn.getParameterAsMatrix());
// factors = new Matrix(factorsIn.getParameterAsMatrix());
// loadings = new Matrix(loadingsIn.getParameterAsMatrix());
this.scaleData=scaleData;
this.data = data;
this.factors = factors;
// Put default bounds on factors
for (int i = 0; i < factors.getParameterCount(); ++i) {
Parameter p = factors.getParameter(i);
System.err.println(p.getId() + " " + p.getDimension());
p.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, p.getDimension()));
}
this.continuous=continuous;
this.loadings = loadings;
// Put default bounds on loadings
// loadings.addBounds();
this.rowPrecision = rowPrecision;
this.colPrecision = colPrecision;
addVariable(data);
addVariable(factors);
addVariable(loadings);
addVariable(rowPrecision);
addVariable(colPrecision);
dimFactors = factors.getRowDimension();
dimData = loadings.getColumnDimension();
// nTaxa = factors.getParameterCount();
// nTaxa = factors.getParameter(0).getDimension();
nTaxa = factors.getColumnDimension();
// System.out.print(nTaxa);
// System.out.print("\n");
// System.out.print(dimData);
// System.out.print("\n");
// System.out.println(dimFactors);
// System.out.println(data.getDimension());
// System.out.println(data.getRowDimension());
// System.out.println(data.getColumnDimension());
// System.out.println(new Matrix(data.getParameterAsMatrix()));
// System.out.println(new Matrix(factors.getParameterAsMatrix()));
if (nTaxa * dimData != data.getDimension()) {
throw new RuntimeException("LOADINGS MATRIX AND FACTOR MATRIX MUST HAVE EXTERNAL DIMENSIONS WHOSE PRODUCT IS EQUAL TO THE NUMBER OF DATA POINTS\n");
// System.exit(10);
}
if (dimData < dimFactors) {
throw new RuntimeException("MUST HAVE FEWER FACTORS THAN DATA POINTS\n");
}
residual=new double[loadings.getColumnDimension()*factors.getColumnDimension()];
LxF=new double[loadings.getColumnDimension()*factors.getColumnDimension()];
storedResidual=new double[residual.length];
storedLxF=new double[LxF.length];
if(!isDataScaled & !scaleData){
sData=this.data;
isDataScaled=true;
}
if(!isDataScaled){
sData = computeScaledData();
isDataScaled=true;
for (int i = 0; i <sData.getRowDimension() ; i++) {
for (int j = 0; j <sData.getColumnDimension() ; j++) {
this.data.setParameterValue(i,j,sData.getParameterValue(i,j));
System.out.println(this.data.getParameterValue(i,j));
}
}
data.fireParameterChangedEvent();
}
// computeResiduals();
// System.out.print(new Matrix(residual.toComponents()));
// System.out.print(calculateLogLikelihood());
}
// public Matrix getData(){
// Matrix ans=data;
// return ans;
// public Matrix getFactors(){
// Matrix ans=factors;
// return ans;
// public Matrix getLoadings(){
// Matrix ans=loadings;
// return ans;
// public Matrix getResidual(){
// Matrix ans=residual;
// return ans;
public MatrixParameter getFactors(){return factors;}
public MatrixParameter getColumnPrecision(){return colPrecision;}
public MatrixParameter getLoadings(){return loadings;}
public MatrixParameter getData(){return data;}
public MatrixParameter getScaledData(){return data;}
public int getFactorDimension(){return factors.getRowDimension();}
private void transposeThenMultiply(MatrixParameter Left, MatrixParameter Right, double[] answer){
int dim=Left.getRowDimension();
int n=Left.getColumnDimension();
int p=Right.getColumnDimension();
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
double sum = 0;
for (int k = 0; k < dim; k++)
sum += Left.getParameterValue(k, i) * Right.getParameterValue(k,j);
answer[i*p+j]=sum;
}
}
}
private void add(MatrixParameter Left, MatrixParameter Right, double[] answer){
int row=Left.getRowDimension();
int col=Left.getColumnDimension();
for (int i = 0; i <row ; i++) {
for (int j = 0; j < col; j++) {
answer[i*col+j]=Left.getParameterValue(i,j)+Right.getParameterValue(i,j);
}
}
}
private void subtract(MatrixParameter Left, double[] Right, double[] answer){
int row=Left.getRowDimension();
int col=Left.getColumnDimension();
boolean containsDiscrete=false;
for (int i = 0; i <row ; i++) {
if(continuous.getParameterValue(i)!=0){
for (int j = 0; j < col; j++) {
answer[i*col+j]=Left.getParameterValue(i,j)-Right[i*col+j];
}
}
else{
for (int j = 0; j <col; j++) {
Left.setParameterValueQuietly(i,j, Right[i*col+j]);
}
containsDiscrete=true;
}
}
if(containsDiscrete){
Left.fireParameterChangedEvent();}
}
private double TDTTrace(double[] array, DiagonalMatrix middle){
int innerDim=middle.getRowDimension();
int outerDim=array.length/innerDim;
double sum=0;
for (int j = 0; j <innerDim ; j++){
if(continuous.getParameterValue(j)!=0) {
for (int i = 0; i < outerDim; i++) {
double s1 = array[j * outerDim + i];
double s2 = middle.getParameterValue(j, j);
sum += s1 * s1 * s2;
}
}
}
return sum;
}
private MatrixParameter computeScaledData(){
MatrixParameter answer=new MatrixParameter(data.getParameterName() + ".scaled");
answer.setDimensions(data.getRowDimension(), data.getColumnDimension());
// Matrix answer=new Matrix(data.getRowDimension(), data.getColumnDimension());
double[][] aData=data.getParameterAsMatrix();
double[] meanList=new double[data.getRowDimension()];
double[] varList=new double[data.getRowDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for (int j=0; j<data.getRowDimension(); j++){
meanList[j]+=data.getParameterValue(j,i);
}
}
for(int i=0; i<data.getRowDimension(); i++){
meanList[i]=meanList[i]/data.getColumnDimension();
}
double[][] answerTemp=new double[data.getRowDimension()][data.getColumnDimension()];
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
answerTemp[j][i]=aData[j][i]-meanList[j];
}
}
// System.out.println(new Matrix(answerTemp));
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
varList[j]+=answerTemp[j][i]*answerTemp[j][i];
}
}
for(int i=0; i<data.getRowDimension(); i++){
varList[i]=varList[i]/(data.getColumnDimension()-1);
varList[i]=StrictMath.sqrt(varList[i]);
}
// System.out.println(data.getColumnDimension());
// System.out.println(data.getRowDimension());
for(int i=0; i<data.getColumnDimension(); i++){
for(int j=0; j<data.getRowDimension(); j++){
answer.setParameterValue(j,i, answerTemp[j][i]/varList[j]);
}
}
// System.out.println(new Matrix(answerTemp));
return answer;
}
private Matrix copy(CompoundParameter parameter, int dimMajor, int dimMinor) {
return new Matrix(parameter.getParameterValues(), dimMajor, dimMinor);
}
private void computeResiduals() {
// Parameter[] dataTemp=new Parameter[nTaxa];
// for(int i=0; i<nTaxa; i++)
// dataTemp[i] = new Parameter.Default(dimData);
// for(int j=0; j<dimData; j++)
// dataTemp[i].setParameterValue(j, data.getParameterValue(i*dimData+j));
// MatrixParameter dataMatrix=new MatrixParameter(null, dataTemp);
if(!LxFKnown){
transposeThenMultiply(loadings, factors, LxF);
LxFKnown=true;
}
subtract(data, LxF, residual);
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
// Do nothing
}
/**
* Additional state information, outside of the sub-model is stored by this call.
*/
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
storedLikelihoodKnown = likelihoodKnown;
storedLogDetColKnown=logDetColKnown;
storedLogDetCol=logDetCol;
storedTrace=trace;
storedTraceKnown=traceKnown;
storedResidualKnown=residualKnown;
storedLxFKnown=LxFKnown;
System.arraycopy(residual, 0, storedResidual, 0, residual.length);
System.arraycopy(LxF, 0, storedLxF, 0, residual.length);
}
/**
* After this call the model is guaranteed to have returned its extra state information to
* the values coinciding with the last storeState call.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood; // TODO Possible error in store/restore -- when changed to 42, no error arises
likelihoodKnown = storedLikelihoodKnown;
trace=storedTrace;
traceKnown=storedTraceKnown;
residualKnown=storedResidualKnown;
LxFKnown=storedLxFKnown;
residual=storedResidual;
storedResidual=new double[residual.length];
LxF=storedLxF;
storedLxF=new double[LxF.length];
logDetCol=storedLogDetCol;
logDetColKnown=storedLogDetColKnown;
}
/**
* This call specifies that the current state is accept. Most models will not need to do anything.
* Sub-models are handled automatically and do not need to be considered in this method.
*/
@Override
protected void acceptState() {
// Do nothing
}
/**
* This method is called whenever a parameter is changed.
* <p/>
* It is strongly recommended that the model component sets a "dirty" flag and does no
* further calculations. Recalculation is typically done when the model component is asked for
* some information that requires them. This mechanism is 'lazy' so that this method
* can be safely called multiple times with minimal computational cost.
*/
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
// if(variable==data){
// isDataScaled=false;
// residualKnown=false;
// traceKnown=false;
if(variable==factors){
LxFKnown=false;
residualKnown=false;
traceKnown=false;
// computeResiduals();
}
if(variable==loadings){
LxFKnown=false;
residualKnown=false;
traceKnown=false;
// computeResiduals();
}
if(variable==colPrecision){
logDetColKnown=false;
traceKnown=false;
}
likelihoodKnown = false;
}
/**
* @return a list of citations associated with this object
*/
@Override
public List<Citation> getCitations() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
/**
* Get the model.
*
* @return the model.
*/
@Override
public Model getModel() {
return this;
}
/**
* Get the log likelihood.
*
* @return the log likelihood.
*/
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = calculateLogLikelihood();
likelihoodKnown = true;
}
return logLikelihood;
}
/**
* Forces a complete recalculation of the likelihood next time getLikelihood is called
*/
@Override
public void makeDirty() {
likelihoodKnown = false;
}
private double calculateLogLikelihood() {
for(int i=0; i<StrictMath.min(loadings.getRowDimension(),loadings.getColumnDimension()); i++)
{
if(loadings.getParameter(i).getParameterValue(i)<0)
{
return Double.NEGATIVE_INFINITY;
}
}
// Matrix tRowPrecision= new Matrix(rowPrecision.getParameterAsMatrix());
// Matrix tColPrecision= new Matrix(colPrecision.getParameterAsMatrix());
if(!residualKnown){
residualKnown=true;
computeResiduals();
}
// expPart = residual.productInPlace(rowPrecision.productInPlace(residual.transposeThenProductInPlace(colPrecision, TResidualxC), RxTRxC), expPart);
// logDetRow=StrictMath.log(rowPrecision.getDeterminant());
if(!logDetColKnown){
logDetColKnown=true;
logDetCol=StrictMath.log(colPrecision.getDeterminant());
}
// System.out.println(logDetCol);
// System.out.println(logDetRow);
if(!traceKnown){
traceKnown=true;
trace=TDTTrace(residual, colPrecision);
}
// if(expPart.getRowDimension()!=expPart.getColumnDimension())
// System.err.print("Matrices are not conformable");
// System.exit(0);
// else{
// for(int i=0; i<expPart.getRowDimension(); i++){
// trace+=expPart.getParameterValue(i, i);
// System.out.println(expPart);
return -.5*trace + .5*data.getColumnDimension()*logDetCol
-.5*data.getRowDimension()*data.getColumnDimension()*Math.log(2.0 * StrictMath.PI);
}
}
|
package org.lightmare.jpa.hibernate.boot.registry.classloading.internal;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.util.ClassLoaderHelper;
import org.jboss.logging.Logger;
import org.lightmare.utils.CollectionUtils;
/**
* Implementation of class loader services
*
* @author Levan Tsinadze
*
*/
public class ClassLoaderServiceExt extends ClassLoaderServiceImpl {
private static final long serialVersionUID = 1L;
private static final Logger LOG = CoreLogging
.logger(ClassLoaderServiceExt.class);
@SuppressWarnings("rawtypes")
private final Map<Class, ServiceLoader> serviceLoaders = new HashMap<Class, ServiceLoader>();
private AggregatedClassLoader aggregatedClassLoader;
/**
* Constructs a {@link ClassLoaderServiceExt} with standard set-up
*/
public ClassLoaderServiceExt() {
this(ClassLoaderServiceExt.class.getClassLoader());
}
/**
* Constructs a ClassLoaderServiceExt with the given ClassLoader
*
* @param classLoader
* The ClassLoader to use
*/
public ClassLoaderServiceExt(ClassLoader classLoader) {
this(Collections.singletonList(classLoader));
}
/**
* Constructs a {@link ClassLoaderServiceExt} with the given ClassLoader
* instances
*
* @param providedClassLoaders
* The ClassLoader instances to use
*/
public ClassLoaderServiceExt(Collection<ClassLoader> providedClassLoaders) {
final LinkedHashSet<ClassLoader> orderedClassLoaderSet = new LinkedHashSet<ClassLoader>();
// first, add all provided class loaders, if any
if (providedClassLoaders != null) {
for (ClassLoader classLoader : providedClassLoaders) {
if (classLoader != null) {
orderedClassLoaderSet.add(classLoader);
}
}
}
// normalize adding known class-loaders...
// then the Hibernate class loader
orderedClassLoaderSet.add(ClassLoaderServiceExt.class.getClassLoader());
// then the TCCL, if one...
final ClassLoader tccl = locateTCCL();
if (tccl != null) {
orderedClassLoaderSet.add(tccl);
}
// finally the system classloader
final ClassLoader sysClassLoader = locateSystemClassLoader();
if (sysClassLoader != null) {
orderedClassLoaderSet.add(sysClassLoader);
}
// now build the aggregated class loader...
this.aggregatedClassLoader = new AggregatedClassLoader(
orderedClassLoaderSet);
}
public void addLoaders(ClassLoader... loaders) {
Collection<ClassLoader> providedLoaders;
if (CollectionUtils.valid(loaders)) {
providedLoaders = new HashSet<ClassLoader>(Arrays.asList(loaders));
} else {
providedLoaders = Collections.emptySet();
}
this.aggregatedClassLoader.addLoaders(providedLoaders);
;
}
/**
* No longer used/supported!
*
* @param configValues
* The config values
*
* @return The built service
*
* @deprecated No longer used/supported!
*/
@Deprecated
@SuppressWarnings({ "unchecked", "rawtypes" })
public static ClassLoaderServiceExt fromConfigSettings(Map configValues) {
final List<ClassLoader> providedClassLoaders = new ArrayList<ClassLoader>();
final Collection<ClassLoader> classLoaders = (Collection<ClassLoader>) configValues
.get(AvailableSettings.CLASSLOADERS);
if (classLoaders != null) {
for (ClassLoader classLoader : classLoaders) {
providedClassLoaders.add(classLoader);
}
}
addIfSet(providedClassLoaders, AvailableSettings.APP_CLASSLOADER,
configValues);
addIfSet(providedClassLoaders, AvailableSettings.RESOURCES_CLASSLOADER,
configValues);
addIfSet(providedClassLoaders, AvailableSettings.HIBERNATE_CLASSLOADER,
configValues);
addIfSet(providedClassLoaders,
AvailableSettings.ENVIRONMENT_CLASSLOADER, configValues);
if (providedClassLoaders.isEmpty()) {
LOG.debugf("Incoming config yielded no classloaders; adding standard SE ones");
final ClassLoader tccl = locateTCCL();
if (tccl != null) {
providedClassLoaders.add(tccl);
}
providedClassLoaders.add(ClassLoaderServiceExt.class
.getClassLoader());
}
return new ClassLoaderServiceExt(providedClassLoaders);
}
@SuppressWarnings("rawtypes")
private static void addIfSet(List<ClassLoader> providedClassLoaders,
String name, Map configVales) {
final ClassLoader providedClassLoader = (ClassLoader) configVales
.get(name);
if (providedClassLoader != null) {
providedClassLoaders.add(providedClassLoader);
}
}
protected static ClassLoader locateSystemClassLoader() {
try {
return ClassLoader.getSystemClassLoader();
} catch (Exception e) {
return null;
}
}
private static ClassLoader locateTCCL() {
try {
return ClassLoaderHelper.getContextClassLoader();
} catch (Exception e) {
return null;
}
}
private static class AggregatedClassLoader extends ClassLoader {
private ClassLoader[] individualClassLoaders;
private AggregatedClassLoader(
final LinkedHashSet<ClassLoader> orderedClassLoaderSet) {
super(null);
individualClassLoaders = orderedClassLoaderSet
.toArray(new ClassLoader[orderedClassLoaderSet.size()]);
}
public void addLoaders(Collection<ClassLoader> loaders) {
if (CollectionUtils.valid(loaders)) {
Set<ClassLoader> existeds = new LinkedHashSet<ClassLoader>(
Arrays.asList(individualClassLoaders));
existeds.addAll(loaders);
individualClassLoaders = existeds
.toArray(new ClassLoader[existeds.size()]);
}
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
final HashSet<URL> resourceUrls = new HashSet<URL>();
for (ClassLoader classLoader : individualClassLoaders) {
final Enumeration<URL> urls = classLoader.getResources(name);
while (urls.hasMoreElements()) {
resourceUrls.add(urls.nextElement());
}
}
return new Enumeration<URL>() {
final Iterator<URL> resourceUrlIterator = resourceUrls
.iterator();
@Override
public boolean hasMoreElements() {
return resourceUrlIterator.hasNext();
}
@Override
public URL nextElement() {
return resourceUrlIterator.next();
}
};
}
@Override
protected URL findResource(String name) {
for (ClassLoader classLoader : individualClassLoaders) {
final URL resource = classLoader.getResource(name);
if (resource != null) {
return resource;
}
}
return super.findResource(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
for (ClassLoader classLoader : individualClassLoaders) {
try {
return classLoader.loadClass(name);
} catch (Exception ignore) {
}
}
throw new ClassNotFoundException(
"Could not load requested class : " + name);
}
public void destroy() {
individualClassLoaders = null;
}
}
@Override
@SuppressWarnings({ "unchecked" })
public <T> Class<T> classForName(String className) {
try {
return (Class<T>) Class.forName(className, true,
aggregatedClassLoader);
} catch (Exception e) {
throw new ClassLoadingException("Unable to load class ["
+ className + "]", e);
}
}
@Override
public URL locateResource(String name) {
// first we try name as a URL
try {
return new URL(name);
} catch (Exception ignore) {
}
try {
return aggregatedClassLoader.getResource(name);
} catch (Exception ignore) {
}
return null;
}
@Override
public InputStream locateResourceStream(String name) {
// first we try name as a URL
try {
LOG.tracef("trying via [new URL(\"%s\")]", name);
return new URL(name).openStream();
} catch (Exception ignore) {
}
try {
LOG.tracef("trying via [ClassLoader.getResourceAsStream(\"%s\")]",
name);
final InputStream stream = aggregatedClassLoader
.getResourceAsStream(name);
if (stream != null) {
return stream;
}
} catch (Exception ignore) {
}
final String stripped = name.startsWith("/") ? name.substring(1) : null;
if (stripped != null) {
try {
LOG.tracef("trying via [new URL(\"%s\")]", stripped);
return new URL(stripped).openStream();
} catch (Exception ignore) {
}
try {
LOG.tracef(
"trying via [ClassLoader.getResourceAsStream(\"%s\")]",
stripped);
final InputStream stream = aggregatedClassLoader
.getResourceAsStream(stripped);
if (stream != null) {
return stream;
}
} catch (Exception ignore) {
}
}
return null;
}
@Override
public List<URL> locateResources(String name) {
final ArrayList<URL> urls = new ArrayList<URL>();
try {
final Enumeration<URL> urlEnumeration = aggregatedClassLoader
.getResources(name);
if (urlEnumeration != null && urlEnumeration.hasMoreElements()) {
while (urlEnumeration.hasMoreElements()) {
urls.add(urlEnumeration.nextElement());
}
}
} catch (Exception ignore) {
}
return urls;
}
@Override
@SuppressWarnings("unchecked")
public <S> LinkedHashSet<S> loadJavaServices(Class<S> serviceContract) {
ServiceLoader<S> serviceLoader;
if (serviceLoaders.containsKey(serviceContract)) {
serviceLoader = serviceLoaders.get(serviceContract);
} else {
serviceLoader = ServiceLoader.load(serviceContract,
aggregatedClassLoader);
serviceLoaders.put(serviceContract, serviceLoader);
}
final LinkedHashSet<S> services = new LinkedHashSet<S>();
for (S service : serviceLoader) {
services.add(service);
}
return services;
}
@SuppressWarnings("rawtypes")
@Override
public void stop() {
for (ServiceLoader serviceLoader : serviceLoaders.values()) {
serviceLoader.reload(); // clear service loader providers
}
serviceLoaders.clear();
if (aggregatedClassLoader != null) {
aggregatedClassLoader.destroy();
aggregatedClassLoader = null;
}
}
// completely temporary !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/**
* Hack around continued (temporary) need to sometimes set the TCCL for code
* we call that expects it.
*
* @param <T>
* The result type
*/
public static interface Work<T> {
/**
* The work to be performed with the TCCL set
*
* @return The result of the work
*/
public T perform();
}
/**
* Perform some discrete work with with the TCCL set to our aggregated
* ClassLoader
*
* @param work
* The discrete work to be done
* @param <T>
* The type of the work result
*
* @return The work result.
*/
public <T> T withTccl(Work<T> work) {
final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
boolean set = false;
try {
Thread.currentThread().setContextClassLoader(aggregatedClassLoader);
set = true;
} catch (Exception ignore) {
}
try {
return work.perform();
} finally {
if (set) {
Thread.currentThread().setContextClassLoader(tccl);
}
}
}
}
|
package dr.inference.operators;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inferencexml.operators.DirtyLikelihoodOperatorParser;
/**
* @author Marc Suchard
*/
public abstract class InvariantOperator extends SimpleMCMCOperator implements GibbsOperator {
private InvariantOperator(Parameter parameter, Likelihood likelihood, double weight,
boolean checkLikelihood) {
this.parameter = parameter;
this.likelihood = likelihood;
this.checkLikelihood = checkLikelihood || DEBUG;
setWeight(weight);
}
public String getPerformanceSuggestion() {
return null;
}
public String getOperatorName() {
return DirtyLikelihoodOperatorParser.TOUCH_OPERATOR;
}
@Override
public double doOperation() {
double logLikelihood = 0;
if (checkLikelihood) {
if (likelihood != null) {
logLikelihood = likelihood.getLogLikelihood();
}
}
if (pathParameter == 1.0) {
transform(parameter);
}
if (checkLikelihood) {
if (likelihood != null) {
double newLogLikelihood = likelihood.getLogLikelihood();
if (Math.abs(logLikelihood - newLogLikelihood) > tolerance) {
String sb = "Likelihood is not invariant to transformation:\n" +
"Before: " + logLikelihood + "\n" +
"After : " + newLogLikelihood + "\n";
throw new RuntimeException(sb);
}
}
}
return 0;
}
@Override
public void setPathParameter(double beta) {
pathParameter = beta;
}
private double pathParameter = 1.0;
protected abstract void transform(Parameter parameter);
public int getStepCount() {
return 1;
}
private final Parameter parameter;
private final Likelihood likelihood;
private final boolean checkLikelihood;
private final static boolean DEBUG = false;
private final static double tolerance = 1E-1;
public static class Rotation extends InvariantOperator {
private final boolean translationInvariant;
private final boolean rotationInvariant;
private final int dim;
public Rotation(Parameter parameter, int dim,
double weight, Likelihood likelihood,
boolean translate, boolean rotate,
boolean checkLikelihood) {
super(parameter, likelihood, weight, checkLikelihood);
this.dim = dim;
this.translationInvariant = translate;
this.rotationInvariant = rotate;
}
@Override
protected void transform(Parameter parameter) {
double[] x = parameter.getParameterValues();
EllipticalSliceOperator.transformPoint(x, translationInvariant, rotationInvariant, dim);
final int len = x.length;
for (int i = 0; i < len; ++i) {
parameter.setParameterValueQuietly(i, x[i]);
}
parameter.fireParameterChangedEvent();
}
}
}
|
package dr.inference.operators;
import dr.inference.model.Parameter;
import dr.xml.*;
public class RejectionOperator extends SimpleMCMCOperator {
public interface RejectionProvider extends GibbsOperator {
double[] getProposedUpdate();
Parameter getParameter();
}
public interface AcceptCondition {
boolean satisfiesCondition(double[] values);
}
public enum SimpleAcceptCondition implements AcceptCondition {
DescendingAbsoluteValue("descendingAbsoluteValue") {
@Override
public boolean satisfiesCondition(double[] values) {
for (int i = 1; i < values.length; i++) {
if (Math.abs(values[i - 1]) < Math.abs(values[i])) {
return false;
}
}
return true;
}
},
// DescendingAbsoluteValueSpaced("descendingAbsoluteValueSpaced") {
// @Override
// public boolean satisfiesCondition(double[] values) {
// for (int i = 1; i < values.length; i++) {
// if (0.9 * Math.abs(values[i - 1]) < Math.abs(values[i])) {
// return false;
// return true;
AlternatingSigns("descendingAlternatingSigns") {
@Override
public boolean satisfiesCondition(double[] values) {
for (int i = 1; i < values.length; i++) {
Boolean signa = (values[i] > 0);
Boolean signb = (values[i - 1] > 0);
if (Math.abs(values[i - 1]) < Math.abs(values[i]) || signa == signb) {
return false;
}
}
return true;
}
};
private final String name;
SimpleAcceptCondition(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public abstract boolean satisfiesCondition(double[] values);
}
public static class DescendingAndSpacedCondition implements AcceptCondition {
private final double spacing;
DescendingAndSpacedCondition(double spacing) {
this.spacing = spacing;
}
@Override
public boolean satisfiesCondition(double[] values) {
for (int i = 1; i < values.length; i++) {
if (spacing * Math.abs(values[i - 1]) < Math.abs(values[i])) {
return false;
}
}
return true;
}
private static final String DESCENDING_AND_SPACED = "descendingAndSpaced";
private static final String SPACING = "spacing";
public static AbstractXMLObjectParser PARSER = new AbstractXMLObjectParser() {
@Override
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
double spacing = xo.getDoubleAttribute(SPACING);
if (spacing < 0.0 || spacing > 1.0) {
throw new XMLParseException("Attribute '" + SPACING + "' must be between 0 and 1.");
}
return new DescendingAndSpacedCondition(spacing);
}
@Override
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[]{
AttributeRule.newDoubleRule(SPACING)
};
}
@Override
public String getParserDescription() {
return "Condition requiring parameter to have descending absolute values with some minimum spacing.";
}
@Override
public Class getReturnType() {
return DescendingAndSpacedCondition.class;
}
@Override
public String getParserName() {
return DESCENDING_AND_SPACED;
}
};
}
private final RejectionProvider gibbsOp;
private final AcceptCondition condition;
public RejectionOperator(RejectionProvider gibbsOp, AcceptCondition condition, double weight) {
setWeight(weight);
this.gibbsOp = gibbsOp;
this.condition = condition;
}
@Override
public String getOperatorName() {
return REJECTION_OPERATOR;
}
@Override
public double doOperation() {
double[] values = gibbsOp.getProposedUpdate();
if (condition.satisfiesCondition(values)) {
Parameter parameter = gibbsOp.getParameter();
for (int i = 0; i < parameter.getDimension(); i++) {
parameter.setParameterValueQuietly(i, values[i]);
}
parameter.fireParameterChangedEvent();
return Double.POSITIVE_INFINITY;
}
return Double.NEGATIVE_INFINITY;
}
private static final String REJECTION_OPERATOR = "rejectionOperator";
private static final String CONDITION = "condition";
public static AbstractXMLObjectParser PARSER = new AbstractXMLObjectParser() {
@Override
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
RejectionProvider gibbsOp = (RejectionProvider) xo.getChild(RejectionProvider.class);
double weight = xo.getAttribute(WEIGHT, gibbsOp.getWeight());
AcceptCondition condition = null;
String stringCondition = xo.getStringAttribute(CONDITION);
if (stringCondition == null) {
condition = (AcceptCondition) xo.getChild(AcceptCondition.class);
} else {
for (SimpleAcceptCondition simpleCondition : SimpleAcceptCondition.values()) {
if (stringCondition.equalsIgnoreCase(simpleCondition.getName())) {
condition = simpleCondition;
break;
}
}
if (condition == null) {
throw new XMLParseException("Unrecognized condition type: " + stringCondition);
}
}
return new RejectionOperator(gibbsOp, condition, weight);
}
@Override
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[]{
new ElementRule(RejectionProvider.class),
new XORRule(
AttributeRule.newStringRule(CONDITION),
new ElementRule(AcceptCondition.class)
),
AttributeRule.newDoubleRule(WEIGHT, true)
};
}
@Override
public String getParserDescription() {
return "A rejection sampler that always accepts a Gibbs proposal if a condition is met (and always rejects otherwise)";
}
@Override
public Class getReturnType() {
return RejectionOperator.class;
}
@Override
public String getParserName() {
return REJECTION_OPERATOR;
}
};
}
|
package org.jenkinsci.plugins.pretestedintegration.integration.scm.git;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.Result;
import hudson.plugins.git.BranchSpec;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.SubmoduleConfig;
import hudson.plugins.git.UserRemoteConfig;
import hudson.plugins.git.extensions.GitSCMExtension;
import hudson.plugins.git.extensions.impl.CleanCheckout;
import hudson.plugins.git.extensions.impl.PruneStaleBranch;
import hudson.triggers.SCMTrigger;
import hudson.util.RunList;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.jenkinsci.plugins.pretestedintegration.PretestedIntegrationBuildWrapper;
import org.jenkinsci.plugins.pretestedintegration.PretestedIntegrationPostCheckout;
import org.jenkinsci.plugins.pretestedintegration.scm.git.GitBridge;
import org.jenkinsci.plugins.pretestedintegration.scm.git.SquashCommitStrategy;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class SquashCommitStrategyIT {
@Rule
public JenkinsRule jenkinsRule = new JenkinsRule();
private final File GIT_DIR = new File("test-repo/.git");
private final File GIT_PARENT_DIR = GIT_DIR.getParentFile().getAbsoluteFile();
private final String README_FILE_PATH = GIT_PARENT_DIR.getPath().concat("/" + "readme");
private final String AUTHER_NAME = "john Doe";
private final String AUTHER_EMAIL = "Joh@praqma.net";
private Repository repository;
private Git git;
private String readmeFileContents_fromDevBranch;
@After
public void tearDown() throws Exception {
repository.close();
if (GIT_PARENT_DIR.exists())
FileUtils.deleteDirectory(GIT_PARENT_DIR);
}
public void createValidRepositoryWith2FeatureBranches() throws IOException, GitAPIException {
if (GIT_PARENT_DIR.exists())
FileUtils.deleteDirectory(GIT_PARENT_DIR);
final String FEATURE_BRANCH_1_NAME = "ready/feature_1";
final String FEATURE_BRANCH_2_NAME = "ready/feature_2";
FileRepositoryBuilder builder = new FileRepositoryBuilder();
repository = builder.setGitDir(GIT_DIR.getAbsoluteFile())
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
if (!repository.isBare() && repository.getBranch() == null) {
repository.create();
}
git = new Git(repository);
File readme = new File(README_FILE_PATH);
if (!readme.exists())
FileUtils.writeStringToFile(readme, "sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 1").call();
FileUtils.writeStringToFile(readme, "changed sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 2").call();
CreateBranchCommand createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_1_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_1_NAME).call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n", true);
git.add().addFilepattern(readme.getName()).call();
CommitCommand commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n", true);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_2_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_2_NAME).call();
String readmeContents = FileUtils.readFileToString(readme);
FileUtils.writeStringToFile(readme, "FEATURE_2 branch commit 1\n\n" + readmeContents);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_2 branch commit 2\n\n" + readmeContents);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 2 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
readmeFileContents_fromDevBranch = FileUtils.readFileToString(new File(README_FILE_PATH));
}
public void createRepositoryWith2FeatureBranches1Valid1Invalid() throws IOException, GitAPIException {
if (GIT_PARENT_DIR.exists())
FileUtils.deleteDirectory(GIT_PARENT_DIR);
final String FEATURE_BRANCH_1_NAME = "ready/feature_1";
final String FEATURE_BRANCH_2_NAME = "ready/feature_2";
FileRepositoryBuilder builder = new FileRepositoryBuilder();
repository = builder.setGitDir(GIT_DIR.getAbsoluteFile())
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
if (!repository.isBare() && repository.getBranch() == null) {
repository.create();
}
git = new Git(repository);
File readme = new File(README_FILE_PATH);
if (!readme.exists())
FileUtils.writeStringToFile(readme, "sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 1").call();
FileUtils.writeStringToFile(readme, "changed sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 2").call();
CreateBranchCommand createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_1_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_1_NAME).call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n", true);
git.add().addFilepattern(readme.getName()).call();
CommitCommand commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n", true);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_2_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_2_NAME).call();
FileUtils.writeStringToFile(readme, "FEATURE_2 branch commit 1\n\n", true);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_2 branch commit 2\n\n", true);
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 2 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
readmeFileContents_fromDevBranch = FileUtils.readFileToString(new File(README_FILE_PATH));
}
public void createValidRepository() throws IOException, GitAPIException {
if (GIT_PARENT_DIR.exists())
FileUtils.deleteDirectory(GIT_PARENT_DIR);
final String FEATURE_BRANCH_NAME = "ready/feature_1";
FileRepositoryBuilder builder = new FileRepositoryBuilder();
repository = builder.setGitDir(GIT_DIR.getAbsoluteFile())
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
if (!repository.isBare() && repository.getBranch() == null) {
repository.create();
}
git = new Git(repository);
File readme = new File(README_FILE_PATH);
if (!readme.exists())
FileUtils.writeStringToFile(readme, "sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 1").call();
FileUtils.writeStringToFile(readme, "changed sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 2").call();
CreateBranchCommand createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_NAME).call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n");
git.add().addFilepattern(readme.getName()).call();
CommitCommand commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n");
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
readmeFileContents_fromDevBranch = FileUtils.readFileToString(new File(README_FILE_PATH));
}
private void createRepositoryWithMergeConflict() throws IOException, GitAPIException {
if (GIT_PARENT_DIR.exists())
FileUtils.deleteDirectory(GIT_PARENT_DIR);
final String FEATURE_BRANCH_NAME = "ready/feature_1";
FileRepositoryBuilder builder = new FileRepositoryBuilder();
repository = builder.setGitDir(GIT_DIR.getAbsoluteFile())
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
if (!repository.isBare() && repository.getBranch() == null) {
repository.create();
}
git = new Git(repository);
File readme = new File(README_FILE_PATH);
if (!readme.exists())
FileUtils.writeStringToFile(readme, "sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 1").call();
FileUtils.writeStringToFile(readme, "changed sample text\n");
git.add().addFilepattern(readme.getName()).call();
git.commit().setMessage("commit message 2").call();
CreateBranchCommand createBranchCommand = git.branchCreate();
createBranchCommand.setName(FEATURE_BRANCH_NAME);
createBranchCommand.call();
git.checkout().setName(FEATURE_BRANCH_NAME).call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 1\n");
git.add().addFilepattern(readme.getName()).call();
CommitCommand commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
FileUtils.writeStringToFile(readme, "FEATURE_1 branch commit 2\n");
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("feature 1 commit 2");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
git.checkout().setName("master").call();
FileUtils.writeStringToFile(readme, "Merge conflict branch commit 2\n");
git.add().addFilepattern(readme.getName()).call();
commitCommand = git.commit();
commitCommand.setMessage("merge conflict message 1");
commitCommand.setAuthor(AUTHER_NAME, AUTHER_EMAIL);
commitCommand.call();
readmeFileContents_fromDevBranch = FileUtils.readFileToString(new File(README_FILE_PATH));
}
private FreeStyleProject configurePretestedIntegrationPlugin() throws IOException, ANTLRException, InterruptedException {
FreeStyleProject project = jenkinsRule.createFreeStyleProject();
GitBridge gitBridge = new GitBridge(new SquashCommitStrategy(), "master");
project.getBuildWrappersList().add(new PretestedIntegrationBuildWrapper(gitBridge));
project.getPublishersList().add(new PretestedIntegrationPostCheckout());
List<UserRemoteConfig> repoList = new ArrayList<UserRemoteConfig>();
repoList.add(new UserRemoteConfig("file://" + GIT_DIR.getAbsolutePath(), null, null, null));
List<GitSCMExtension> gitSCMExtensions = new ArrayList<GitSCMExtension>();
gitSCMExtensions.add(new PruneStaleBranch());
gitSCMExtensions.add(new CleanCheckout());
GitSCM gitSCM = new GitSCM(repoList,
|
/*
* This class controls the shooting arm on the roboto
*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Solenoid;
public class Catapult {
Solenoid solenoid1;
Solenoid solenoid2;
DigitalInput armDownLimit;
public void Catapult(int sol1, int sol2, int limitSwitchPort){
solenoid1 = new Solenoid(sol1);
solenoid2 = new Solenoid(sol2);
armDownLimit = new DigitalInput(limitSwitchPort);
}
public boolean isDown(){
boolean isDown = false;
return isDown;
}
public boolean isLoaded(){
boolean loadValue = false;
return loadValue;
}
public void shootHigh(){
}
public void shootLow(){
}
}
|
package com.google.android.gms.dependencies;
import com.google.android.gms.StrictVersionMatcherPlugin;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.DependencyResolutionListener;
import org.gradle.api.artifacts.ResolvableDependencies;
import org.gradle.api.artifacts.result.DependencyResult;
import org.gradle.api.artifacts.result.ResolutionResult;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.HashMap;
/**
* This listener attaches to the Gradle project dependency resolution process in order to alert when
* the strict version declarations ("[16.0.0]" dependency declarations in POM files) in Google Play
* services libraries aren't being maintained.
* <p>
* Specifically, when an exact version is specified in Google Play services library POM files it
* means the libraries were ProGuard/R8'ed together to optimize symbols across the library group
* (AARs). Those changes aren't represented in the SemVer version declarations and unknown behavior
* is exhibited when the strict version number declarations are ignored. The strict number
* declaration can be skipped by Gradle's default behavior when other libraries request higher
* versions of libraries as part of the dependency resolution process so this plugin breaks the
* build to warn of the situation and provides paths to the problematic dependency paths.
* <p>
* This listener is used in both the google-services and strict-version-matcher-plugin Gradle
* plugins.
*/
public class DependencyInspector implements DependencyResolutionListener {
private static Logger logger = Logging.getLogger(StrictVersionMatcherPlugin.class);
private final DependencyAnalyzer dependencyAnalyzer;
private final String projectName;
/**
* Creates a Listener for inspection and analysis.
*
* @param dependencyAnalyzer where to register newly discovered dependencies and then extract them
* for analysis.
* @param projectName Gradle project name for clear error and info messaging.
*/
public DependencyInspector(@Nonnull DependencyAnalyzer dependencyAnalyzer,
@Nonnull String projectName) {
this.dependencyAnalyzer = dependencyAnalyzer;
this.projectName = projectName;
}
private static void printNode(int depth, Node n) {
StringBuilder prefix = new StringBuilder();
for (int z = 0; z < depth; z++) {
prefix.append("
}
prefix.append(" ");
Dependency dep = n.getDependency();
if ("gradle.project".equals(n.getDependency().getFromArtifactVersion().getGroupId())) {
String fromRef = dep.getFromArtifactVersion().getGradleRef().replace(
"gradle.project", "");
String toRef = dep.getToArtifact().getGradleRef().replace(
"com.google.android.gms", "c.g.a.g").replace(
"com.google.firebase", "c.g.f");
logger.warn(prefix.toString() + fromRef + " task/module dep -> " + toRef + "@" +
dep.getToArtifactVersionString());
} else {
String fromRef = dep.getFromArtifactVersion().getGradleRef().replace(
"com.google.android.gms", "c.g.a.g").replace(
"com.google.firebase", "c.g.f");
String toRef = dep.getToArtifact().getGradleRef().replace(
"com.google.android.gms", "c.g.a.g").replace(
"com.google.firebase", "c.g.f");
logger.warn(prefix.toString() + fromRef + " library depends -> " + toRef + "@" +
dep.getToArtifactVersionString());
}
if (n.getChild() != null) {
printNode(depth + 1, n.getChild());
}
}
private void registerDependencies(ResolvableDependencies resolvableDependencies,
String projectName, String taskName) {
ResolutionResult resolutionResult = resolvableDependencies.getResolutionResult();
// Record all of the dependencies into the tracker.
for (DependencyResult depResult : resolutionResult.getAllDependencies()) {
ArtifactVersion fromDep;
// Notes regarding getAllDependencies()
// * it contains all dep links within each project.
// * it contains links that may not be needed after the final
// versions are determined.
// * depResult.getFrom() == null represents a direct dep from the
// project being evaluated.
if (depResult.getFrom() == null ||
"".equals(depResult.getFrom().getId().getDisplayName())) {
// Register the dep from the project directly.
fromDep = ArtifactVersion.Companion.fromGradleRef(
"gradle.project:" + projectName + "-" + taskName + ":0.0.0");
} else {
String depFromString = ("" + depResult.getFrom().getId().getDisplayName());
if (depFromString.startsWith("project ")) {
// TODO(paulrashidi): Figure out more about this format.
// In a project with other project dependencies the dep
// string will be "project :module1"
String depName = depFromString.split(":")[1];
// Register the dep from another module in the project.
fromDep = ArtifactVersion.Companion.fromGradleRef(
"gradle.project:" + projectName + "-" + taskName + "-" +
depName + ":0.0.0");
} else {
try {
fromDep = ArtifactVersion.Companion.fromGradleRef(depFromString);
} catch (IllegalArgumentException iae) {
logger.error("Skipping misunderstood FROM dep string: " + depFromString);
continue;
}
}
}
if (depResult.getRequested() == null) {
// TODO(paulrashidi): What does this represent?
continue;
}
ArtifactVersion toDep;
String toDepString = "" + depResult.getRequested();
try {
toDep = ArtifactVersion.Companion.fromGradleRef(toDepString);
} catch (IllegalArgumentException iae) {
logger.error("Skipping misunderstood TO dep string: " + toDepString);
continue;
}
dependencyAnalyzer.registerDependency(
Dependency.Companion.fromArtifactVersions(fromDep, toDep));
}
}
@Override
public void beforeResolve(ResolvableDependencies resolvableDependencies) {
// This information isn't currently useful to the plugin.
// After doing testing, the only dependencies info available in
// resolvableDependencies is resolvableDependencies.dependencies.
// Those are the declared dependencies for task within the module.
// Also, not sure if Android test tasks have already had the
// dependencies de-duped by this time.
}
@Override
public void afterResolve(ResolvableDependencies resolvableDependencies) {
String taskName = resolvableDependencies.getName();
// Use of Product flavors can change task names so we look for compile tasks
// in a case in-sensitive way.
if (!taskName.contains("ompile")) {
// Quickly no-op to speed up Gradle build analysis.
return;
}
// Phase 1: register all the dependency information from the project globally.
logger.info("Registered task dependencies: " + projectName + ":" + taskName);
if (resolvableDependencies.getResolutionResult() != null &&
resolvableDependencies.getResolutionResult().getAllDependencies() != null) {
registerDependencies(resolvableDependencies, projectName, taskName);
}
// Phase 2: take the resolved versions of Artifacts, go get the dependencies that
// apply to those specific versions, and then ensure all are being honored.
logger.info("Starting dependency analysis");
ResolutionResult resolutionResult = resolvableDependencies.getResolutionResult();
// Create an Artifact to ArtifactVersion mapping for resolved components.
HashMap<Artifact, ArtifactVersion> resolvedVersions = new HashMap<>();
for (ResolvedComponentResult resolvedComponentResult :
resolutionResult.getAllComponents()) {
ArtifactVersion version = ArtifactVersion.Companion.fromGradleRefOrNull(
resolvedComponentResult.getId().toString());
if (version != null) {
resolvedVersions.put(version.getArtifact(), version);
}
}
// Quick no-op when no versions.
if (resolvedVersions.size() < 1) {
return;
}
// Retrieve dependencies that apply to the resolved dep set.
Collection<Dependency> activeDeps = dependencyAnalyzer.getActiveDependencies(
resolvedVersions.values());
// Validate each of the dependencies that should apply.
for (Dependency dep : activeDeps) {
ArtifactVersion resolvedVersion = resolvedVersions.get(dep.getToArtifact());
// Check whether dependency is still valid.
if (!dep.isVersionCompatible(resolvedVersion.getVersion())) {
logger.warn("Dependency resolved to an incompatible version: " + dep);
logger.info("Dependency Resolution Help: Displaying all currently known " +
"paths to any version of the dependency: " + dep.getToArtifact());
// This means a resolved version failed a dependency rule.
GradleException exception = new GradleException("In '" + projectName +
"' one resolved Google Play " +
"services library dependency depends on another at an exact version " +
"(e.g. \"[1.4.3]\"), but isn't being resolved to that version. " +
"Behavior exhibited by the library will be unknown. Execute gradle " +
"from the command line with ./gradlew --info :app:assembleDebug to " +
"see the dependency paths to the artifact. Dependency failing: " +
dep.getDisplayString() + " but " + dep.getToArtifact().getArtifactId() +
" version was " + resolvedVersion.getVersion() + ". This error came " +
"from the strict-dep-checker-plugin and can be disabled by disabling " +
"that plugin at your own risk. ");
// TODO: Warn, not fail, when the Major version boundaries are breached.
// TODO: Experiment with collecting all issues and reporting them at once.
Collection<Node> depsPaths = dependencyAnalyzer.getPaths(
resolvedVersion.getArtifact());
logger.info("NOTE: com.google.android.gms translated to c.g.a.g for brevity. " +
"Same for com.google.firebase -> c.g.f");
for (Node n : depsPaths) {
printNode(1, n);
}
throw exception;
}
}
}
}
|
package won.protocol.highlevel;
import org.apache.jena.query.Dataset;
import org.apache.jena.rdf.model.Model;
public class HighlevelProtocols {
/**
* Calculates all agreements present in the specified conversation dataset.
*/
public static Dataset getAgreements(Dataset conversationDataset) {
return HighlevelFunctionFactory.getAcknowledgedSelection()
.andThen(HighlevelFunctionFactory.getModifiedSelection())
.andThen(HighlevelFunctionFactory.getAgreementFunction())
.apply(conversationDataset);
}
/**
* Calculates all open proposals present in the specified conversation dataset.
* Returns the envelope graph of the proposal with the contents of the proposed
* message inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposals(Dataset conversationDataset) {
return HighlevelFunctionFactory.getAcknowledgedSelection()
.andThen(HighlevelFunctionFactory.getModifiedSelection())
.andThen(HighlevelFunctionFactory.getProposalFunction())
.apply(conversationDataset);
}
/** reveiw and rewrite the JavaDoc descriptions below **/
/**
* Calculates all open proposals to cancel present in the specified conversation dataset.
* returns envelope graph of the proposaltocancel with the contents of the target agreement to
* cancel inside.
* @param conversationDataset
* @return
*/
public static Dataset getProposalsToCancel(Dataset conversationDataset) {
return HighlevelFunctionFactory.getAcknowledgedSelection()
.andThen(HighlevelFunctionFactory.getModifiedSelection())
.andThen(HighlevelFunctionFactory.getProposalToCancelFunction())
.apply(conversationDataset);
}
/**
* Returns ?openprop agr:proposes ?openclause .
* ?openprop == unaccepted propsal
* ?openclause == proposed clause that is unaccepted
* @param conversationDataset
* @return
*/
public static Model getPendingProposes(Dataset conversationDataset) {
Model pendingproposes = HighlevelFunctionFactory.getPendingProposesFunction().apply(conversationDataset);
return pendingproposes;
}
/**
* Returns ?openprop agr:proposesToCancel ?acc .
* ?openprop == unaccepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getPendingProposesToCancel(Dataset conversationDataset) {
Model pendingproposestocancel = HighlevelFunctionFactory.getPendingProposesToCancelFunction().apply(conversationDataset);
return pendingproposestocancel;
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in an agreement
* ?clause == accepted clause in an agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposes(Dataset conversationDataset) {
Model acceptedproposes = HighlevelFunctionFactory.getAcceptedProposesFunction().apply(conversationDataset);
return acceptedproposes;
}
/**
* Returns ?acc agr:accepts ?prop .
* ?prop == accepted proposal in an agreement
* ?acc == agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposes(Dataset conversationDataset) {
Model acceptsproposes = HighlevelFunctionFactory.getAcceptsProposesFunction().apply(conversationDataset);
return acceptsproposes;
}
/**
* Returns ?cancelProp2 agr:proposesToCancel ?acc .
* ?cancelProp2 == accepted proposal to cancel
* ?acc == agreement proposed for cancellation
* @param conversationDataset
* @return
*/
public static Model getAcceptedProposesToCancel(Dataset conversationDataset) {
Model acceptedproposestocancel = HighlevelFunctionFactory.getAcceptedProposesToCancelFunction().apply(conversationDataset);
return acceptedproposestocancel;
}
/**
* Returns ?cancelAcc2 agr:accepts ?cancelProp2 .
* ?cancelProp2 . == accepted proposal to cancel
* ?cancelAcc2 == cancallation agreement
* @param conversationDataset
* @return
*/
public static Model getAcceptsProposesToCancel(Dataset conversationDataset) {
Model acceptsproposestocancel = HighlevelFunctionFactory.getAcceptsProposesToCancelFunction().apply(conversationDataset);
return acceptsproposestocancel;
}
/**
* Returns ?prop agr:proposes ?clause .
* ?prop == accepted proposal in agreement that was cancelled
* ?clause == accepted clause in an agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getProposesInCancelledAgreement(Dataset conversationDataset) {
Model proposesincancelledagreement = HighlevelFunctionFactory.getProposesInCancelledAgreementFunction().apply(conversationDataset);
return proposesincancelledagreement;
}
/**
* Returns ?acc agr:accepts ?prop .
* ?acc == agreement that was cancelled
* ?prop == accepted proposal in agreement that was cancelled
* @param conversationDataset
* @return
*/
public static Model getAcceptsInCancelledAgreement(Dataset conversationDataset) {
Model acceptscancelledagreement = HighlevelFunctionFactory.getAcceptsInCancelledAgreementFunction().apply(conversationDataset);
return acceptscancelledagreement;
}
/**
* Returns ?retractingMsg mod:retracts ?retractedMsg .
* ?retractingMsg == message containing mod:retracts
* ?retractedMsg == message that was retracted
* @param conversationDataset
* @return
*/
public static Model getAcceptedRetracts(Dataset conversationDataset) {
Model acceptedretracts = HighlevelFunctionFactory.getAcceptedRetractsFunction().apply(conversationDataset);
return acceptedretracts;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.