idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
10,000
public boolean invert ( ) { double determinant = determinant ( ) ; if ( Math . abs ( determinant ) <= Double . MIN_VALUE ) { return false ; } double t00 = m00 ; double t01 = m01 ; double t02 = m02 ; double t10 = m10 ; double t11 = m11 ; double t12 = m12 ; m00 = t11 / determinant ; m10 = - t10 / determinant ; m01 = - t01 / determinant ; m11 = t00 / determinant ; m02 = ( t01 * t12 - t11 * t02 ) / determinant ; m12 = ( t10 * t02 - t00 * t12 ) / determinant ; return true ; }
Invert this matrix . Implementation stolen from OpenJDK .
10,001
public void setAdditionalField ( final String key , final Object value ) { this . additionalFields . put ( key , value ) ; }
Add additional field
10,002
public static Object getGenInstance ( Class < ? > cls , Object ... args ) throws ParserException { Class < ? > parserClass = getGenClass ( cls ) ; try { if ( args . length == 0 ) { return parserClass . newInstance ( ) ; } else { for ( Constructor constructor : parserClass . getConstructors ( ) ) { Class [ ] parameterTypes = constructor . getParameterTypes ( ) ; if ( parameterTypes . length == args . length ) { boolean match = true ; int index = 0 ; for ( Class c : parameterTypes ) { if ( ! c . isAssignableFrom ( args [ index ++ ] . getClass ( ) ) ) { match = false ; break ; } } if ( match ) { return constructor . newInstance ( args ) ; } } } throw new IllegalArgumentException ( "no required constructor for " + cls ) ; } } catch ( InstantiationException | IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException ex ) { throw new ParserException ( ex ) ; } }
Creates generated class instance either by using ClassLoader or by compiling it dynamically
10,003
public static Class < ? > getGenClass ( Class < ? > cls ) throws ParserException { GenClassname genClassname = cls . getAnnotation ( GenClassname . class ) ; if ( genClassname == null ) { throw new IllegalArgumentException ( "@GenClassname not set in " + cls ) ; } try { return loadGenClass ( cls ) ; } catch ( ClassNotFoundException ex ) { throw new ParserException ( cls + " classes implementation class not compiled.\n" + "Possible problem with annotation processor.\n" + "Try building the whole project and check that implementation class " + genClassname . value ( ) + " exist!" ) ; } }
Creates generated class either by using ClassLoader
10,004
public static Object createDynamicInstance ( Class < ? > cls ) throws IOException { GenClassCompiler pc = GenClassCompiler . compile ( El . getTypeElement ( cls . getCanonicalName ( ) ) , null ) ; return pc . loadDynamic ( ) ; }
Creates instance of implementation class and loads it dynamic . This method is used in testing .
10,005
public static Class < ? > loadGenClass ( Class < ? > cls ) throws ClassNotFoundException { Class < ? > parserClass = map . get ( cls ) ; if ( parserClass == null ) { GenClassname genClassname = cls . getAnnotation ( GenClassname . class ) ; if ( genClassname == null ) { throw new IllegalArgumentException ( "@GenClassname not set in " + cls ) ; } parserClass = Class . forName ( genClassname . value ( ) ) ; map . put ( cls , parserClass ) ; } return parserClass ; }
Creates generated class by using ClassLoader . Return null if unable to load class
10,006
private String getObtainRequestPath ( String requestID , Boolean byResourceID , Boolean byDocID , Boolean idsOnly , String resumptionToken ) { String path = obtainPath ; if ( resumptionToken != null ) { path += "?" + resumptionTokenParam + "=" + resumptionToken ; return path ; } if ( requestID != null ) { path += "?" + requestIDParam + "=" + requestID ; } else { return null ; } if ( byResourceID ) { path += "&" + byResourceIDParam + "=" + booleanTrueString ; } else { path += "&" + byResourceIDParam + "=" + booleanFalseString ; } if ( byDocID ) { path += "&" + byDocIDParam + "=" + booleanTrueString ; } else { path += "&" + byDocIDParam + "=" + booleanFalseString ; } if ( idsOnly ) { path += "&" + idsOnlyParam + "=" + booleanTrueString ; } else { path += "&" + idsOnlyParam + "=" + booleanFalseString ; } return path ; }
Obtain the path used for an obtain request
10,007
private String getHarvestRequestPath ( String requestID , Boolean byResourceID , Boolean byDocID ) { String path = harvestPath ; if ( requestID != null ) { path += "?" + requestIDParam + "=" + requestID ; } else { return null ; } if ( byResourceID ) { path += "&" + byResourceIDParam + "=" + booleanTrueString ; } else { path += "&" + byResourceIDParam + "=" + booleanFalseString ; } if ( byDocID ) { path += "&" + byDocIDParam + "=" + booleanTrueString ; } else { path += "&" + byDocIDParam + "=" + booleanFalseString ; } return path ; }
Obtain the path used for a harvest request
10,008
private LRResult getObtainJSONData ( String requestID , Boolean byResourceID , Boolean byDocID , Boolean idsOnly , String resumptionToken ) throws LRException { String path = getObtainRequestPath ( requestID , byResourceID , byDocID , idsOnly , resumptionToken ) ; JSONObject json = getJSONFromPath ( path ) ; return new LRResult ( json ) ; }
Get a result from an obtain request If the resumption token is not null it will override the other parameters for ths request
10,009
public LRResult getHarvestJSONData ( String requestID , Boolean byResourceID , Boolean byDocID ) throws LRException { String path = getHarvestRequestPath ( requestID , byResourceID , byDocID ) ; JSONObject json = getJSONFromPath ( path ) ; return new LRResult ( json ) ; }
Get a result from a harvest request
10,010
private String getExtractRequestPath ( String dataServiceName , String viewName , Date from , Date until , Boolean idsOnly , String mainValue , Boolean partial , String mainName ) { String path = extractPath ; if ( viewName != null ) { path += "/" + viewName ; } else { return null ; } if ( dataServiceName != null ) { path += "/" + dataServiceName ; } else { return null ; } if ( mainValue != null && mainName != null ) { path += "?" + mainName ; if ( partial ) { path += startsWithParam ; } path += "=" + mainValue ; } else { return null ; } if ( from != null ) { path += "&" + fromParam + "=" + ISO8601 . format ( from ) ; } if ( until != null ) { path += "&" + untilParam + "=" + ISO8601 . format ( until ) ; } if ( idsOnly ) { path += "&" + idsOnlyParam + "=" + booleanTrueString ; } return path ; }
Get an extract request path
10,011
private JSONObject getJSONFromPath ( String path ) throws LRException { JSONObject json = null ; String jsonTxt = null ; try { jsonTxt = LRClient . executeJsonGet ( importProtocol + "://" + nodeHost + path ) ; } catch ( Exception e ) { throw new LRException ( LRException . IMPORT_FAILED ) ; } try { json = new JSONObject ( jsonTxt ) ; } catch ( JSONException e ) { throw new LRException ( LRException . JSON_IMPORT_FAILED ) ; } return json ; }
Get the data from the specified path as a JSONObject
10,012
private static int fontStyleToInt ( FontStyle style ) { switch ( style ) { case PLAIN : return java . awt . Font . PLAIN ; case BOLD : return java . awt . Font . BOLD ; case ITALIC : return java . awt . Font . ITALIC ; default : return java . awt . Font . PLAIN ; } }
Return a java . awt . Font style constant from FontStyle .
10,013
private static FontStyle intToFontStyle ( int style ) { switch ( style ) { case java . awt . Font . PLAIN : return FontStyle . PLAIN ; case java . awt . Font . BOLD : return FontStyle . BOLD ; case java . awt . Font . ITALIC : return FontStyle . ITALIC ; case java . awt . Font . BOLD + java . awt . Font . ITALIC : return FontStyle . BOLD_ITALIC ; default : return FontStyle . PLAIN ; } }
Return FontStyle enum value from java . awt . Font style constant .
10,014
private static FontStyle stringToFontStyle ( String style ) { if ( style . compareToIgnoreCase ( "plain" ) == 0 ) { return FontStyle . PLAIN ; } else if ( style . compareToIgnoreCase ( "bold" ) == 0 ) { return FontStyle . BOLD ; } else if ( style . compareToIgnoreCase ( "italic" ) == 0 ) { return FontStyle . ITALIC ; } else { throw new IllegalArgumentException ( ) ; } }
Return FontStyle enum value from a font style name .
10,015
public void onReload ( final Container _container ) { final Set < Class < ? > > classesToRemove = new HashSet < > ( ) ; final Set < Class < ? > > classesToAdd = new HashSet < > ( ) ; for ( final Class < ? > c : getClasses ( ) ) { if ( ! this . cachedClasses . contains ( c ) ) { classesToAdd . add ( c ) ; } } for ( final Class < ? > c : this . cachedClasses ) { if ( ! getClasses ( ) . contains ( c ) ) { classesToRemove . add ( c ) ; } } getClasses ( ) . clear ( ) ; init ( ) ; getClasses ( ) . addAll ( classesToAdd ) ; getClasses ( ) . removeAll ( classesToRemove ) ; }
Perform a new search for resource classes and provider classes .
10,016
private void addInstSelect ( final Select _select , final AbstractDataElement < ? > _element , final Object _attrOrClass , final Type _currentType ) throws CacheReloadException { if ( StringUtils . isNotEmpty ( _element . getPath ( ) ) && ! this . instSelects . containsKey ( _element . getPath ( ) ) ) { final Select instSelect = Select . get ( ) ; for ( final AbstractElement < ? > selectTmp : _select . getElements ( ) ) { if ( ! selectTmp . equals ( _element ) ) { if ( selectTmp instanceof LinktoElement ) { instSelect . addElement ( new LinktoElement ( ) . setAttribute ( ( ( LinktoElement ) selectTmp ) . getAttribute ( ) ) ) ; } else if ( selectTmp instanceof LinkfromElement ) { instSelect . addElement ( new LinkfromElement ( ) . setAttribute ( ( ( LinkfromElement ) selectTmp ) . getAttribute ( ) ) . setStartType ( ( ( LinkfromElement ) selectTmp ) . getStartType ( ) ) ) ; } else if ( selectTmp instanceof ClassElement ) { instSelect . addElement ( new ClassElement ( ) . setClassification ( ( ( ClassElement ) selectTmp ) . getClassification ( ) ) . setType ( ( ( ClassElement ) selectTmp ) . getType ( ) ) ) ; } else if ( selectTmp instanceof AttributeSetElement ) { instSelect . addElement ( new AttributeSetElement ( ) . setAttributeSet ( ( ( AttributeSetElement ) selectTmp ) . getAttributeSet ( ) ) . setType ( ( ( ClassElement ) selectTmp ) . getType ( ) ) ) ; } } } if ( _element instanceof LinkfromElement ) { instSelect . addElement ( new LinkfromElement ( ) . setAttribute ( ( Attribute ) _attrOrClass ) . setStartType ( _currentType ) ) ; instSelect . addElement ( new InstanceElement ( ( ( Attribute ) _attrOrClass ) . getParent ( ) ) ) ; } else if ( _element instanceof LinktoElement ) { instSelect . addElement ( new LinktoElement ( ) . setAttribute ( ( Attribute ) _attrOrClass ) ) ; instSelect . addElement ( new InstanceElement ( _currentType ) ) ; } else if ( _element instanceof ClassElement ) { instSelect . addElement ( new ClassElement ( ) . setClassification ( ( Classification ) _attrOrClass ) . setType ( _currentType ) ) ; instSelect . addElement ( new InstanceElement ( ( Type ) _attrOrClass ) ) ; } else if ( _element instanceof AttributeSetElement ) { instSelect . addElement ( new AttributeSetElement ( ) . setAttributeSet ( ( AttributeSet ) _attrOrClass ) . setType ( _currentType ) ) ; instSelect . addElement ( new InstanceElement ( ( Type ) _attrOrClass ) ) ; } this . instSelects . put ( _element . getPath ( ) , instSelect ) ; } }
Adds the inst select .
10,017
private Type evalMainType ( final Collection < Type > _baseTypes ) throws EFapsException { final Type ret ; if ( _baseTypes . size ( ) == 1 ) { ret = _baseTypes . iterator ( ) . next ( ) ; } else { final List < List < Type > > typeLists = new ArrayList < > ( ) ; for ( final Type type : _baseTypes ) { final List < Type > typesTmp = new ArrayList < > ( ) ; typeLists . add ( typesTmp ) ; Type tmpType = type ; while ( tmpType != null ) { typesTmp . add ( tmpType ) ; tmpType = tmpType . getParentType ( ) ; } } final Set < Type > common = new LinkedHashSet < > ( ) ; if ( ! typeLists . isEmpty ( ) ) { final Iterator < List < Type > > iterator = typeLists . iterator ( ) ; common . addAll ( iterator . next ( ) ) ; while ( iterator . hasNext ( ) ) { common . retainAll ( iterator . next ( ) ) ; } } if ( common . isEmpty ( ) ) { throw new EFapsException ( Selection . class , "noCommon" , _baseTypes ) ; } else { ret = common . iterator ( ) . next ( ) ; } } return ret ; }
Gets the main type .
10,018
public Collection < Select > getAllSelects ( ) { final List < Select > ret = new ArrayList < > ( this . selects ) ; ret . addAll ( this . instSelects . values ( ) ) ; return Collections . unmodifiableCollection ( ret ) ; }
Gets the all data selects .
10,019
protected void unassignFromUserObjectInDb ( final Type _unassignType , final JAASSystem _jaasSystem , final AbstractUserObject _object ) throws EFapsException { Connection con = null ; try { con = Context . getConnection ( ) ; Statement stmt = null ; final StringBuilder cmd = new StringBuilder ( ) ; try { cmd . append ( "delete from " ) . append ( _unassignType . getMainTable ( ) . getSqlTable ( ) ) . append ( " " ) . append ( "where USERJAASSYSTEM=" ) . append ( _jaasSystem . getId ( ) ) . append ( " " ) . append ( "and USERABSTRACTFROM=" ) . append ( getId ( ) ) . append ( " " ) . append ( "and USERABSTRACTTO=" ) . append ( _object . getId ( ) ) ; stmt = con . createStatement ( ) ; stmt . executeUpdate ( cmd . toString ( ) ) ; } catch ( final SQLException e ) { AbstractUserObject . LOG . error ( "could not execute '" + cmd . toString ( ) + "' to unassign user object '" + toString ( ) + "' from object '" + _object + "' for JAAS system '" + _jaasSystem + "' " , e ) ; throw new EFapsException ( getClass ( ) , "unassignFromUserObjectInDb.SQLException" , e , cmd . toString ( ) , getName ( ) ) ; } finally { try { if ( stmt != null ) { stmt . close ( ) ; } con . commit ( ) ; } catch ( final SQLException e ) { AbstractUserObject . LOG . error ( "Could not close a statement." , e ) ; } } } finally { try { if ( con != null && ! con . isClosed ( ) ) { con . close ( ) ; } } catch ( final SQLException e ) { throw new CacheReloadException ( "Cannot read a type for an attribute." , e ) ; } } }
Unassign this user object from the given user object for given JAAS system .
10,020
protected void setStatusInDB ( final boolean _status ) throws EFapsException { Connection con = null ; try { con = Context . getConnection ( ) ; PreparedStatement stmt = null ; final StringBuilder cmd = new StringBuilder ( ) ; try { cmd . append ( " update T_USERABSTRACT set STATUS=? where ID=" ) . append ( getId ( ) ) ; stmt = con . prepareStatement ( cmd . toString ( ) ) ; stmt . setBoolean ( 1 , _status ) ; final int rows = stmt . executeUpdate ( ) ; if ( rows == 0 ) { AbstractUserObject . LOG . error ( "could not execute '" + cmd . toString ( ) + "' to update status information for person '" + toString ( ) + "'" ) ; throw new EFapsException ( getClass ( ) , "setStatusInDB.NotUpdated" , cmd . toString ( ) , getName ( ) ) ; } } catch ( final SQLException e ) { AbstractUserObject . LOG . error ( "could not execute '" + cmd . toString ( ) + "' to update status information for person '" + toString ( ) + "'" , e ) ; throw new EFapsException ( getClass ( ) , "setStatusInDB.SQLException" , e , cmd . toString ( ) , getName ( ) ) ; } finally { try { if ( stmt != null ) { stmt . close ( ) ; } con . commit ( ) ; } catch ( final SQLException e ) { throw new EFapsException ( getClass ( ) , "setStatusInDB.SQLException" , e , cmd . toString ( ) , getName ( ) ) ; } } } finally { try { if ( con != null && ! con . isClosed ( ) ) { con . close ( ) ; } } catch ( final SQLException e ) { throw new CacheReloadException ( "Cannot read a type for an attribute." , e ) ; } } }
Method to set the status of a UserObject in the eFaps Database .
10,021
private void readFromDB4Access ( ) throws CacheReloadException { Statement stmt = null ; try { stmt = Context . getThreadContext ( ) . getConnectionResource ( ) . createStatement ( ) ; final ResultSet resultset = stmt . executeQuery ( "select " + "T_UIACCESS.USERABSTRACT " + "from T_UIACCESS " + "where T_UIACCESS.UIABSTRACT=" + getId ( ) ) ; while ( resultset . next ( ) ) { final long userId = resultset . getLong ( 1 ) ; final AbstractUserObject userObject = AbstractUserObject . getUserObject ( userId ) ; if ( userObject == null ) { throw new CacheReloadException ( "user " + userId + " does not exists!" ) ; } else { getAccess ( ) . add ( userId ) ; } } resultset . close ( ) ; } catch ( final SQLException e ) { throw new CacheReloadException ( "could not read access for " + "'" + getName ( ) + "'" , e ) ; } catch ( final EFapsException e ) { throw new CacheReloadException ( "could not read access for " + "'" + getName ( ) + "'" , e ) ; } finally { if ( stmt != null ) { try { stmt . close ( ) ; } catch ( final SQLException e ) { throw new CacheReloadException ( "could not read access for " + "'" + getName ( ) + "'" , e ) ; } } } }
The instance method reads the access for this user interface object .
10,022
public String getPath ( ) { final StringBuilder path = new StringBuilder ( ) ; if ( getPrevious ( ) != null ) { path . append ( getPrevious ( ) . getPath ( ) ) ; } return path . toString ( ) ; }
Gets the path .
10,023
private Map < String , IEsjpSelect > getEsjpSelect ( final List < Instance > _instances ) throws Exception { final Map < String , IEsjpSelect > ret = new HashMap < > ( ) ; if ( ! _instances . isEmpty ( ) ) { for ( final Entry < String , AbstractSelect > entry : getAlias2Selects ( ) . entrySet ( ) ) { if ( entry . getValue ( ) instanceof ExecSelect ) { final Class < ? > clazz = Class . forName ( entry . getValue ( ) . getSelect ( ) , false , EFapsClassLoader . getInstance ( ) ) ; final IEsjpSelect esjp = ( IEsjpSelect ) clazz . newInstance ( ) ; final List < String > parameters = ( ( ExecSelect ) entry . getValue ( ) ) . getParameters ( ) ; if ( parameters . isEmpty ( ) ) { esjp . initialize ( _instances ) ; } else { esjp . initialize ( _instances , parameters . toArray ( new String [ parameters . size ( ) ] ) ) ; } ret . put ( entry . getKey ( ) , esjp ) ; } } } return ret ; }
Gets the esjp select .
10,024
private MultiPrintQuery getMultiPrint ( ) throws EFapsException { final MultiPrintQuery ret ; if ( getInstances ( ) . isEmpty ( ) ) { ret = new MultiPrintQuery ( QueryBldrUtil . getInstances ( this ) ) ; } else { final List < Instance > instances = new ArrayList < > ( ) ; for ( final String oid : getInstances ( ) ) { instances . add ( Instance . get ( oid ) ) ; } ret = new MultiPrintQuery ( instances ) ; } return ret ; }
Gets the multi print .
10,025
private void addUoM ( final UoM _uom ) { this . uoMs . add ( _uom ) ; if ( _uom . getId ( ) == this . baseUoMId ) { this . baseUoM = _uom ; } }
Method to add an UoM to this dimension .
10,026
public static UoM getUoM ( final Long _uoMId ) { final Cache < Long , UoM > cache = InfinispanCache . get ( ) . < Long , UoM > getCache ( Dimension . IDCACHE4UOM ) ; if ( ! cache . containsKey ( _uoMId ) ) { try { Dimension . getUoMFromDB ( Dimension . SQL_SELECT_UOM4ID , _uoMId ) ; } catch ( final CacheReloadException e ) { Dimension . LOG . error ( "read UoM from DB failed for id: '{}'" , _uoMId ) ; } } return cache . get ( _uoMId ) ; }
Static Method to get an UoM for an id .
10,027
public String getResumptionToken ( ) { String resumptionToken = null ; try { if ( data != null && data . has ( resumptionTokenParam ) ) { resumptionToken = data . getString ( resumptionTokenParam ) ; } } catch ( JSONException e ) { } return resumptionToken ; }
Returns the resumption token if it exists
10,028
public List < JSONObject > getResourceData ( ) { List < JSONObject > resources = new ArrayList < JSONObject > ( ) ; try { if ( data != null && data . has ( documentsParam ) ) { List < JSONObject > results = getDocuments ( ) ; for ( JSONObject json : results ) { if ( json . has ( documentParam ) ) { JSONObject result = json . getJSONObject ( documentParam ) ; results . add ( result ) ; } } } else if ( data != null && data . has ( getRecordParam ) ) { List < JSONObject > results = getRecords ( ) ; for ( JSONObject json : results ) { if ( json . has ( resourceDataParam ) ) { JSONObject result = json . getJSONObject ( resourceDataParam ) ; results . add ( result ) ; } } } } catch ( JSONException e ) { } return resources ; }
Returns resource data from obtain or harvest request
10,029
public List < JSONObject > getDocuments ( ) { List < JSONObject > documents = new ArrayList < JSONObject > ( ) ; try { if ( data != null && data . has ( documentsParam ) ) { JSONArray jsonDocuments = data . getJSONArray ( documentsParam ) ; for ( int i = 0 ; i < jsonDocuments . length ( ) ; i ++ ) { JSONObject document = jsonDocuments . getJSONObject ( i ) ; documents . add ( document ) ; } } } catch ( JSONException e ) { } return documents ; }
Returns documents from obtain request
10,030
public List < JSONObject > getRecords ( ) { List < JSONObject > records = new ArrayList < JSONObject > ( ) ; try { if ( data != null && data . has ( getRecordParam ) ) { JSONObject jsonGetRecord = data . getJSONObject ( getRecordParam ) ; if ( jsonGetRecord . has ( recordParam ) ) { JSONArray jsonRecords = jsonGetRecord . getJSONArray ( recordParam ) ; for ( int i = 0 ; i < jsonRecords . length ( ) ; i ++ ) { JSONObject record = jsonRecords . getJSONObject ( i ) ; records . add ( record ) ; } } } } catch ( JSONException e ) { } return records ; }
Returns records from harvest request
10,031
public BigDecimal roundBigDecimal ( final BigDecimal number ) { int mscale = getMathScale ( ) ; if ( mscale >= 0 ) { return number . setScale ( mscale , getMathContext ( ) . getRoundingMode ( ) ) ; } else { return number ; } }
Ensure a big decimal is rounded by this arithmetic scale and rounding mode .
10,032
protected boolean isFloatingPointType ( Object left , Object right ) { return left instanceof Float || left instanceof Double || right instanceof Float || right instanceof Double ; }
Test if either left or right are either a Float or Double .
10,033
protected boolean isNumberable ( final Object o ) { return o instanceof Integer || o instanceof Long || o instanceof Byte || o instanceof Short || o instanceof Character ; }
Is Object a whole number .
10,034
protected Number narrowBigDecimal ( Object lhs , Object rhs , BigDecimal bigd ) { if ( isNumberable ( lhs ) || isNumberable ( rhs ) ) { try { long l = bigd . longValueExact ( ) ; if ( l <= Integer . MAX_VALUE && l >= Integer . MIN_VALUE ) { return Integer . valueOf ( ( int ) l ) ; } else { return Long . valueOf ( l ) ; } } catch ( ArithmeticException xa ) { } } return bigd ; }
Given a BigDecimal attempt to narrow it to an Integer or Long if it fits if one of the arguments is a numberable .
10,035
protected boolean narrowArguments ( Object [ ] args ) { boolean narrowed = false ; for ( int a = 0 ; a < args . length ; ++ a ) { Object arg = args [ a ] ; if ( arg instanceof Number ) { Object narg = narrow ( ( Number ) arg ) ; if ( narg != arg ) { narrowed = true ; } args [ a ] = narg ; } } return narrowed ; }
Replace all numbers in an arguments array with the smallest type that will fit .
10,036
public Object divide ( Object left , Object right ) { if ( left == null && right == null ) { return 0 ; } if ( isFloatingPointNumber ( left ) || isFloatingPointNumber ( right ) ) { double l = toDouble ( left ) ; double r = toDouble ( right ) ; if ( r == 0.0 ) { throw new ArithmeticException ( "/" ) ; } return new Double ( l / r ) ; } if ( left instanceof BigDecimal || right instanceof BigDecimal ) { BigDecimal l = toBigDecimal ( left ) ; BigDecimal r = toBigDecimal ( right ) ; if ( BigDecimal . ZERO . equals ( r ) ) { throw new ArithmeticException ( "/" ) ; } BigDecimal result = l . divide ( r , getMathContext ( ) ) ; return narrowBigDecimal ( left , right , result ) ; } BigInteger l = toBigInteger ( left ) ; BigInteger r = toBigInteger ( right ) ; if ( BigInteger . ZERO . equals ( r ) ) { throw new ArithmeticException ( "/" ) ; } BigInteger result = l . divide ( r ) ; return narrowBigInteger ( left , right , result ) ; }
Divide the left value by the right .
10,037
public Object multiply ( Object left , Object right ) { if ( left == null && right == null ) { return 0 ; } if ( isFloatingPointNumber ( left ) || isFloatingPointNumber ( right ) ) { double l = toDouble ( left ) ; double r = toDouble ( right ) ; return new Double ( l * r ) ; } if ( left instanceof BigDecimal || right instanceof BigDecimal ) { BigDecimal l = toBigDecimal ( left ) ; BigDecimal r = toBigDecimal ( right ) ; BigDecimal result = l . multiply ( r , getMathContext ( ) ) ; return narrowBigDecimal ( left , right , result ) ; } BigInteger l = toBigInteger ( left ) ; BigInteger r = toBigInteger ( right ) ; BigInteger result = l . multiply ( r ) ; return narrowBigInteger ( left , right , result ) ; }
Multiply the left value by the right .
10,038
public boolean matches ( Object left , Object right ) { if ( left == null && right == null ) { return true ; } if ( left == null || right == null ) { return false ; } final String arg = left . toString ( ) ; if ( right instanceof java . util . regex . Pattern ) { return ( ( java . util . regex . Pattern ) right ) . matcher ( arg ) . matches ( ) ; } else { return arg . matches ( right . toString ( ) ) ; } }
Test if left regexp matches right .
10,039
public Object bitwiseOr ( Object left , Object right ) { long l = toLong ( left ) ; long r = toLong ( right ) ; return Long . valueOf ( l | r ) ; }
Performs a bitwise or .
10,040
public Object bitwiseComplement ( Object val ) { long l = toLong ( val ) ; return Long . valueOf ( ~ l ) ; }
Performs a bitwise complement .
10,041
public boolean lessThan ( Object left , Object right ) { if ( ( left == right ) || ( left == null ) || ( right == null ) ) { return false ; } else { return compare ( left , right , "<" ) < 0 ; } }
Test if left < right .
10,042
public boolean greaterThan ( Object left , Object right ) { if ( ( left == right ) || left == null || right == null ) { return false ; } else { return compare ( left , right , ">" ) > 0 ; } }
Test if left > right .
10,043
public boolean lessThanOrEqual ( Object left , Object right ) { if ( left == right ) { return true ; } else if ( left == null || right == null ) { return false ; } else { return compare ( left , right , "<=" ) <= 0 ; } }
Test if left < = right .
10,044
public boolean greaterThanOrEqual ( Object left , Object right ) { if ( left == right ) { return true ; } else if ( left == null || right == null ) { return false ; } else { return compare ( left , right , ">=" ) >= 0 ; } }
Test if left > = right .
10,045
public int toInteger ( Object val ) { if ( val == null ) { return 0 ; } else if ( val instanceof Double ) { if ( ! Double . isNaN ( ( ( Double ) val ) . doubleValue ( ) ) ) { return 0 ; } else { return ( ( Double ) val ) . intValue ( ) ; } } else if ( val instanceof Number ) { return ( ( Number ) val ) . intValue ( ) ; } else if ( val instanceof String ) { if ( "" . equals ( val ) ) { return 0 ; } return Integer . parseInt ( ( String ) val ) ; } else if ( val instanceof Boolean ) { return ( ( Boolean ) val ) . booleanValue ( ) ? 1 : 0 ; } else if ( val instanceof Character ) { return ( ( Character ) val ) . charValue ( ) ; } throw new ArithmeticException ( "Integer coercion: " + val . getClass ( ) . getName ( ) + ":(" + val + ")" ) ; }
Coerce to a int .
10,046
public BigInteger toBigInteger ( Object val ) { if ( val == null ) { return BigInteger . ZERO ; } else if ( val instanceof BigInteger ) { return ( BigInteger ) val ; } else if ( val instanceof Double ) { if ( ! Double . isNaN ( ( ( Double ) val ) . doubleValue ( ) ) ) { return new BigInteger ( val . toString ( ) ) ; } else { return BigInteger . ZERO ; } } else if ( val instanceof Number ) { return new BigInteger ( val . toString ( ) ) ; } else if ( val instanceof String ) { String string = ( String ) val ; if ( "" . equals ( string . trim ( ) ) ) { return BigInteger . ZERO ; } else { return new BigInteger ( string ) ; } } else if ( val instanceof Character ) { int i = ( ( Character ) val ) . charValue ( ) ; return BigInteger . valueOf ( i ) ; } throw new ArithmeticException ( "BigInteger coercion: " + val . getClass ( ) . getName ( ) + ":(" + val + ")" ) ; }
Get a BigInteger from the object passed . Null and empty string maps to zero .
10,047
public BigDecimal toBigDecimal ( Object val ) { if ( val instanceof BigDecimal ) { return roundBigDecimal ( ( BigDecimal ) val ) ; } else if ( val == null ) { return BigDecimal . ZERO ; } else if ( val instanceof String ) { String string = ( ( String ) val ) . trim ( ) ; if ( "" . equals ( string ) ) { return BigDecimal . ZERO ; } return roundBigDecimal ( new BigDecimal ( string , getMathContext ( ) ) ) ; } else if ( val instanceof Double ) { if ( ! Double . isNaN ( ( ( Double ) val ) . doubleValue ( ) ) ) { return roundBigDecimal ( new BigDecimal ( val . toString ( ) , getMathContext ( ) ) ) ; } else { return BigDecimal . ZERO ; } } else if ( val instanceof Number ) { return roundBigDecimal ( new BigDecimal ( val . toString ( ) , getMathContext ( ) ) ) ; } else if ( val instanceof Character ) { int i = ( ( Character ) val ) . charValue ( ) ; return new BigDecimal ( i ) ; } throw new ArithmeticException ( "BigDecimal coercion: " + val . getClass ( ) . getName ( ) + ":(" + val + ")" ) ; }
Get a BigDecimal from the object passed . Null and empty string maps to zero .
10,048
public double toDouble ( Object val ) { if ( val == null ) { return 0 ; } else if ( val instanceof Double ) { return ( ( Double ) val ) . doubleValue ( ) ; } else if ( val instanceof Number ) { return Double . parseDouble ( String . valueOf ( val ) ) ; } else if ( val instanceof Boolean ) { return ( ( Boolean ) val ) . booleanValue ( ) ? 1. : 0. ; } else if ( val instanceof String ) { String string = ( ( String ) val ) . trim ( ) ; if ( "" . equals ( string ) ) { return Double . NaN ; } else { return Double . parseDouble ( string ) ; } } else if ( val instanceof Character ) { int i = ( ( Character ) val ) . charValue ( ) ; return i ; } throw new ArithmeticException ( "Double coercion: " + val . getClass ( ) . getName ( ) + ":(" + val + ")" ) ; }
Coerce to a double .
10,049
public Collection < ? > toCollection ( Object val ) { if ( val == null ) { return Collections . emptyList ( ) ; } else if ( val instanceof Collection < ? > ) { return ( Collection < ? > ) val ; } else if ( val . getClass ( ) . isArray ( ) ) { return newArrayList ( ( Object [ ] ) val ) ; } else if ( val instanceof Map < ? , ? > ) { return ( ( Map < ? , ? > ) val ) . entrySet ( ) ; } else { return newArrayList ( val ) ; } }
Coerce to a collection
10,050
protected boolean narrowAccept ( Class < ? > narrow , Class < ? > source ) { return narrow == null || narrow . equals ( source ) ; }
Whether we consider the narrow class as a potential candidate for narrowing the source .
10,051
protected Number narrowNumber ( Number original , Class < ? > narrow ) { if ( original == null ) { return original ; } Number result = original ; if ( original instanceof BigDecimal ) { BigDecimal bigd = ( BigDecimal ) original ; if ( bigd . compareTo ( BIGD_DOUBLE_MAX_VALUE ) > 0 ) { return original ; } else { try { long l = bigd . longValueExact ( ) ; if ( narrowAccept ( narrow , Integer . class ) && l <= Integer . MAX_VALUE && l >= Integer . MIN_VALUE ) { return Integer . valueOf ( ( int ) l ) ; } else if ( narrowAccept ( narrow , Long . class ) ) { return Long . valueOf ( l ) ; } } catch ( ArithmeticException xa ) { } } } if ( original instanceof Double || original instanceof Float || original instanceof BigDecimal ) { double value = original . doubleValue ( ) ; if ( narrowAccept ( narrow , Float . class ) && value <= Float . MAX_VALUE && value >= Float . MIN_VALUE ) { result = Float . valueOf ( result . floatValue ( ) ) ; } } else { if ( original instanceof BigInteger ) { BigInteger bigi = ( BigInteger ) original ; if ( bigi . compareTo ( BIGI_LONG_MAX_VALUE ) > 0 || bigi . compareTo ( BIGI_LONG_MIN_VALUE ) < 0 ) { return original ; } } long value = original . longValue ( ) ; if ( narrowAccept ( narrow , Byte . class ) && value <= Byte . MAX_VALUE && value >= Byte . MIN_VALUE ) { result = Byte . valueOf ( ( byte ) value ) ; } else if ( narrowAccept ( narrow , Short . class ) && value <= Short . MAX_VALUE && value >= Short . MIN_VALUE ) { result = Short . valueOf ( ( short ) value ) ; } else if ( narrowAccept ( narrow , Integer . class ) && value <= Integer . MAX_VALUE && value >= Integer . MIN_VALUE ) { result = Integer . valueOf ( ( int ) value ) ; } } return result ; }
Given a Number return back the value attempting to narrow it to a target class .
10,052
public static AttributeSet get ( final String _typeName , final String _name ) throws CacheReloadException { return ( AttributeSet ) Type . get ( AttributeSet . evaluateName ( _typeName , _name ) ) ; }
Method to get the type from the cache .
10,053
public static AttributeSet find ( final String _typeName , final String _name ) throws CacheReloadException { AttributeSet ret = ( AttributeSet ) Type . get ( AttributeSet . evaluateName ( _typeName , _name ) ) ; if ( ret == null ) { if ( Type . get ( _typeName ) . getParentType ( ) != null ) { ret = AttributeSet . find ( Type . get ( _typeName ) . getParentType ( ) . getName ( ) , _name ) ; } } return ret ; }
Method to get the type from the cache . Searches if not found in the type hierarchy .
10,054
private Set < Classification > getClassification ( final List < Long > _classIds ) throws CacheReloadException { final Set < Classification > noadd = new HashSet < > ( ) ; final Set < Classification > add = new HashSet < > ( ) ; if ( _classIds != null ) { for ( final Long id : _classIds ) { Classification clazz = ( Classification ) Type . get ( id ) ; if ( ! noadd . contains ( clazz ) ) { add . add ( clazz ) ; while ( clazz . getParentClassification ( ) != null ) { clazz = clazz . getParentClassification ( ) ; if ( add . contains ( clazz ) ) { add . remove ( clazz ) ; } noadd . add ( clazz ) ; } } } } return add ; }
Method to get only the leaf of the classification tree .
10,055
protected boolean executeOneCompleteStmt ( final String _complStmt , final List < Instance > _instances ) throws EFapsException { final boolean ret = false ; ConnectionResource con = null ; try { con = Context . getThreadContext ( ) . getConnectionResource ( ) ; final Statement stmt = con . createStatement ( ) ; final ResultSet rs = stmt . executeQuery ( _complStmt . toString ( ) ) ; final Map < Long , List < Long > > link2clazz = new HashMap < > ( ) ; while ( rs . next ( ) ) { final long linkId = rs . getLong ( 2 ) ; final long classificationID = rs . getLong ( 3 ) ; final List < Long > templ ; if ( link2clazz . containsKey ( linkId ) ) { templ = link2clazz . get ( linkId ) ; } else { templ = new ArrayList < > ( ) ; link2clazz . put ( linkId , templ ) ; } templ . add ( classificationID ) ; } for ( final Instance instance : _instances ) { this . instances2classId . put ( instance , link2clazz . get ( instance . getId ( ) ) ) ; } rs . close ( ) ; stmt . close ( ) ; } catch ( final SQLException e ) { throw new EFapsException ( ClassificationValueSelect . class , "executeOneCompleteStmt" , e ) ; } return ret ; }
Method to execute one statement against the eFaps - DataBase .
10,056
public static void writeSourceToFile ( Class < ? > koanClass , String newSource ) { Path currentRelativePath = Paths . get ( "" ) ; String workingDirectory = currentRelativePath . toAbsolutePath ( ) . toString ( ) ; String packagePath = koanClass . getPackage ( ) . getName ( ) ; packagePath = packagePath . replace ( PACKAGE_SEPARATOR , PATH_SEPARATOR ) ; String className = koanClass . getSimpleName ( ) ; File file = new File ( workingDirectory + KOAN_JAVA_PATH + packagePath + PATH_SEPARATOR + className + JAVA_EXTENSION ) ; try { FileWriter fw = new FileWriter ( file . getAbsoluteFile ( ) ) ; BufferedWriter bw = new BufferedWriter ( fw ) ; bw . write ( newSource ) ; bw . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Write source to file .
10,057
protected Person createPerson ( final LoginContext _login ) throws EFapsException { Person person = null ; for ( final JAASSystem system : JAASSystem . getAllJAASSystems ( ) ) { final Set < ? > users = _login . getSubject ( ) . getPrincipals ( system . getPersonJAASPrincipleClass ( ) ) ; for ( final Object persObj : users ) { try { final String persKey = ( String ) system . getPersonMethodKey ( ) . invoke ( persObj ) ; final String persName = ( String ) system . getPersonMethodName ( ) . invoke ( persObj ) ; if ( person == null ) { person = Person . createPerson ( system , persKey , persName , null ) ; } else { person . assignToJAASSystem ( system , persKey ) ; } } catch ( final IllegalAccessException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "IllegalAccessException" , e ) ; } catch ( final IllegalArgumentException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "IllegalArgumentException" , e ) ; } catch ( final InvocationTargetException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "InvocationTargetException" , e ) ; } } } return person ; }
The person represented in the JAAS login context is created and associated to eFaps . If the person is defined in more than one JAAS system the person is also associated to the other JAAS systems .
10,058
protected void updatePerson ( final LoginContext _login , final Person _person ) throws EFapsException { for ( final JAASSystem system : JAASSystem . getAllJAASSystems ( ) ) { final Set < ? > users = _login . getSubject ( ) . getPrincipals ( system . getPersonJAASPrincipleClass ( ) ) ; for ( final Object persObj : users ) { try { for ( final Map . Entry < Person . AttrName , Method > entry : system . getPersonMethodAttributes ( ) . entrySet ( ) ) { _person . updateAttrValue ( entry . getKey ( ) , ( String ) entry . getValue ( ) . invoke ( persObj ) ) ; } } catch ( final IllegalAccessException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "IllegalAccessException" , e ) ; } catch ( final IllegalArgumentException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "IllegalArgumentException" , e ) ; } catch ( final InvocationTargetException e ) { LoginHandler . LOG . error ( "could not execute a person method for system " + system . getName ( ) , e ) ; throw new EFapsException ( LoginHandler . class , "InvocationTargetException" , e ) ; } } } _person . commitAttrValuesInDB ( ) ; }
The person information inside eFaps is update with information from JAAS login context .
10,059
protected void updateRoles ( final LoginContext _login , final Person _person ) throws EFapsException { for ( final JAASSystem system : JAASSystem . getAllJAASSystems ( ) ) { if ( system . getRoleJAASPrincipleClass ( ) != null ) { final Set < ? > rolesJaas = _login . getSubject ( ) . getPrincipals ( system . getRoleJAASPrincipleClass ( ) ) ; final Set < Role > rolesEfaps = new HashSet < > ( ) ; for ( final Object roleObj : rolesJaas ) { try { final String roleKey = ( String ) system . getRoleMethodKey ( ) . invoke ( roleObj ) ; final Role roleEfaps = Role . getWithJAASKey ( system , roleKey ) ; if ( roleEfaps != null ) { rolesEfaps . add ( roleEfaps ) ; } } catch ( final IllegalAccessException e ) { LoginHandler . LOG . error ( "could not execute role key method for system " + system . getName ( ) , e ) ; } catch ( final IllegalArgumentException e ) { LoginHandler . LOG . error ( "could not execute role key method for system " + system . getName ( ) , e ) ; } catch ( final InvocationTargetException e ) { LoginHandler . LOG . error ( "could not execute role key method for system " + system . getName ( ) , e ) ; } } _person . setRoles ( system , rolesEfaps ) ; } } }
The roles of the given person are updated with the information from the JAAS login context .
10,060
protected void updateGroups ( final LoginContext _login , final Person _person ) throws EFapsException { for ( final JAASSystem system : JAASSystem . getAllJAASSystems ( ) ) { if ( system . getGroupJAASPrincipleClass ( ) != null ) { final Set < ? > groupsJaas = _login . getSubject ( ) . getPrincipals ( system . getGroupJAASPrincipleClass ( ) ) ; final Set < Group > groupsEfaps = new HashSet < > ( ) ; for ( final Object groupObj : groupsJaas ) { try { final String groupKey = ( String ) system . getGroupMethodKey ( ) . invoke ( groupObj ) ; final Group groupEfaps = Group . getWithJAASKey ( system , groupKey ) ; if ( groupEfaps != null ) { groupsEfaps . add ( groupEfaps ) ; } } catch ( final IllegalAccessException e ) { LoginHandler . LOG . error ( "could not execute group key method for system " + system . getName ( ) , e ) ; } catch ( final IllegalArgumentException e ) { LoginHandler . LOG . error ( "could not execute group key method for system " + system . getName ( ) , e ) ; } catch ( final InvocationTargetException e ) { LoginHandler . LOG . error ( "could not execute group key method for system " + system . getName ( ) , e ) ; } } _person . setGroups ( system , groupsEfaps ) ; } } }
The groups of the given person are updated with the information from the JAAS login context .
10,061
public Attachment updateWithUploadDetails ( UploadContentResponse response ) { this . id = response . getId ( ) ; this . url = response . getUrl ( ) ; this . size = response . getSize ( ) ; this . type = response . getType ( ) ; return this ; }
For internal use . Update attachment details with upload APIs response .
10,062
protected void initTableInfoUniqueKeys ( final Connection _con , final String _sql , final Map < String , TableInformation > _cache4Name ) throws SQLException { final String sqlStmt = new StringBuilder ( ) . append ( "select t.tablename as TABLE_NAME, c.CONSTRAINTNAME as INDEX_NAME, g.DESCRIPTOR as COLUMN_NAME" ) . append ( " from SYS.SYSTABLES t, SYS.SYSCONSTRAINTS c, SYS.SYSKEYS k, SYS.SYSCONGLOMERATES g " ) . append ( " where t.TABLEID=c.TABLEID" ) . append ( " AND c.TYPE='U'" ) . append ( " AND c.CONSTRAINTID = k.CONSTRAINTID" ) . append ( " AND k.CONGLOMERATEID = g.CONGLOMERATEID" ) . toString ( ) ; super . initTableInfoUniqueKeys ( _con , sqlStmt , _cache4Name ) ; }
Fetches all unique keys for this table . Instead of using the JDBC meta data functionality a SQL statement on system tables are used because the JDBC meta data functionality returns for unique keys internal names and not the real names . Also if a unique key includes also columns with null values this unique keys are not included .
10,063
private void backup ( final FileObject _backup , final int _number ) throws FileSystemException { if ( _number < this . numberBackup ) { final FileObject backFile = this . manager . resolveFile ( this . manager . getBaseFile ( ) , this . storeFileName + VFSStoreResource . EXTENSION_BACKUP + _number ) ; if ( backFile . exists ( ) ) { backup ( backFile , _number + 1 ) ; } _backup . moveTo ( backFile ) ; } else { _backup . delete ( ) ; } }
Method that deletes the oldest backup and moves the others one up .
10,064
public Xid [ ] recover ( final int _flag ) { if ( VFSStoreResource . LOG . isDebugEnabled ( ) ) { VFSStoreResource . LOG . debug ( "recover (flag = " + _flag + ")" ) ; } return null ; }
Obtains a list of prepared transaction branches from a resource manager .
10,065
Observable < ChatResult > sendMessageWithAttachments ( final String conversationId , final MessageToSend message , final List < Attachment > attachments ) { final MessageProcessor messageProcessor = attCon . createMessageProcessor ( message , attachments , conversationId , getProfileId ( ) ) ; return checkState ( ) . flatMap ( client -> { messageProcessor . preparePreUpload ( ) ; return upsertTempMessage ( messageProcessor . createTempMessage ( ) ) . flatMap ( isOk -> attCon . uploadAttachments ( messageProcessor . getAttachments ( ) , client ) ) . flatMap ( uploaded -> { if ( uploaded != null && ! uploaded . isEmpty ( ) ) { messageProcessor . preparePostUpload ( uploaded ) ; return upsertTempMessage ( messageProcessor . createTempMessage ( ) ) ; } else { return Observable . fromCallable ( ( ) -> true ) ; } } ) . flatMap ( isOk -> client . service ( ) . messaging ( ) . sendMessage ( conversationId , messageProcessor . prepareMessageToSend ( ) ) . flatMap ( result -> result . isSuccessful ( ) ? updateStoreWithSentMsg ( messageProcessor , result ) : handleMessageError ( messageProcessor , new ComapiException ( result . getErrorBody ( ) ) ) ) . onErrorResumeNext ( t -> handleMessageError ( messageProcessor , t ) ) ) ; } ) ; }
Save and send message with attachments .
10,066
public Observable < ChatResult > handleParticipantsAdded ( final String conversationId ) { return persistenceController . getConversation ( conversationId ) . flatMap ( conversation -> { if ( conversation == null ) { return handleNoLocalConversation ( conversationId ) ; } else { return Observable . fromCallable ( ( ) -> new ChatResult ( true , null ) ) ; } } ) ; }
Handle participant added to a conversation Foundation SDK event .
10,067
private Observable < ChatResult > handleMessageError ( MessageProcessor mp , Throwable t ) { return persistenceController . updateStoreForSentError ( mp . getConversationId ( ) , mp . getTempId ( ) , mp . getSender ( ) ) . map ( success -> new ChatResult ( false , new ChatResult . Error ( 0 , t ) ) ) ; }
Handle failure when sent message .
10,068
Observable < RxComapiClient > checkState ( ) { final RxComapiClient client = clientReference . get ( ) ; if ( client == null ) { return Observable . error ( new ComapiException ( "No client instance available in controller." ) ) ; } else { return Observable . fromCallable ( ( ) -> client ) ; } }
Checks if controller state is correct .
10,069
Observable < ChatResult > handleNoLocalConversation ( String conversationId ) { return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . getConversation ( conversationId ) . flatMap ( result -> { if ( result . isSuccessful ( ) && result . getResult ( ) != null ) { return persistenceController . upsertConversation ( ChatConversation . builder ( ) . populate ( result . getResult ( ) , result . getETag ( ) ) . build ( ) ) . map ( success -> new ChatResult ( success , success ? null : new ChatResult . Error ( 0 , "External store reported failure." , "Error when inserting conversation " + conversationId ) ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( result ) ) ; } } ) ) ; }
When SDK detects missing conversation it makes query in services and saves in the saves locally .
10,070
Observable < ComapiResult < Void > > markDelivered ( String conversationId , Set < String > ids ) { final List < MessageStatusUpdate > updates = new ArrayList < > ( ) ; updates . add ( MessageStatusUpdate . builder ( ) . setMessagesIds ( ids ) . setStatus ( MessageStatus . delivered ) . setTimestamp ( DateHelper . getCurrentUTC ( ) ) . build ( ) ) ; return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . updateMessageStatus ( conversationId , updates ) . retryWhen ( observable -> { return observable . zipWith ( Observable . range ( 1 , 3 ) , ( Func2 < Throwable , Integer , Integer > ) ( throwable , integer ) -> integer ) . flatMap ( new Func1 < Integer , Observable < Long > > ( ) { public Observable < Long > call ( Integer retryCount ) { return Observable . timer ( ( long ) Math . pow ( 1 , retryCount ) , TimeUnit . SECONDS ) ; } } ) ; } ) ) ; }
Mark messages in a conversations as delivered .
10,071
String getProfileId ( ) { final RxComapiClient client = clientReference . get ( ) ; return client != null ? client . getSession ( ) . getProfileId ( ) : null ; }
Gets profile id from Foundation for the active user .
10,072
Observable < ChatResult > synchroniseStore ( ) { if ( isSynchronising . getAndSet ( true ) ) { log . i ( "Synchronisation in progress." ) ; return Observable . fromCallable ( ( ) -> new ChatResult ( true , null ) ) ; } log . i ( "Synchronising store." ) ; return synchroniseConversations ( ) . onErrorReturn ( t -> new ChatResult ( false , new ChatResult . Error ( 0 , t ) ) ) . doOnNext ( i -> { if ( i . isSuccessful ( ) ) { log . i ( "Synchronisation successfully finished." ) ; } else { log . e ( "Synchronisation finished with error. " + ( i . getError ( ) != null ? i . getError ( ) . getDetails ( ) : "" ) ) ; } isSynchronising . compareAndSet ( true , false ) ; } ) ; }
Check state for all conversations and update from services .
10,073
Observable < ChatResult > handleConversationCreated ( ComapiResult < ConversationDetails > result ) { if ( result . isSuccessful ( ) ) { return persistenceController . upsertConversation ( ChatConversation . builder ( ) . populate ( result . getResult ( ) , result . getETag ( ) ) . build ( ) ) . map ( success -> adapter . adaptResult ( result , success ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( result ) ) ; } }
Handles conversation create service response .
10,074
Observable < ChatResult > handleConversationDeleted ( String conversationId , ComapiResult < Void > result ) { if ( result . getCode ( ) != ETAG_NOT_VALID ) { return persistenceController . deleteConversation ( conversationId ) . map ( success -> adapter . adaptResult ( result , success ) ) ; } else { return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . getConversation ( conversationId ) . flatMap ( newResult -> { if ( newResult . isSuccessful ( ) ) { return persistenceController . upsertConversation ( ChatConversation . builder ( ) . populate ( newResult . getResult ( ) , newResult . getETag ( ) ) . build ( ) ) . flatMap ( success -> Observable . fromCallable ( ( ) -> new ChatResult ( false , success ? new ChatResult . Error ( ETAG_NOT_VALID , "Conversation updated, try delete again." , "Conversation " + conversationId + " updated in response to wrong eTag error when deleting." ) : new ChatResult . Error ( 0 , "Error updating custom store." , null ) ) ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( newResult ) ) ; } } ) ) ; } }
Handles conversation delete service response .
10,075
Observable < ChatResult > handleConversationUpdated ( ConversationUpdate request , ComapiResult < ConversationDetails > result ) { if ( result . isSuccessful ( ) ) { return persistenceController . upsertConversation ( ChatConversation . builder ( ) . populate ( result . getResult ( ) , result . getETag ( ) ) . build ( ) ) . map ( success -> adapter . adaptResult ( result , success ) ) ; } if ( result . getCode ( ) == ETAG_NOT_VALID ) { return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . getConversation ( request . getId ( ) ) . flatMap ( newResult -> { if ( newResult . isSuccessful ( ) ) { return persistenceController . upsertConversation ( ChatConversation . builder ( ) . populate ( newResult . getResult ( ) , newResult . getETag ( ) ) . build ( ) ) . flatMap ( success -> Observable . fromCallable ( ( ) -> new ChatResult ( false , success ? new ChatResult . Error ( ETAG_NOT_VALID , "Conversation updated, try delete again." , "Conversation " + request . getId ( ) + " updated in response to wrong eTag error when updating." ) : new ChatResult . Error ( 1500 , "Error updating custom store." , null ) ) ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( newResult ) ) ; } } ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( result ) ) ; } }
Handles conversation update service response .
10,076
Observable < ChatResult > handleMessageStatusToUpdate ( String conversationId , List < MessageStatusUpdate > msgStatusList , ComapiResult < Void > result ) { if ( result . isSuccessful ( ) && msgStatusList != null && ! msgStatusList . isEmpty ( ) ) { return persistenceController . upsertMessageStatuses ( conversationId , getProfileId ( ) , msgStatusList ) . map ( success -> adapter . adaptResult ( result , success ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( result ) ) ; } }
Handles message status update service response .
10,077
private Observable < Boolean > upsertTempMessage ( ChatMessage message ) { return persistenceController . updateStoreWithNewMessage ( message , noConversationListener ) . doOnError ( t -> log . e ( "Error saving temp message " + t . getLocalizedMessage ( ) ) ) . onErrorReturn ( t -> false ) ; }
Insert temporary message to the store for the ui to be responsive .
10,078
Observable < ChatResult > updateStoreWithSentMsg ( MessageProcessor mp , ComapiResult < MessageSentResponse > response ) { if ( response . isSuccessful ( ) ) { return persistenceController . updateStoreWithNewMessage ( mp . createFinalMessage ( response . getResult ( ) ) , noConversationListener ) . map ( success -> adapter . adaptResult ( response , success ) ) ; } else { return Observable . fromCallable ( ( ) -> adapter . adaptResult ( response ) ) ; } }
Handles message send service response . Will delete temporary message object . Same message but with correct message id will be inserted instead .
10,079
private Observable < ChatResult > synchroniseConversations ( ) { return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . getConversations ( false ) . flatMap ( result -> persistenceController . loadAllConversations ( ) . map ( chatConversationBases -> compare ( result . isSuccessful ( ) , result . getResult ( ) , chatConversationBases ) ) ) . flatMap ( this :: updateLocalConversationList ) . flatMap ( result -> lookForMissingEvents ( client , result ) ) . map ( result -> new ChatResult ( result . isSuccessful , null ) ) ) ; }
Updates all conversation states .
10,080
ConversationComparison compare ( boolean successful , List < Conversation > remote , List < ChatConversationBase > local ) { return new ConversationComparison ( successful , makeMapFromDownloadedConversations ( remote ) , makeMapFromSavedConversations ( local ) ) ; }
Compares remote and local conversation lists .
10,081
Observable < ChatResult > synchroniseConversation ( String conversationId ) { return checkState ( ) . flatMap ( client -> client . service ( ) . messaging ( ) . queryMessages ( conversationId , null , 1 ) . map ( result -> { if ( result . isSuccessful ( ) && result . getResult ( ) != null ) { return ( long ) result . getResult ( ) . getLatestEventId ( ) ; } return - 1L ; } ) . flatMap ( result -> persistenceController . getConversation ( conversationId ) . map ( loaded -> compare ( result , loaded ) ) ) . flatMap ( this :: updateLocalConversationList ) . flatMap ( result -> lookForMissingEvents ( client , result ) ) . map ( result -> new ChatResult ( result . isSuccessful , null ) ) ) ; }
Updates single conversation state .
10,082
private Observable < ConversationComparison > lookForMissingEvents ( final RxComapiClient client , ConversationComparison conversationComparison ) { if ( ! conversationComparison . isSuccessful || conversationComparison . conversationsToUpdate . isEmpty ( ) ) { return Observable . fromCallable ( ( ) -> conversationComparison ) ; } return synchroniseEvents ( client , conversationComparison . conversationsToUpdate , new ArrayList < > ( ) ) . map ( result -> { if ( conversationComparison . isSuccessful && ! result ) { conversationComparison . addSuccess ( false ) ; } return conversationComparison ; } ) ; }
Checks services for missing events in stored conversations .
10,083
private Observable < ConversationComparison > updateLocalConversationList ( final ConversationComparison conversationComparison ) { return Observable . zip ( persistenceController . deleteConversations ( conversationComparison . conversationsToDelete ) , persistenceController . upsertConversations ( conversationComparison . conversationsToAdd ) , persistenceController . updateConversations ( conversationComparison . conversationsToUpdate ) , ( success1 , success2 , success3 ) -> success1 && success2 && success3 ) . map ( result -> { conversationComparison . addSuccess ( result ) ; return conversationComparison ; } ) ; }
Update list of local conversations .
10,084
private Observable < Boolean > synchroniseEvents ( final RxComapiClient client , final List < ChatConversation > conversationsToUpdate , final List < Boolean > successes ) { final List < ChatConversation > limited = limitNumberOfConversations ( conversationsToUpdate ) ; if ( limited . isEmpty ( ) ) { return Observable . fromCallable ( ( ) -> true ) ; } return Observable . from ( limited ) . onBackpressureBuffer ( ) . flatMap ( conversation -> persistenceController . getConversation ( conversation . getConversationId ( ) ) ) . flatMap ( conversation -> { if ( conversation . getLastRemoteEventId ( ) > conversation . getLastLocalEventId ( ) ) { final long from = conversation . getLastLocalEventId ( ) >= 0 ? conversation . getLastLocalEventId ( ) : 0 ; return queryEventsRecursively ( client , conversation . getConversationId ( ) , from , 0 , successes ) . map ( ComapiResult :: isSuccessful ) ; } else { return Observable . fromCallable ( ( Callable < Object > ) ( ) -> true ) ; } } ) . flatMap ( res -> Observable . from ( successes ) . all ( Boolean :: booleanValue ) ) ; }
Synchronise missing events for the list of locally stored conversations .
10,085
private Observable < ComapiResult < ConversationEventsResponse > > queryEventsRecursively ( final RxComapiClient client , final String conversationId , final long lastEventId , final int count , final List < Boolean > successes ) { return client . service ( ) . messaging ( ) . queryConversationEvents ( conversationId , lastEventId , eventsPerQuery ) . flatMap ( result -> processEventsQueryResponse ( result , successes ) ) . flatMap ( result -> { if ( result . getResult ( ) != null && result . getResult ( ) . getEventsInOrder ( ) . size ( ) >= eventsPerQuery && count < maxEventQueries ) { return queryEventsRecursively ( client , conversationId , lastEventId + result . getResult ( ) . getEventsInOrder ( ) . size ( ) , count + 1 , successes ) ; } else { return Observable . just ( result ) ; } } ) ; }
Synchronise missing events for particular conversation .
10,086
private Observable < ComapiResult < ConversationEventsResponse > > processEventsQueryResponse ( ComapiResult < ConversationEventsResponse > result , final List < Boolean > successes ) { ConversationEventsResponse response = result . getResult ( ) ; successes . add ( result . isSuccessful ( ) ) ; if ( response != null && response . getEventsInOrder ( ) . size ( ) > 0 ) { Collection < Event > events = response . getEventsInOrder ( ) ; List < Observable < Boolean > > list = new ArrayList < > ( ) ; for ( Event event : events ) { if ( event instanceof MessageSentEvent ) { MessageSentEvent messageEvent = ( MessageSentEvent ) event ; list . add ( persistenceController . updateStoreWithNewMessage ( ChatMessage . builder ( ) . populate ( messageEvent ) . build ( ) , noConversationListener ) ) ; } else if ( event instanceof MessageDeliveredEvent ) { list . add ( persistenceController . upsertMessageStatus ( ChatMessageStatus . builder ( ) . populate ( ( MessageDeliveredEvent ) event ) . build ( ) ) ) ; } else if ( event instanceof MessageReadEvent ) { list . add ( persistenceController . upsertMessageStatus ( ChatMessageStatus . builder ( ) . populate ( ( MessageReadEvent ) event ) . build ( ) ) ) ; } } return Observable . from ( list ) . flatMap ( task -> task ) . doOnNext ( successes :: add ) . toList ( ) . map ( results -> result ) ; } return Observable . fromCallable ( ( ) -> result ) ; }
Process the event query response . Calls appropraiate persistance controller methods for received events .
10,087
private List < ChatConversation > limitNumberOfConversations ( List < ChatConversation > conversations ) { List < ChatConversation > noEmptyConversations = new ArrayList < > ( ) ; for ( ChatConversation c : conversations ) { if ( c . getLastRemoteEventId ( ) != null && c . getLastRemoteEventId ( ) >= 0 ) { noEmptyConversations . add ( c ) ; } } List < ChatConversation > limitedList ; if ( noEmptyConversations . size ( ) <= maxConversationsSynced ) { limitedList = noEmptyConversations ; } else { SortedMap < Long , ChatConversation > sorted = new TreeMap < > ( ) ; for ( ChatConversation conversation : noEmptyConversations ) { Long updatedOn = conversation . getUpdatedOn ( ) ; if ( updatedOn != null ) { sorted . put ( updatedOn , conversation ) ; } } limitedList = new ArrayList < > ( ) ; Object [ ] array = sorted . values ( ) . toArray ( ) ; for ( int i = 0 ; i < Math . min ( maxConversationsSynced , array . length ) ; i ++ ) { limitedList . add ( ( ChatConversation ) array [ i ] ) ; } } return limitedList ; }
Limits number of conversations to check and synchronise . Emty conversations wont be synchronised . The synchronisation will take place for twenty conversations updated most recently .
10,088
public Observable < Boolean > handleMessage ( final ChatMessage message ) { String sender = message . getSentBy ( ) ; Observable < Boolean > replaceMessages = persistenceController . updateStoreWithNewMessage ( message , noConversationListener ) ; if ( ! TextUtils . isEmpty ( sender ) && ! sender . equals ( getProfileId ( ) ) ) { final Set < String > ids = new HashSet < > ( ) ; ids . add ( message . getMessageId ( ) ) ; return Observable . zip ( replaceMessages , markDelivered ( message . getConversationId ( ) , ids ) , ( saved , result ) -> saved && result . isSuccessful ( ) ) ; } else { return replaceMessages ; } }
Handle incomming message . Replace temporary message with received one and mark as delivered .
10,089
public void analyzeEndStop ( ) { DFA < T > dfa = constructDFA ( new Scope < DFAState < T > > ( "analyzeEndStop" ) ) ; for ( DFAState < T > s : dfa ) { if ( s . isAccepting ( ) ) { if ( s . isEndStop ( ) ) { for ( NFAState < T > n : s . getNfaSet ( ) ) { if ( n . isAccepting ( ) ) { n . setEndStop ( true ) ; } } } } } }
Marks all nfa states that can be accepting to end stop .
10,090
public DFA < T > constructDFA ( Scope < DFAState < T > > scope ) { return new DFA < > ( first . constructDFA ( scope ) , scope . count ( ) ) ; }
Constructs a dfa from using first nfa state as starting state .
10,091
public void concat ( NFA < T > nfa ) { last . addEpsilon ( nfa . getFirst ( ) ) ; last = nfa . last ; }
Concatenates this to nfa by making epsilon move from this last to nfa first .
10,092
public static Application getApplicationFromSource ( final File _versionFile , final List < String > _classpathElements , final File _eFapsDir , final File _outputDir , final List < String > _includes , final List < String > _excludes , final Map < String , String > _file2typeMapping ) throws InstallationException { final Map < String , String > file2typeMapping = _file2typeMapping == null ? Application . DEFAULT_TYPE_MAPPING : _file2typeMapping ; final Application appl ; try { appl = Application . getApplication ( _versionFile . toURI ( ) . toURL ( ) , _eFapsDir . toURI ( ) . toURL ( ) , _classpathElements ) ; for ( final String fileName : Application . getFiles ( _eFapsDir , _includes , _excludes ) ) { final String type = file2typeMapping . get ( fileName . substring ( fileName . lastIndexOf ( "." ) + 1 ) ) ; appl . install . addFile ( new InstallFile ( ) . setType ( type ) . setURL ( new File ( _eFapsDir , fileName ) . toURI ( ) . toURL ( ) ) ) ; } if ( _outputDir . exists ( ) ) { for ( final String fileName : Application . getFiles ( _outputDir , _includes , _excludes ) ) { final String type = file2typeMapping . get ( fileName . substring ( fileName . lastIndexOf ( "." ) + 1 ) ) ; appl . install . addFile ( new InstallFile ( ) . setType ( type ) . setURL ( new File ( _outputDir , fileName ) . toURI ( ) . toURL ( ) ) ) ; } } } catch ( final IOException e ) { throw new InstallationException ( "Could not open / read version file " + "'" + _versionFile + "'" , e ) ; } catch ( final Exception e ) { throw new InstallationException ( "Read version file '" + _versionFile + "' failed" , e ) ; } return appl ; }
Returns the application definition read from a source directory .
10,093
public static Application getApplicationFromClassPath ( final String _application , final List < String > _classpath ) throws InstallationException { return Application . getApplicationsFromClassPath ( _application , _classpath ) . get ( _application ) ; }
Method to get the applications from the class path .
10,094
public static Map < String , Application > getApplicationsFromClassPath ( final String _application , final List < String > _classpath ) throws InstallationException { final Map < String , Application > appls = new HashMap < > ( ) ; try { final ClassLoader parent = Application . class . getClassLoader ( ) ; final List < URL > urls = new ArrayList < > ( ) ; for ( final String pathElement : _classpath ) { urls . add ( new File ( pathElement ) . toURI ( ) . toURL ( ) ) ; } final URLClassLoader cl = URLClassLoader . newInstance ( urls . toArray ( new URL [ urls . size ( ) ] ) , parent ) ; final Enumeration < URL > urlEnum = cl . getResources ( "META-INF/efaps/install.xml" ) ; while ( urlEnum . hasMoreElements ( ) ) { final URL url = urlEnum . nextElement ( ) ; final Application appl = Application . getApplication ( url , new URL ( url , "../../../" ) , _classpath ) ; appls . put ( appl . getApplication ( ) , appl ) ; } } catch ( final IOException e ) { throw new InstallationException ( "Could not access the install.xml file " + "(in path META-INF/efaps/ path of each eFaps install jar)." , e ) ; } return appls ; }
Method to get all applications from the class path .
10,095
public void updateLastVersion ( final String _userName , final String _password , final Set < Profile > _profiles ) throws Exception { reloadCache ( ) ; Context . begin ( ) ; EFapsClassLoader . getOfflineInstance ( getClass ( ) . getClassLoader ( ) ) ; final Map < String , Integer > latestVersions = this . install . getLatestVersions ( ) ; Context . rollback ( ) ; final long latestVersion = latestVersions . get ( this . application ) ; final ApplicationVersion version = getLastVersion ( ) ; if ( version . getNumber ( ) == latestVersion ) { Application . LOG . info ( "Update version '{}' of application '{}' " , version . getNumber ( ) , this . application ) ; version . install ( this . install , version . getNumber ( ) , _profiles , _userName , _password ) ; Application . LOG . info ( "Finished update of version '{}'" , version . getNumber ( ) ) ; } else { Application . LOG . error ( "Version {}' of application '{}' not installed and could not updated!" , version . getNumber ( ) , this . application ) ; } }
Updates the last installed version .
10,096
protected void reloadCache ( ) throws InstallationException { try { LOG . info ( "Reloading Cache" ) ; Context . begin ( ) ; if ( RunLevel . isInitialisable ( ) ) { RunLevel . init ( "shell" ) ; RunLevel . execute ( ) ; } Context . commit ( ) ; } catch ( final EFapsException e ) { throw new InstallationException ( "Reload cache failed" , e ) ; } }
Reloads the eFaps cache .
10,097
public String getString ( long start , int length ) { if ( length == 0 ) { return "" ; } if ( array != null ) { int ps = ( int ) ( start % size ) ; int es = ( int ) ( ( start + length ) % size ) ; if ( ps < es ) { return new String ( array , ps , length ) ; } else { StringBuilder sb = new StringBuilder ( ) ; sb . append ( array , ps , size - ps ) ; sb . append ( array , 0 , es ) ; return sb . toString ( ) ; } } else { StringBuilder sb = new StringBuilder ( ) ; for ( int ii = 0 ; ii < length ; ii ++ ) { sb . append ( ( char ) get ( start + ii ) ) ; } return sb . toString ( ) ; } }
Returns string from buffer
10,098
static Map < String , Set < String > > groupNameToSet ( GravityNameValue [ ] nameValues ) { Map < String , Set < String > > result = new HashMap < > ( ) ; for ( GravityNameValue nameValue : nameValues ) { if ( nameValue . name == null || nameValue . value == null ) continue ; if ( ! result . containsKey ( nameValue . name ) ) result . put ( nameValue . name , new LinkedHashSet < String > ( ) ) ; Collections . addAll ( result . get ( nameValue . name ) , nameValue . value ) ; } return result ; }
Transform grouped into a map of name to a linked set of values
10,099
protected void setFileInfo ( final String _filename , final long _fileLength ) throws EFapsException { if ( ! _filename . equals ( this . fileName ) || _fileLength != this . fileLength ) { ConnectionResource res = null ; try { res = Context . getThreadContext ( ) . getConnectionResource ( ) ; final AbstractDatabase < ? > db = Context . getDbType ( ) ; final StringBuilder cmd = new StringBuilder ( ) . append ( db . getSQLPart ( SQLPart . UPDATE ) ) . append ( " " ) . append ( db . getTableQuote ( ) ) . append ( AbstractStoreResource . TABLENAME_STORE ) . append ( db . getTableQuote ( ) ) . append ( " " ) . append ( db . getSQLPart ( SQLPart . SET ) ) . append ( " " ) . append ( db . getColumnQuote ( ) ) . append ( AbstractStoreResource . COLNAME_FILENAME ) . append ( db . getColumnQuote ( ) ) . append ( db . getSQLPart ( SQLPart . EQUAL ) ) . append ( "? " ) . append ( db . getSQLPart ( SQLPart . COMMA ) ) . append ( db . getColumnQuote ( ) ) . append ( AbstractStoreResource . COLNAME_FILELENGTH ) . append ( db . getColumnQuote ( ) ) . append ( db . getSQLPart ( SQLPart . EQUAL ) ) . append ( "? " ) . append ( db . getSQLPart ( SQLPart . WHERE ) ) . append ( " " ) . append ( db . getColumnQuote ( ) ) . append ( "ID" ) . append ( db . getColumnQuote ( ) ) . append ( db . getSQLPart ( SQLPart . EQUAL ) ) . append ( getGeneralID ( ) ) ; final PreparedStatement stmt = res . prepareStatement ( cmd . toString ( ) ) ; try { stmt . setString ( 1 , _filename ) ; stmt . setLong ( 2 , _fileLength ) ; stmt . execute ( ) ; } finally { stmt . close ( ) ; } } catch ( final EFapsException e ) { throw e ; } catch ( final SQLException e ) { throw new EFapsException ( JDBCStoreResource . class , "write.SQLException" , e ) ; } } }
Set the info for the file in this store reosurce .