idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
4,800
private void checkNeededValues ( TransformationDescription description ) { String message = "The TransformationDescription doesn't contain a %s. Description loading aborted" ; if ( description . getSourceModel ( ) . getModelClassName ( ) == null ) { throw new IllegalArgumentException ( String . format ( message , "source class" ) ) ; } if ( description . getTargetModel ( ) . getModelClassName ( ) == null ) { throw new IllegalArgumentException ( String . format ( message , "target class" ) ) ; } String message2 = "The version string of the %s is not a correct version string. Description loading aborted" ; try { Version . parseVersion ( description . getSourceModel ( ) . getVersionString ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( String . format ( message2 , "source class" ) , e ) ; } try { Version . parseVersion ( description . getTargetModel ( ) . getVersionString ( ) ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( String . format ( message2 , "target class" ) , e ) ; } }
Does the checking of all necessary values of the TransformationDescription which are needed to process the description
250
18
4,801
public Object transformObject ( TransformationDescription description , Object source ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { return transformObject ( description , source , null ) ; }
Transforms the given object based on the given TransformationDescription .
38
12
4,802
public Object transformObject ( TransformationDescription description , Object source , Object target ) throws InstantiationException , IllegalAccessException , ClassNotFoundException { checkNeededValues ( description ) ; Class < ? > sourceClass = modelRegistry . loadModel ( description . getSourceModel ( ) ) ; Class < ? > targetClass = modelRegistry . loadModel ( description . getTargetModel ( ) ) ; if ( ! sourceClass . isAssignableFrom ( source . getClass ( ) ) ) { throw new IllegalArgumentException ( "The given source object does not match the given description" ) ; } this . source = source ; if ( target == null ) { this . target = targetClass . newInstance ( ) ; } else { this . target = target ; } for ( TransformationStep step : description . getTransformingSteps ( ) ) { performTransformationStep ( step ) ; } return this . target ; }
Performs a transformation based merge of the given source object with the given target object based on the given TransformationDescription .
193
23
4,803
private void performTransformationStep ( TransformationStep step ) throws IllegalAccessException { try { TransformationOperation operation = operationLoader . loadTransformationOperationByName ( step . getOperationName ( ) ) ; Object value = operation . performOperation ( getSourceFieldValues ( step ) , step . getOperationParams ( ) ) ; setObjectToTargetField ( step . getTargetField ( ) , value ) ; } catch ( TransformationStepException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } catch ( Exception e ) { LOGGER . error ( "Unable to perform transformation step {}." , step , e ) ; } }
Performs one transformation step
137
5
4,804
private List < Object > getSourceFieldValues ( TransformationStep step ) throws Exception { List < Object > sources = new ArrayList < Object > ( ) ; for ( String sourceField : step . getSourceFields ( ) ) { Object object = getObjectValue ( sourceField , true ) ; if ( object == null ) { String message = String . format ( "The source field %s is null. Step will be be ignored" , sourceField ) ; throw new TransformationStepException ( message ) ; } sources . add ( object ) ; } return sources ; }
Returns a list of actual field values from the sources of the given transformation step
117
15
4,805
private void setObjectToTargetField ( String fieldname , Object value ) throws Exception { Object toWrite = null ; if ( fieldname . contains ( "." ) ) { String path = StringUtils . substringBeforeLast ( fieldname , "." ) ; toWrite = getObjectValue ( path , false ) ; } if ( toWrite == null && isTemporaryField ( fieldname ) ) { String mapKey = StringUtils . substringAfter ( fieldname , "#" ) ; mapKey = StringUtils . substringBefore ( mapKey , "." ) ; temporaryFields . put ( mapKey , value ) ; return ; } String realFieldName = fieldname . contains ( "." ) ? StringUtils . substringAfterLast ( fieldname , "." ) : fieldname ; writeObjectToField ( realFieldName , value , toWrite , target ) ; }
Sets the given value object to the field with the field name of the target object . Is also aware of temporary fields .
188
25
4,806
private Object getObjectValue ( String fieldname , boolean fromSource ) throws Exception { Object sourceObject = fromSource ? source : target ; Object result = null ; for ( String part : StringUtils . split ( fieldname , "." ) ) { if ( isTemporaryField ( part ) ) { result = loadObjectFromTemporary ( part , fieldname ) ; } else { result = loadObjectFromField ( part , result , sourceObject ) ; } } return result ; }
Gets the value of the field with the field name either from the source object or the target object depending on the parameters . Is also aware of temporary fields .
101
32
4,807
private Object loadObjectFromField ( String fieldname , Object object , Object alternative ) throws Exception { Object source = object != null ? object : alternative ; try { return FieldUtils . readField ( source , fieldname , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( String . format ( "Unable to load field '%s' from object '%s'" , fieldname , source . getClass ( ) . getName ( ) ) ) ; } }
Loads the object from the field with the given name from either the object parameter or if this parameter is null from the alternative parameter .
103
27
4,808
private void writeObjectToField ( String fieldname , Object value , Object object , Object alternative ) throws Exception { Object target = object != null ? object : alternative ; try { FieldUtils . writeField ( target , fieldname , value , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( String . format ( "Unable to write value '%s' to field '%s' of object %s" , value . toString ( ) , fieldname , target . getClass ( ) . getName ( ) ) ) ; } }
Writes a value to the object from the field with the given name from either the object parameter or if this parameter is null from the alternative parameter .
119
30
4,809
private static Object waitForServiceFromTracker ( ServiceTracker tracker , long timeout ) throws OsgiServiceNotAvailableException { synchronized ( tracker ) { tracker . open ( ) ; try { return tracker . waitForService ( timeout ) ; } catch ( InterruptedException e ) { throw new OsgiServiceNotAvailableException ( e ) ; } finally { tracker . close ( ) ; } } }
tries to retrieve the service from the given service - tracker for the amount of milliseconds provided by the given timeout .
80
23
4,810
protected double [ ] getDialogDimensions ( String message , VaadinConfirmDialog . ContentMode style ) { // Based on Reindeer style: double chrW = 0.51d ; double chrH = 1.5d ; double length = message != null ? chrW * message . length ( ) : 0 ; double rows = Math . ceil ( length / MAX_WIDTH ) ; // Estimate extra lines if ( style == VaadinConfirmDialog . ContentMode . TEXT_WITH_NEWLINES ) { rows += message != null ? count ( "\n" , message ) : 0 ; } //System.out.println(message.length() + " = " + length + "em"); //System.out.println("Rows: " + (length / MAX_WIDTH) + " = " + rows); // Obey maximum size double width = Math . min ( MAX_WIDTH , length ) ; double height = Math . ceil ( Math . min ( MAX_HEIGHT , rows * chrH ) ) ; // Obey the minimum size width = Math . max ( width , MIN_WIDTH ) ; height = Math . max ( height , MIN_HEIGHT ) ; // Based on Reindeer style: double btnHeight = 4d ; double vmargin = 5d ; double hmargin = 1d ; double [ ] res = new double [ ] { width + hmargin , height + btnHeight + vmargin } ; //System.out.println(res[0] + "," + res[1]); return res ; }
Approximates the dialog dimensions based on its message length .
341
12
4,811
private static int count ( final String needle , final String haystack ) { int count = 0 ; int pos = - 1 ; while ( ( pos = haystack . indexOf ( needle , pos + 1 ) ) >= 0 ) { count ++ ; } return count ; }
Count the number of needles within a haystack .
56
10
4,812
private String format ( double n ) { NumberFormat nf = NumberFormat . getNumberInstance ( Locale . ENGLISH ) ; nf . setMaximumFractionDigits ( 1 ) ; nf . setGroupingUsed ( false ) ; return nf . format ( n ) ; }
Format a double single fraction digit .
62
7
4,813
public ModelDescription getModelDescription ( ) { String modelType = object . getString ( EDBConstants . MODEL_TYPE ) ; String version = object . getString ( EDBConstants . MODEL_TYPE_VERSION ) ; return new ModelDescription ( modelType , version ) ; }
Returns the model description for the model class of the EDBModelObject
64
14
4,814
public OpenEngSBModel getCorrespondingModel ( ) throws EKBException { ModelDescription description = getModelDescription ( ) ; try { Class < ? > modelClass = modelRegistry . loadModel ( description ) ; return ( OpenEngSBModel ) edbConverter . convertEDBObjectToModel ( modelClass , object ) ; } catch ( ClassNotFoundException e ) { throw new EKBException ( String . format ( "Unable to load model of type %s" , description ) , e ) ; } }
Returns the corresponding model object for the EDBModelObject
112
11
4,815
public Iterator iterator ( ) { CsvPreference preferences = new CsvPreference . Builder ( m_quoteChar , m_delimiterChar , m_endOfLineSymbols ) . build ( ) ; return new CsvIterator ( new CsvListReader ( m_reader , preferences ) , m_header ) ; }
Return an iterator over this source .
72
7
4,816
protected Serializable getCompiledExpression ( ) { if ( compiledExpression == null ) { compiledExpression = MVEL . compileExpression ( getExpression ( ) , PARSER_CONTEXT ) ; } return compiledExpression ; }
Return a compiled MVEL expression .
52
7
4,817
protected Serializable getCompiledSetExpression ( ) { if ( compiledSetExpression == null ) { compiledSetExpression = MVEL . compileSetExpression ( getExpression ( ) , PARSER_CONTEXT ) ; } return compiledSetExpression ; }
Return a compiled MVEL set expression .
57
8
4,818
public void attachFormValidator ( final Form < ? > form , final FormValidator validator ) { form . add ( new AbstractFormValidator ( ) { private static final long serialVersionUID = - 4181095793820830517L ; @ Override public void validate ( Form < ? > form ) { Map < String , FormComponent < ? > > loadFormComponents = loadFormComponents ( form ) ; Map < String , String > toValidate = new HashMap < String , String > ( ) ; for ( Map . Entry < String , FormComponent < ? > > entry : loadFormComponents . entrySet ( ) ) { toValidate . put ( entry . getKey ( ) , entry . getValue ( ) . getValue ( ) ) ; } try { validator . validate ( toValidate ) ; } catch ( ConnectorValidationFailedException e ) { Map < String , String > attributeErrorMessages = e . getErrorMessages ( ) ; for ( Map . Entry < String , String > entry : attributeErrorMessages . entrySet ( ) ) { FormComponent < ? > fc = loadFormComponents . get ( entry . getKey ( ) ) ; fc . error ( new ValidationError ( ) . setMessage ( entry . getValue ( ) ) ) ; } } } @ Override public FormComponent < ? > [ ] getDependentFormComponents ( ) { Collection < FormComponent < ? > > formComponents = loadFormComponents ( form ) . values ( ) ; return formComponents . toArray ( new FormComponent < ? > [ formComponents . size ( ) ] ) ; } private Map < String , FormComponent < ? > > loadFormComponents ( final Form < ? > form ) { Map < String , FormComponent < ? > > formComponents = new HashMap < String , FormComponent < ? > > ( ) ; if ( validator != null ) { for ( String attribute : validator . fieldsToValidate ( ) ) { Component component = form . get ( "attributesPanel:fields:" + attribute + ":row:field" ) ; if ( component instanceof FormComponent < ? > ) { formComponents . put ( attribute , ( FormComponent < ? > ) component ) ; } } } return formComponents ; } } ) ; }
attach a ServiceValidator to the given form . This formValidator is meant to validate the fields in context to each other . This validation is only done on submit .
497
34
4,819
protected Long performCommitLogic ( EDBCommit commit ) throws EDBException { if ( ! ( commit instanceof JPACommit ) ) { throw new EDBException ( "The given commit type is not supported." ) ; } if ( commit . isCommitted ( ) ) { throw new EDBException ( "EDBCommit is already commitet." ) ; } if ( revisionCheckEnabled && commit . getParentRevisionNumber ( ) != null && ! commit . getParentRevisionNumber ( ) . equals ( getCurrentRevisionNumber ( ) ) ) { throw new EDBException ( "EDBCommit do not have the correct head revision number." ) ; } runBeginCommitHooks ( commit ) ; EDBException exception = runPreCommitHooks ( commit ) ; if ( exception != null ) { return runErrorHooks ( commit , exception ) ; } Long timestamp = performCommit ( ( JPACommit ) commit ) ; runEDBPostHooks ( commit ) ; return timestamp ; }
Performs the actual commit logic for the EDB including the hooks and the revision checking .
219
18
4,820
private void persistCommitChanges ( JPACommit commit , Long timestamp ) { commit . setTimestamp ( timestamp ) ; addModifiedObjectsToEntityManager ( commit . getJPAObjects ( ) , timestamp ) ; commit . setCommitted ( true ) ; logger . debug ( "persisting JPACommit" ) ; entityManager . persist ( commit ) ; logger . debug ( "mark the deleted elements as deleted" ) ; updateDeletedObjectsThroughEntityManager ( commit . getDeletions ( ) , timestamp ) ; }
Add all the changes which are done through the given commit object to the entity manager .
115
17
4,821
private void addModifiedObjectsToEntityManager ( List < JPAObject > modified , Long timestamp ) { for ( JPAObject update : modified ) { update . setTimestamp ( timestamp ) ; entityManager . persist ( update ) ; } }
Updates all modified EDBObjects with the timestamp and persist them through the entity manager .
52
19
4,822
private void updateDeletedObjectsThroughEntityManager ( List < String > oids , Long timestamp ) { for ( String id : oids ) { EDBObject o = new EDBObject ( id ) ; o . updateTimestamp ( timestamp ) ; o . setDeleted ( true ) ; JPAObject j = EDBUtils . convertEDBObjectToJPAObject ( o ) ; entityManager . persist ( j ) ; } }
Updates all deleted objects with the timestamp mark them as deleted and persist them through the entity manager .
94
20
4,823
private void runBeginCommitHooks ( EDBCommit commit ) throws EDBException { for ( EDBBeginCommitHook hook : beginCommitHooks ) { try { hook . onStartCommit ( commit ) ; } catch ( ServiceUnavailableException e ) { // Ignore } catch ( EDBException e ) { throw e ; } catch ( Exception e ) { logger . error ( "Error while performing EDBBeginCommitHook" , e ) ; } } }
Runs all registered begin commit hooks on the EDBCommit object . Logs exceptions which occurs in the hooks except for ServiceUnavailableExceptions and EDBExceptions . If an EDBException occurs it is thrown and so returned to the calling instance .
106
53
4,824
private EDBException runPreCommitHooks ( EDBCommit commit ) { EDBException exception = null ; for ( EDBPreCommitHook hook : preCommitHooks ) { try { hook . onPreCommit ( commit ) ; } catch ( ServiceUnavailableException e ) { // Ignore } catch ( EDBException e ) { exception = e ; break ; } catch ( Exception e ) { logger . error ( "Error while performing EDBPreCommitHook" , e ) ; } } return exception ; }
Runs all registered pre commit hooks on the EDBCommit object . Logs exceptions which occurs in the hooks except for ServiceUnavailableExceptions and EDBExceptions . If an EDBException occurs the function returns this exception .
115
48
4,825
private Long runErrorHooks ( EDBCommit commit , EDBException exception ) throws EDBException { for ( EDBErrorHook hook : errorHooks ) { try { EDBCommit newCommit = hook . onError ( commit , exception ) ; if ( newCommit != null ) { return commit ( newCommit ) ; } } catch ( ServiceUnavailableException e ) { // Ignore } catch ( EDBException e ) { exception = e ; break ; } catch ( Exception e ) { logger . error ( "Error while performing EDBErrorHook" , e ) ; } } throw exception ; }
Runs all registered error hooks on the EDBCommit object . Logs exceptions which occurs in the hooks except for ServiceUnavailableExceptions and EDBExceptions . If an EDBException occurs the function overrides the cause of the error with the new Exception . If an error hook returns a new EDBCommit the EDB tries to persist this commit instead .
133
76
4,826
private void runEDBPostHooks ( EDBCommit commit ) { for ( EDBPostCommitHook hook : postCommitHooks ) { try { hook . onPostCommit ( commit ) ; } catch ( ServiceUnavailableException e ) { // Ignore } catch ( Exception e ) { logger . error ( "Error while performing EDBPostCommitHook" , e ) ; } } }
Runs all registered post commit hooks on the EDBCommit object . Logs exceptions which occurs in the hooks except for ServiceUnavailableExceptions .
88
31
4,827
public boolean isLaconic ( Explanation < E > justification ) throws ExplanationException { // OBSERVATION: If a justification is laconic, then given its O+, there should be // one justification that is equal to itself. // Could optimise more here - we know that a laconic justification won't contain // equivalent classes axioms, inverse properties axioms etc. If an checker doesn't // appear in O+ then it's not laconic! Set < OWLAxiom > justificationSigmaClosure = computeOPlus ( justification . getAxioms ( ) ) ; ExplanationGenerator < E > gen2 = explanationGeneratorFactory . createExplanationGenerator ( justificationSigmaClosure ) ; Set < Explanation < E > > exps = gen2 . getExplanations ( justification . getEntailment ( ) , 2 ) ; return Collections . singleton ( justification ) . equals ( exps ) ; }
Checks to see if a justification for a given entailment is laconic .
203
17
4,828
public JPAEntry getEntry ( String entryKey ) { for ( JPAEntry entry : entries ) { if ( entry . getKey ( ) . equals ( entryKey ) ) { return entry ; } } return null ; }
Returns the entry of the JPAEntry list of this object with the given key . Returns null in case there is no such entry .
47
27
4,829
public void removeEntry ( String entryKey ) { Iterator < JPAEntry > iter = entries . iterator ( ) ; while ( iter . hasNext ( ) ) { if ( iter . next ( ) . getKey ( ) . equals ( entryKey ) ) { iter . remove ( ) ; return ; } } }
Removes the entry from the JPAEntry list of this object with the given key .
66
18
4,830
private Object getLengthOfObject ( Object object , String functionName ) throws TransformationOperationException { try { Method method = object . getClass ( ) . getMethod ( functionName ) ; return method . invoke ( object ) ; } catch ( NoSuchMethodException e ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "The type of the given field for the length step doesn't support " ) ; builder . append ( functionName ) . append ( " method. So 0 will be used as standard value." ) ; throw new TransformationOperationException ( builder . toString ( ) , e ) ; } catch ( IllegalArgumentException e ) { throw new TransformationOperationException ( "Can't get length of the source field" , e ) ; } catch ( IllegalAccessException e ) { throw new TransformationOperationException ( "Can't get length of the source field" , e ) ; } catch ( InvocationTargetException e ) { throw new TransformationOperationException ( "Can't get length of the source field" , e ) ; } }
Returns the length of the given object got through the method of the given function name
218
16
4,831
private < T > T read_ ( Class < T > clazz , Object id ) { Map < String , Object > objects = objects ( clazz ) ; return ( T ) objects . get ( id . toString ( ) ) ; }
read without clone
50
3
4,832
public void deleteSubtreeExcludingRoot ( Dn root ) throws NoSuchNodeException , MissingParentException { existsCheck ( root ) ; try { EntryCursor entryCursor = connection . search ( root , "(objectclass=*)" , SearchScope . ONELEVEL ) ; while ( entryCursor . next ( ) ) { deleteSubtreeIncludingRoot ( entryCursor . get ( ) . getDn ( ) ) ; } } catch ( Exception e ) { throw new LdapDaoException ( e ) ; } }
Deletes the entire subtree of root but not root itself . Throws NoSuchNodeException if root does not exist . Throws MissingParentException if some node above root does not exist .
114
39
4,833
public boolean exists ( Dn dn ) { try { return connection . exists ( dn ) ; } catch ( LdapException e ) { throw new LdapDaoException ( e ) ; } }
Returns true if dn exists false otherwise .
45
9
4,834
private QueryRequest createQueryRequest ( String [ ] elements ) { QueryRequest request = QueryRequest . create ( ) ; for ( String element : elements ) { String [ ] parts = StringUtils . split ( element , ":" , 2 ) ; parts [ 0 ] = parts [ 0 ] . replace ( "\\" , "\\\\" ) ; parts [ 1 ] = parts [ 1 ] . replace ( "\\" , "\\\\" ) ; request . addParameter ( parts [ 0 ] , parts [ 1 ] . substring ( 1 , parts [ 1 ] . length ( ) - 1 ) ) ; } return request ; }
Parses the previously split query string into a query request and fills the parameters of the object with the data .
131
23
4,835
public SequenceGenerator . SequenceBlock allocateBlock ( int blockSize ) { final long l = this . last ; SequenceGenerator . SequenceBlock block = new SequenceGenerator . SequenceBlock ( l + 1 , l + blockSize ) ; this . last = l + blockSize ; return block ; }
Allocate a block of sequence numbers starting from the last allocated sequence value .
62
15
4,836
public void readExternal ( PofReader reader ) throws IOException { name = reader . readString ( 0 ) ; last = reader . readLong ( 1 ) ; }
Deserialize object from the POF stream .
35
10
4,837
public void writeExternal ( PofWriter writer ) throws IOException { writer . writeString ( 0 , name ) ; writer . writeLong ( 1 , last ) ; }
Serialize object into the POF stream .
35
9
4,838
public Set < OWLClass > getRootUnsatisfiableClasses ( ) throws ExplanationException { StructuralRootDerivedReasoner srd = new StructuralRootDerivedReasoner ( manager , baseReasoner , reasonerFactory ) ; Set < OWLClass > estimatedRoots = srd . getRootUnsatisfiableClasses ( ) ; cls2JustificationMap = new HashMap < OWLClass , Set < Explanation < OWLAxiom > > > ( ) ; Set < OWLAxiom > allAxioms = new HashSet < OWLAxiom > ( ) ; for ( OWLOntology ont : baseReasoner . getRootOntology ( ) . getImportsClosure ( ) ) { allAxioms . addAll ( ont . getLogicalAxioms ( ) ) ; } for ( OWLClass cls : estimatedRoots ) { cls2JustificationMap . put ( cls , new HashSet < Explanation < OWLAxiom > > ( ) ) ; System . out . println ( "POTENTIAL ROOT: " + cls ) ; } System . out . println ( "Finding real roots from " + estimatedRoots . size ( ) + " estimated roots" ) ; int done = 0 ; roots . addAll ( estimatedRoots ) ; for ( final OWLClass estimatedRoot : estimatedRoots ) { ExplanationGeneratorFactory < OWLAxiom > genFac = ExplanationManager . createExplanationGeneratorFactory ( reasonerFactory ) ; ExplanationGenerator < OWLAxiom > gen = genFac . createExplanationGenerator ( allAxioms ) ; OWLDataFactory df = manager . getOWLDataFactory ( ) ; Set < Explanation < OWLAxiom > > expls = gen . getExplanations ( df . getOWLSubClassOfAxiom ( estimatedRoot , df . getOWLNothing ( ) ) ) ; cls2JustificationMap . get ( estimatedRoot ) . addAll ( expls ) ; done ++ ; System . out . println ( "Done " + done ) ; } for ( OWLClass clsA : estimatedRoots ) { for ( OWLClass clsB : estimatedRoots ) { if ( ! clsA . equals ( clsB ) ) { Set < Explanation < OWLAxiom >> clsAExpls = cls2JustificationMap . get ( clsA ) ; Set < Explanation < OWLAxiom > > clsBExpls = cls2JustificationMap . get ( clsB ) ; boolean clsARootForClsB = false ; boolean clsBRootForClsA = false ; // Be careful of cyclic dependencies! for ( Explanation < OWLAxiom > clsAExpl : clsAExpls ) { for ( Explanation < OWLAxiom > clsBExpl : clsBExpls ) { if ( isRootFor ( clsAExpl , clsBExpl ) ) { // A is a root of B clsARootForClsB = true ; // System.out.println(clsB + " --- depends ---> " + clsA); } else if ( isRootFor ( clsBExpl , clsAExpl ) ) { // B is a root of A clsBRootForClsA = true ; // System.out.println(clsA + " --- depends ---> " + clsB); } } } if ( ! clsARootForClsB || ! clsBRootForClsA ) { if ( clsARootForClsB ) { roots . remove ( clsB ) ; } else if ( clsBRootForClsA ) { roots . remove ( clsA ) ; } } } } } return roots ; }
Gets the root unsatisfiable classes .
832
8
4,839
public static Connection getConnection ( final String jndiName ) throws FactoryException { Validate . notBlank ( jndiName , "The validated character sequence 'jndiName' is null or empty" ) ; // no need for defensive copies of Strings try { return DataSourceFactory . getDataSource ( jndiName ) . getConnection ( ) ; } catch ( SQLException e ) { final String error = "Error retrieving JDBC connection from JNDI: " + jndiName ; LOG . warn ( error ) ; throw new FactoryException ( error , e ) ; } }
Return a Connection instance for a JNDI managed JDBC connection .
129
14
4,840
public static QueryRequest query ( String key , Object value ) { return QueryRequest . create ( ) . addParameter ( key , value ) ; }
Creates a new QueryRequest object and adds the given first parameter .
30
14
4,841
public QueryRequest addParameter ( String key , Object value ) { if ( parameters . get ( key ) == null ) { parameters . put ( key , Sets . newHashSet ( value ) ) ; } else { parameters . get ( key ) . add ( value ) ; } return this ; }
Adds a parameter to this request .
61
7
4,842
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private Predicate [ ] analyzeParamMap ( CriteriaBuilder criteriaBuilder , Root from , Map < String , Object > param ) { List < Predicate > predicates = new ArrayList < Predicate > ( ) ; for ( Map . Entry < String , Object > entry : param . entrySet ( ) ) { String key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( key . equals ( "timestamp" ) ) { predicates . add ( criteriaBuilder . le ( from . get ( "timestamp" ) , ( Long ) value ) ) ; } else if ( key . equals ( "committer" ) ) { predicates . add ( criteriaBuilder . equal ( from . get ( "committer" ) , value ) ) ; } else if ( key . equals ( "context" ) ) { predicates . add ( criteriaBuilder . equal ( from . get ( "context" ) , value ) ) ; } } Predicate [ ] temp = new Predicate [ predicates . size ( ) ] ; for ( int i = 0 ; i < predicates . size ( ) ; i ++ ) { temp [ i ] = predicates . get ( i ) ; } return temp ; }
Analyzes the map and filters the values which are used for query
278
13
4,843
private void batchImport ( ) { m_jdbcTemplate . batchUpdate ( createInsertQuery ( ) , new BatchPreparedStatementSetter ( ) { public void setValues ( PreparedStatement ps , int i ) throws SQLException { int j = 1 ; for ( String property : m_propertyNames ) { Map params = ( Map ) m_batch . get ( i ) ; ps . setObject ( j ++ , params . get ( property ) ) ; } } public int getBatchSize ( ) { return m_batch . size ( ) ; } } ) ; }
Perform batch import into database .
125
7
4,844
private String createInsertQuery ( ) { StringBuilder query = new StringBuilder ( ) ; query . append ( "insert into " ) . append ( m_tableName ) . append ( "(" ) . append ( m_propertyNames [ 0 ] ) ; for ( int i = 1 ; i < m_propertyNames . length ; i ++ ) { query . append ( "," ) . append ( m_propertyNames [ i ] ) ; } query . append ( ") values (?" ) ; for ( int i = 1 ; i < m_propertyNames . length ; i ++ ) { query . append ( ",?" ) ; } query . append ( ")" ) ; return query . toString ( ) ; }
Construct insert query using property names and database table name .
150
11
4,845
public static < T extends Annotation > Method findMethodWithAnnotation ( Class < ? > clazz , Class < T > annotationType ) { Method annotatedMethod = null ; for ( Method method : clazz . getDeclaredMethods ( ) ) { T annotation = AnnotationUtils . findAnnotation ( method , annotationType ) ; if ( annotation != null ) { if ( annotatedMethod != null ) { throw new BeanCreationException ( "Only ONE method with @" + annotationType . getName ( ) + " is allowed on " + clazz . getName ( ) + "." ) ; } annotatedMethod = method ; } } if ( ( annotatedMethod != null ) || clazz . equals ( Object . class ) ) { return annotatedMethod ; } else { return findMethodWithAnnotation ( clazz . getSuperclass ( ) , annotationType ) ; } }
Finds a method annotated with the specified annotation . This method can be defined in the specified class or one of its parents .
188
26
4,846
public static Object invokeMethod ( Object object , Method method , Object ... args ) throws Throwable { try { return method . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } }
Invokes the method of the specified object with some method arguments .
53
13
4,847
public static void validateReturnType ( Method method , Class < ? extends Annotation > annotationType , Class < ? > expectedReturnType ) { if ( ! method . getReturnType ( ) . equals ( expectedReturnType ) ) { throw new BeanCreationException ( "Method " + method . getName ( ) + " annotated with @" + annotationType . getName ( ) + " must have a return type of " + expectedReturnType . getName ( ) ) ; } }
Validates that the method annotated with the specified annotation returns the expected type .
102
16
4,848
public static void validateArgument ( Method method , Class < ? extends Annotation > annotationType , Class < ? > expectedParameterType ) { if ( method . getParameterTypes ( ) . length != 1 || ! method . getParameterTypes ( ) [ 0 ] . equals ( expectedParameterType ) ) { throw new BeanCreationException ( String . format ( "Method %s with @%s MUST take a single argument of type %s" , method , annotationType . getName ( ) , expectedParameterType . getName ( ) ) ) ; } }
Validates that the method annotated with the specified annotation has a single argument of the expected type .
116
20
4,849
protected Object getValue ( ) { Object value = this . value ; if ( value == null ) { this . value = value = fromBinary ( "value" ) ; } return value ; }
Return deserialized value .
41
6
4,850
public CuratorFramework newCurator ( ) { // Make all of the curator threads daemon threads so they don't block the JVM from terminating. Also label them // with the ensemble they're connecting to, in case someone is trying to sort through a thread dump. ThreadFactory threadFactory = new ThreadFactoryBuilder ( ) . setNameFormat ( "CuratorFramework[" + _connectString . orElse ( DEFAULT_CONNECT_STRING ) + "]-%d" ) . setDaemon ( true ) . build ( ) ; org . apache . curator . RetryPolicy retry = _setterRetryPolicy . orElse ( ( _configRetryPolicy != null ) ? _configRetryPolicy : DEFAULT_RETRY_POLICY ) ; return CuratorFrameworkFactory . builder ( ) . ensembleProvider ( new ResolvingEnsembleProvider ( _connectString . orElse ( DEFAULT_CONNECT_STRING ) ) ) . retryPolicy ( retry ) . sessionTimeoutMs ( Ints . checkedCast ( _sessionTimeout . toMilliseconds ( ) ) ) . connectionTimeoutMs ( Ints . checkedCast ( _connectionTimeout . toMilliseconds ( ) ) ) . namespace ( _namespace . orElse ( null ) ) . threadFactory ( threadFactory ) . build ( ) ; }
Return a new Curator connection to the ensemble . It is the caller s responsibility to start and close the connection .
282
23
4,851
public static Class < ? > getTypeArgument ( Class < ? > clazz , Class < ? > interfce ) { Map < Type , Type > resolvedTypes = new HashMap < Type , Type > ( ) ; Type type = clazz ; while ( ! declaresInterface ( getClass ( type ) , interfce ) ) { if ( type instanceof Class ) { type = ( ( Class < ? > ) type ) . getGenericSuperclass ( ) ; } else { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Class < ? > rawType = ( Class < ? > ) parameterizedType . getRawType ( ) ; Type [ ] actualTypeArguments = parameterizedType . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] typeParameters = rawType . getTypeParameters ( ) ; for ( int i = 0 ; i < actualTypeArguments . length ; i ++ ) { resolvedTypes . put ( typeParameters [ i ] , actualTypeArguments [ i ] ) ; } type = rawType . getGenericSuperclass ( ) ; } } Type actualTypeArgument ; if ( type instanceof Class ) { actualTypeArgument = ( ( Class < ? > ) type ) . getTypeParameters ( ) [ 0 ] ; } else { actualTypeArgument = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } Class < ? > typeArgumentAsClass = null ; while ( resolvedTypes . containsKey ( actualTypeArgument ) ) { actualTypeArgument = resolvedTypes . get ( actualTypeArgument ) ; } typeArgumentAsClass = getClass ( actualTypeArgument ) ; return typeArgumentAsClass ; }
Get the actual type argument for a interface with one type
369
11
4,852
public static List < Entry > assignmentStructure ( Assignment assignment ) { List < Entry > entryList = new LinkedList <> ( ) ; entryList . add ( namedObject ( DnFactory . assignment ( assignment ) ) ) ; entryList . add ( namedDescriptiveObject ( DnFactory . assignmentProject ( assignment ) , assignment . getProject ( ) ) ) ; entryList . add ( namedDescriptiveObject ( DnFactory . assignmentUser ( assignment ) , assignment . getUser ( ) ) ) ; entryList . addAll ( createAssignmentPermissionsEntries ( assignment ) ) ; entryList . addAll ( createAssignmentRolesEntries ( assignment ) ) ; return entryList ; }
Returns a list of entries representing an assignment . The list should not be reordered since its order follows the tree structure of the DIT . It can be inserted into the DIT right away .
150
39
4,853
public static List < Entry > permissionStructure ( Permission permission ) { List < Entry > entryList = new LinkedList <> ( ) ; entryList . add ( namedObject ( DnFactory . permission ( permission ) ) ) ; entryList . add ( namedDescriptiveObject ( DnFactory . permissionAction ( permission ) , permission . getAction ( ) ) ) ; entryList . add ( namedDescriptiveObject ( DnFactory . permissionComponent ( permission ) , permission . getComponentName ( ) ) ) ; return entryList ; }
Returns a list of entries representing a permission . The list should not be reordered since its order follows the tree structure of the DIT . It can be inserted into the DIT right away .
116
39
4,854
public static List < Entry > projectStructure ( Project project ) { List < Entry > entryList = new LinkedList <> ( ) ; entryList . add ( namedObject ( DnFactory . project ( project ) ) ) ; entryList . addAll ( createProjectAttributesEntries ( project ) ) ; return entryList ; }
Returns a list of entries representing a project . The list should not be reordered since its order follows the tree structure of the DIT . It can be inserted into the DIT right away .
70
39
4,855
public static List < Entry > roleStructure ( Role role ) { List < Entry > entryList = new LinkedList <> ( ) ; entryList . add ( namedObject ( DnFactory . role ( role ) ) ) ; entryList . addAll ( createRolePermissionsEntries ( role ) ) ; entryList . addAll ( createRoleSubrolesEntries ( role ) ) ; return entryList ; }
Returns a list of entries representing a role . The list should not be reordered since its order follows the tree structure of the DIT . It can be inserted into the DIT right away .
89
39
4,856
public BufferedImage getBufferedImage ( int width , int height ) { BufferedImage bi = chart . createBufferedImage ( width , height ) ; return bi ; }
Get a buffered image of this chart
37
8
4,857
private CategoryDataset createDataset ( ) { DefaultCategoryDataset dataset = new DefaultCategoryDataset ( ) ; startTimes = new Long [ stl . getPulses ( ) . length + 1 ] ; startTimes [ 0 ] = new Long ( 0 ) ; for ( int i = 1 ; i < startTimes . length ; i ++ ) { startTimes [ i ] = stl . getPulses ( ) [ i - 1 ] ; } durations = new Long [ stl . getDurations ( ) . length + 1 ] ; durations [ 0 ] = new Long ( 0 ) ; for ( int i = 1 ; i < durations . length ; i ++ ) { durations [ i ] = stl . getDurations ( ) [ i - 1 ] ; } values = new Object [ stl . getValues ( ) . length + 1 ] ; values [ 0 ] = null ; for ( int i = 1 ; i < values . length ; i ++ ) { values [ i ] = stl . getValues ( ) [ i - 1 ] ; } for ( int i = 0 ; i < durations . length ; i ++ ) { //Dbg.printMsg("dur" + i + ": " + durations.elementAt(i), LogLvl.Normal); //dataset.addValue((long)durations.elementAt(i), i+"", stateVar.getName()); dataset . addValue ( ( long ) durations [ i ] , i + "" , "" ) ; } return dataset ; }
Creates a dataset from the bsv vector .
336
10
4,858
public static String extractAttributeEmptyCheck ( Entry entry , String attributeType ) { Attribute attribute = entry . get ( attributeType ) ; Attribute emptyFlagAttribute = entry . get ( SchemaConstants . EMPTY_FLAG_ATTRIBUTE ) ; boolean empty = false ; try { if ( attribute != null ) { return attribute . getString ( ) ; } else if ( emptyFlagAttribute != null ) { empty = Boolean . valueOf ( emptyFlagAttribute . getString ( ) ) ; } } catch ( LdapInvalidAttributeValueException e ) { throw new ObjectClassViolationException ( e ) ; } return empty ? new String ( ) : null ; }
Returns the value of the first occurence of attributeType from entry .
141
15
4,859
public static List < String > extractAttributeEmptyCheck ( List < Entry > entries , String attributeType ) { List < String > result = new LinkedList < String > ( ) ; for ( Entry e : entries ) { result . add ( extractAttributeEmptyCheck ( e , attributeType ) ) ; } return result ; }
Returns the value of the first occurence of attributeType from each entry .
67
16
4,860
public static List < String > extractAttributeEmptyCheck ( SearchCursor cursor , String attributeType ) { List < String > result = new LinkedList < String > ( ) ; try { while ( cursor . next ( ) ) { Entry entry = cursor . getEntry ( ) ; result . add ( extractAttributeEmptyCheck ( entry , attributeType ) ) ; } } catch ( Exception e ) { throw new LdapRuntimeException ( e ) ; } return result ; }
Returns the value of the first occurence of attributeType from each entry in the cursor .
98
19
4,861
private void createObjectDiffs ( ) throws EDBException { diff = new HashMap < String , EDBObjectDiff > ( ) ; List < EDBObject > tempList = new ArrayList < EDBObject > ( ) ; for ( EDBObject o : this . endState ) { tempList . add ( o ) ; } addModifiedOrDeletedObjects ( tempList ) ; addNewObjects ( tempList ) ; }
Analyzes the start and end state and creates for every object that is different an objectdiff entry
94
19
4,862
private void addModifiedOrDeletedObjects ( List < EDBObject > tempList ) { for ( EDBObject a : this . startState ) { String oid = a . getOID ( ) ; EDBObject b = removeIfExist ( oid , tempList ) ; ObjectDiff odiff = new ObjectDiff ( this . startCommit , this . endCommit , a , b ) ; if ( odiff . getDifferenceCount ( ) > 0 ) { diff . put ( oid , odiff ) ; } } }
add all modified or deleted objects to the diff collection . As base to indicate if something changed the start state and the list of elements from the end state is taken .
118
33
4,863
private void addNewObjects ( List < EDBObject > tempList ) { for ( EDBObject b : tempList ) { String oid = b . getOID ( ) ; ObjectDiff odiff = new ObjectDiff ( this . startCommit , this . endCommit , null , b ) ; if ( odiff . getDifferenceCount ( ) > 0 ) { diff . put ( oid , odiff ) ; } } }
add all new object to the diff collection . As base to indicate if an object is new the list of elements from the end state which are left is taken .
95
32
4,864
private EDBObject removeIfExist ( String oid , List < EDBObject > tempList ) { Iterator < EDBObject > iterator = tempList . iterator ( ) ; while ( iterator . hasNext ( ) ) { EDBObject obj = iterator . next ( ) ; if ( obj . getOID ( ) . equals ( oid ) ) { iterator . remove ( ) ; return obj ; } } LOGGER . debug ( oid + " wasn't found in the list of end state objects" ) ; return null ; }
Removes the element with the given oid if it exists in the list and returns it . If it not exists null will be returned .
114
28
4,865
private boolean compareRelation ( RCCConstraint first , RCCConstraint second ) { boolean existed = false ; for ( int i = 0 ; i < first . types . length ; i ++ ) { existed = false ; for ( int j = 0 ; j < second . types . length ; j ++ ) { if ( first . types [ i ] == second . types [ j ] ) existed = true ; } if ( ! existed ) return false ; } return true ; }
return true when they are equal
102
6
4,866
private void runPersistingLogic ( EKBCommit commit , boolean check , UUID expectedContextHeadRevision , boolean headRevisionCheck ) throws SanityCheckException , EKBException { String contextId = ContextHolder . get ( ) . getCurrentContextId ( ) ; try { lockContext ( contextId ) ; if ( headRevisionCheck ) { checkForContextHeadRevision ( contextId , expectedContextHeadRevision ) ; } runEKBPreCommitHooks ( commit ) ; if ( check ) { performSanityChecks ( commit ) ; } EKBException exception = null ; ConvertedCommit converted = edbConverter . convertEKBCommit ( commit ) ; try { performPersisting ( converted , commit ) ; runEKBPostCommitHooks ( commit ) ; } catch ( EKBException e ) { exception = e ; } runEKBErrorHooks ( commit , exception ) ; } finally { releaseContext ( contextId ) ; } }
Runs the logic of the PersistInterface . Does the sanity checks if check is set to true . Additionally tests if the head revision of the context under which the commit is performed has the given revision number if the headRevisionCheck flag is set to true .
212
53
4,867
private void performRevertLogic ( String revision , UUID expectedContextHeadRevision , boolean expectedHeadCheck ) { String contextId = "" ; try { EDBCommit commit = edbService . getCommitByRevision ( revision ) ; contextId = commit . getContextId ( ) ; lockContext ( contextId ) ; if ( expectedHeadCheck ) { checkForContextHeadRevision ( contextId , expectedContextHeadRevision ) ; } EDBCommit newCommit = edbService . createEDBCommit ( new ArrayList < EDBObject > ( ) , new ArrayList < EDBObject > ( ) , new ArrayList < EDBObject > ( ) ) ; for ( EDBObject reverted : commit . getObjects ( ) ) { // need to be done in order to avoid problems with conflict detection reverted . remove ( EDBConstants . MODEL_VERSION ) ; newCommit . update ( reverted ) ; } for ( String delete : commit . getDeletions ( ) ) { newCommit . delete ( delete ) ; } newCommit . setComment ( String . format ( "revert [%s] %s" , commit . getRevisionNumber ( ) . toString ( ) , commit . getComment ( ) != null ? commit . getComment ( ) : "" ) ) ; edbService . commit ( newCommit ) ; } catch ( EDBException e ) { throw new EKBException ( "Unable to revert to the given revision " + revision , e ) ; } finally { releaseContext ( contextId ) ; } }
Performs the actual revert logic including the context locking and the context head revision check if desired .
339
19
4,868
private void lockContext ( String contextId ) throws EKBConcurrentException { if ( mode == ContextLockingMode . DEACTIVATED ) { return ; } synchronized ( activeWritingContexts ) { if ( activeWritingContexts . contains ( contextId ) ) { throw new EKBConcurrentException ( "There is already a writing process active in the context." ) ; } activeWritingContexts . add ( contextId ) ; } }
If the context locking mode is activated this method locks the given context for writing operations . If this context is already locked an EKBConcurrentException is thrown .
94
33
4,869
private void checkForContextHeadRevision ( String contextId , UUID expectedHeadRevision ) throws EKBConcurrentException { if ( ! Objects . equal ( edbService . getLastRevisionNumberOfContext ( contextId ) , expectedHeadRevision ) ) { throw new EKBConcurrentException ( "The current revision of the context does not match the " + "expected one." ) ; } }
Tests if the head revision for the given context matches the given revision number . If this is not the case an EKBConcurrentException is thrown .
88
32
4,870
private void releaseContext ( String contextId ) { if ( mode == ContextLockingMode . DEACTIVATED ) { return ; } synchronized ( activeWritingContexts ) { activeWritingContexts . remove ( contextId ) ; } }
If the context locking mode is activated this method releases the lock for the given context for writing operations .
49
20
4,871
private void runEKBPreCommitHooks ( EKBCommit commit ) throws EKBException { for ( EKBPreCommitHook hook : preCommitHooks ) { try { hook . onPreCommit ( commit ) ; } catch ( EKBException e ) { throw new EKBException ( "EDBException is thrown in a pre commit hook." , e ) ; } catch ( Exception e ) { LOGGER . warn ( "An exception is thrown in a EKB pre commit hook." , e ) ; } } }
Runs all registered pre - commit hooks
116
8
4,872
private void runEKBPostCommitHooks ( EKBCommit commit ) throws EKBException { for ( EKBPostCommitHook hook : postCommitHooks ) { try { hook . onPostCommit ( commit ) ; } catch ( Exception e ) { LOGGER . warn ( "An exception is thrown in a EKB post commit hook." , e ) ; } } }
Runs all registered post - commit hooks
85
8
4,873
private void runEKBErrorHooks ( EKBCommit commit , EKBException exception ) { if ( exception != null ) { for ( EKBErrorHook hook : errorHooks ) { hook . onError ( commit , exception ) ; } throw exception ; } }
Runs all registered error hooks
59
6
4,874
private void performPersisting ( ConvertedCommit commit , EKBCommit source ) throws EKBException { try { EDBCommit ci = edbService . createEDBCommit ( commit . getInserts ( ) , commit . getUpdates ( ) , commit . getDeletes ( ) ) ; ci . setDomainId ( source . getDomainId ( ) ) ; ci . setConnectorId ( source . getConnectorId ( ) ) ; ci . setInstanceId ( source . getInstanceId ( ) ) ; ci . setComment ( source . getComment ( ) ) ; edbService . commit ( ci ) ; source . setRevisionNumber ( ci . getRevisionNumber ( ) ) ; source . setParentRevisionNumber ( ci . getParentRevisionNumber ( ) ) ; } catch ( EDBCheckException e ) { throw new ModelPersistException ( convertEDBObjectList ( e . getFailedInserts ( ) ) , convertEDBObjectList ( e . getFailedUpdates ( ) ) , e . getFailedDeletes ( ) , e ) ; } catch ( EDBException e ) { throw new EKBException ( "Error while commiting EKBCommit" , e ) ; } }
Performs the persisting of the models into the EDB .
274
13
4,875
private List < String > convertEDBObjectList ( List < EDBObject > objects ) { List < String > oids = new ArrayList <> ( ) ; for ( EDBObject object : objects ) { oids . add ( object . getOID ( ) ) ; } return oids ; }
Converts a list of EDBObject instances into a list of corresponding model oids .
65
18
4,876
private Set < ModelDescription > scanBundleForModels ( Bundle bundle ) { Set < ModelDescription > models = new HashSet < ModelDescription > ( ) ; if ( ! shouldSkipBundle ( bundle ) ) { models = loadModelsOfBundle ( bundle ) ; } return models ; }
Check all found classes of the bundle if they are models and return a set of all found model descriptions .
63
21
4,877
private Set < ModelDescription > loadModelsOfBundle ( Bundle bundle ) { Enumeration < URL > classEntries = bundle . findEntries ( "/" , "*.class" , true ) ; Set < ModelDescription > models = new HashSet < ModelDescription > ( ) ; if ( classEntries == null ) { LOGGER . debug ( "Found no classes in the bundle {}" , bundle ) ; return models ; } while ( classEntries . hasMoreElements ( ) ) { URL classURL = classEntries . nextElement ( ) ; String classname = extractClassName ( classURL ) ; if ( isModelClass ( classname , bundle ) ) { models . add ( new ModelDescription ( classname , bundle . getVersion ( ) . toString ( ) ) ) ; } } return models ; }
Searches the bundle for model classes and return a set of them .
175
15
4,878
private boolean isModelClass ( String classname , Bundle bundle ) { LOGGER . debug ( "Check if class '{}' is a model class" , classname ) ; Class < ? > clazz ; try { clazz = bundle . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { LOGGER . warn ( "Bundle could not load its own class: '{}' bundle: '{}'" , classname , bundle . getSymbolicName ( ) ) ; LOGGER . debug ( "Exact error: " , e ) ; return false ; } catch ( NoClassDefFoundError e ) { // ignore since this happens if bundle have optional imports return false ; } catch ( Error e ) { // if this catch clause is reached, then the bundle which caused this error need to be checked. There // is something wrong with the setup of the bundle (e.g. double import of a library of different versions) LOGGER . warn ( "Error while loading class: '{}' in bundle: '{}'" , classname , bundle . getSymbolicName ( ) ) ; LOGGER . debug ( "Exact error: " , e ) ; return false ; } return clazz . isAnnotationPresent ( Model . class ) ; }
Returns true if the class with the given class name contained in the given bundle is a model and false if not or the class couldn t be loaded .
273
30
4,879
private String extractClassName ( URL classURL ) { String path = classURL . getPath ( ) ; return path . replaceAll ( "^/" , "" ) . replaceAll ( ".class$" , "" ) . replaceAll ( "\\/" , "." ) ; }
Converts an URL to a class into a class name
58
11
4,880
public List < User > findAllUsers ( ) { List < User > list = new ArrayList <> ( ) ; List < String > usernames ; try { usernames = readLines ( usersFile ) ; } catch ( IOException e ) { throw new FileBasedRuntimeException ( e ) ; } for ( String username : usernames ) { if ( StringUtils . isNotBlank ( username ) ) { list . add ( new User ( username ) ) ; } } return list ; }
Finds all the available users .
108
7
4,881
private int rightmostIndexBelowMax ( ) { for ( int i = r - 1 ; i >= 0 ; i -- ) if ( index [ i ] < n - r + i ) return i ; return - 1 ; }
return int the index which can be bumped up .
47
10
4,882
public static void setLevel ( Level l ) { for ( Logger log : loggers . values ( ) ) log . setLevel ( l ) ; globalLevel = l ; }
Set a desired log level for all loggers .
37
10
4,883
public static void setLevel ( Class < ? > c , Level l ) /* throws LoggerNotDefined */ { if ( ! loggers . containsKey ( c ) ) tempLevels . put ( c , l ) ; else loggers . get ( c ) . setLevel ( l ) ; //System.out.println("Set level " + l + " for logger " + loggers.get(c).getName()); }
Set a desired log level for a specific class .
91
10
4,884
public void setImage ( BufferedImage im ) { icon . setImage ( im ) ; if ( image == null ) { this . image = im ; // this.setSize(image.getWidth(), image.getHeight()); int panelX = image . getWidth ( ) ; int panelY = image . getHeight ( ) ; panel . setSize ( panelX , panelY ) ; // Toolkit tk = Toolkit.getDefaultToolkit(); // int xSize = ((int) tk.getScreenSize().getWidth()); // int ySize = ((int) tk.getScreenSize().getHeight()); try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( ClassNotFoundException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } catch ( InstantiationException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } catch ( IllegalAccessException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } catch ( UnsupportedLookAndFeelException e ) { // TODO Auto-generated catch block e . printStackTrace ( ) ; } GraphicsEnvironment ge = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; Rectangle bounds = ge . getMaximumWindowBounds ( ) ; int deltaX = 30 ; int deltaY = 50 ; int xSize = Math . min ( bounds . width , panelX + deltaX ) ; int ySize = Math . min ( bounds . height , panelY + deltaY ) ; this . setPreferredSize ( new Dimension ( xSize , ySize ) ) ; this . setResizable ( true ) ; this . pack ( ) ; } this . getContentPane ( ) . repaint ( ) ; if ( ! this . isVisible ( ) ) this . setVisible ( true ) ; }
Force the visualizer to display a given image .
416
10
4,885
public List < Assignment > findAllAssignments ( ) { List < Assignment > list = new ArrayList <> ( ) ; List < String > assignmentStrings ; try { assignmentStrings = readLines ( assignmentsFile ) ; } catch ( IOException e ) { throw new FileBasedRuntimeException ( e ) ; } for ( String assignmentString : assignmentStrings ) { if ( StringUtils . isNotBlank ( assignmentString ) ) { String [ ] substrings = StringUtils . splitByWholeSeparator ( assignmentString , Configuration . get ( ) . getAssociationSeparator ( ) ) ; if ( substrings . length < 2 || StringUtils . isBlank ( substrings [ 1 ] ) ) { continue ; } Assignment assignment = new Assignment ( substrings [ 0 ] , substrings [ 1 ] ) ; if ( substrings . length > 2 ) { assignment . setRoles ( Arrays . asList ( StringUtils . splitByWholeSeparator ( substrings [ 2 ] , Configuration . get ( ) . getValueSeparator ( ) ) ) ) ; } list . add ( assignment ) ; } } return list ; }
Finds all the available assignments .
250
7
4,886
private static void logValue ( final String key , final String value ) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, the configuration keys are not confidential, which makes this a non-issue / false positive. if ( LOG . isInfoEnabled ( ) ) { final StringBuilder msg = new StringBuilder ( "Key found in configuration ('" ) . append ( key ) . append ( "'), using configured value (not disclosed here for security reasons)" ) ; LOG . info ( msg . toString ( ) ) ; } // Fortify will report a violation here because of disclosure of potentially confidential information. // The configuration VALUES are confidential. DO NOT activate DEBUG logging in production. if ( LOG . isDebugEnabled ( ) ) { final StringBuilder msg = new StringBuilder ( "Key found in configuration ('" ) . append ( key ) . append ( "'), using configured value ('" ) ; if ( value == null ) { msg . append ( "null')" ) ; } else { msg . append ( value ) . append ( "')" ) ; } LOG . debug ( msg . toString ( ) ) ; } }
Create a log entry when a value has been successfully configured .
242
12
4,887
private static void logDefault ( final String key , final String defaultValue ) { // Fortify will report a violation here because of disclosure of potentially confidential information. // However, neither the configuration keys nor the default propsbuilder values are confidential, which makes // this a non-issue / false positive. if ( LOG . isInfoEnabled ( ) ) { final StringBuilder msg = new StringBuilder ( "Key is not configured ('" ) . append ( key ) . append ( "'), using default value ('" ) ; if ( defaultValue == null ) { msg . append ( "null')" ) ; } else { msg . append ( defaultValue ) . append ( "')" ) ; } LOG . info ( msg . toString ( ) ) ; } }
Create a log entry when a default value is being used in case the propsbuilder key has not been provided in the configuration .
156
25
4,888
@ SuppressWarnings ( { "PMD.UseObjectForClearerAPI" } ) // CHECKSTYLE:ON private static void logDefault ( final String key , final String invalidValue , final String validationError , final String defaultValue ) { if ( LOG . isWarnEnabled ( ) ) { final StringBuilder msg = new StringBuilder ( "Invalid value ('" ) . append ( invalidValue ) . append ( "', " ) . append ( validationError ) . append ( ") for key '" ) . append ( key ) . append ( "', using default instead ('" ) ; if ( defaultValue == null ) { msg . append ( "null')" ) ; } else { msg . append ( defaultValue ) . append ( "')" ) ; } LOG . warn ( msg . toString ( ) ) ; } }
suppress warnings about not using an object for the four strings in this PRIVATE method
179
18
4,889
public int getSequenceNumber ( Coordinate coord ) { int minIndex = 0 ; double minDist = Double . MAX_VALUE ; for ( int i = 0 ; i < this . getPositions ( ) . length ; i ++ ) { if ( this . getPositions ( ) [ i ] . distance ( coord ) < minDist ) { minDist = this . getPositions ( ) [ i ] . distance ( coord ) ; minIndex = i ; } } return minIndex ; }
Get the sequence number of the path point that is closest to a given coordinate .
104
16
4,890
private void enhanceEKBCommit ( EKBCommit commit ) throws EKBException { LOGGER . debug ( "Started to enhance the EKBCommit with Engineering Object information" ) ; enhanceCommitInserts ( commit ) ; enhanceCommitUpdates ( commit ) ; // TODO: OPENENGSB-3357, consider also deletions in the enhancement LOGGER . debug ( "Finished EKBCommit enhancing" ) ; }
Does the Engineering Object enhancement of the EKBCommit object . In this step there may be some inserts updated or new objects will be added to the updates of the EKBCommit object . Throws an EKBException if an error in the Engineering Object logic occurs .
99
57
4,891
private void enhanceCommitUpdates ( EKBCommit commit ) throws EKBException { Map < Object , AdvancedModelWrapper > updated = new HashMap < Object , AdvancedModelWrapper > ( ) ; List < AdvancedModelWrapper > result = recursiveUpdateEnhancement ( convertOpenEngSBModelList ( commit . getUpdates ( ) ) , updated , commit ) ; commit . getUpdates ( ) . addAll ( convertSimpleModelWrapperList ( result ) ) ; }
Enhances the EKBCommit for the updates of EngineeringObjects .
104
16
4,892
private List < AdvancedModelWrapper > convertOpenEngSBModelList ( List < OpenEngSBModel > models ) { List < AdvancedModelWrapper > wrappers = new ArrayList < AdvancedModelWrapper > ( ) ; for ( OpenEngSBModel model : models ) { wrappers . add ( AdvancedModelWrapper . wrap ( model ) ) ; } return wrappers ; }
Converts a list of OpenEngSBModel objects to a list of SimpleModelWrapper objects
80
19
4,893
private List < OpenEngSBModel > convertSimpleModelWrapperList ( List < AdvancedModelWrapper > wrappers ) { List < OpenEngSBModel > models = new ArrayList < OpenEngSBModel > ( ) ; for ( AdvancedModelWrapper wrapper : wrappers ) { models . add ( wrapper . getUnderlyingModel ( ) ) ; } return models ; }
Converts a list of SimpleModelWrapper objects to a list of OpenEngSBModel objects
78
19
4,894
private List < AdvancedModelWrapper > recursiveUpdateEnhancement ( List < AdvancedModelWrapper > updates , Map < Object , AdvancedModelWrapper > updated , EKBCommit commit ) { List < AdvancedModelWrapper > additionalUpdates = enhanceUpdates ( updates , updated , commit ) ; for ( AdvancedModelWrapper model : updates ) { updated . put ( model . getCompleteModelOID ( ) , model ) ; } if ( ! additionalUpdates . isEmpty ( ) ) { additionalUpdates . addAll ( recursiveUpdateEnhancement ( additionalUpdates , updated , commit ) ) ; } return additionalUpdates ; }
Recursive function for calculating all models which need to be updated due to the original updates of the EKBCommit .
136
25
4,895
private List < AdvancedModelWrapper > enhanceUpdates ( List < AdvancedModelWrapper > updates , Map < Object , AdvancedModelWrapper > updated , EKBCommit commit ) { List < AdvancedModelWrapper > additionalUpdates = new ArrayList < AdvancedModelWrapper > ( ) ; for ( AdvancedModelWrapper model : updates ) { if ( updated . containsKey ( model . getCompleteModelOID ( ) ) ) { continue ; // this model was already updated in this commit } if ( model . isEngineeringObject ( ) ) { additionalUpdates . addAll ( performEOModelUpdate ( model . toEngineeringObject ( ) , commit ) ) ; } additionalUpdates . addAll ( getReferenceBasedUpdates ( model , updated , commit ) ) ; } return additionalUpdates ; }
Enhances the given list of updates and returns a list of models which need to be additionally updated .
173
20
4,896
private List < AdvancedModelWrapper > performEOModelUpdate ( EngineeringObjectModelWrapper model , EKBCommit commit ) { ModelDiff diff = createModelDiff ( model . getUnderlyingModel ( ) , model . getCompleteModelOID ( ) , edbService , edbConverter ) ; boolean referencesChanged = diff . isForeignKeyChanged ( ) ; boolean valuesChanged = diff . isValueChanged ( ) ; // TODO: OPENENGSB-3358, Make it possible to change references and values at the same time. Should be // no too big deal since we already know at this point which values of the model have been changed and // what the old and the new value for the changed properties are if ( referencesChanged && valuesChanged ) { throw new EKBException ( "Engineering Objects may be updated only at " + "references or at values not both in the same commit" ) ; } if ( referencesChanged ) { reloadReferencesAndUpdateEO ( diff , model ) ; } else { return updateReferencedModelsByEO ( model ) ; } return new ArrayList < AdvancedModelWrapper > ( ) ; }
Runs the logic of updating an Engineering Object model . Returns a list of models which need to be updated additionally .
244
23
4,897
private List < AdvancedModelWrapper > updateReferencedModelsByEO ( EngineeringObjectModelWrapper model ) { List < AdvancedModelWrapper > updates = new ArrayList < AdvancedModelWrapper > ( ) ; for ( Field field : model . getForeignKeyFields ( ) ) { try { AdvancedModelWrapper result = performMerge ( model , loadReferencedModel ( model , field ) ) ; if ( result != null ) { updates . add ( result ) ; } } catch ( EDBException e ) { LOGGER . debug ( "Skipped referenced model for field {}, since it does not exist." , field , e ) ; } } return updates ; }
Updates all models which are referenced by the given engineering object .
144
13
4,898
private void reloadReferencesAndUpdateEO ( ModelDiff diff , EngineeringObjectModelWrapper model ) { for ( ModelDiffEntry entry : diff . getDifferences ( ) . values ( ) ) { mergeEngineeringObjectWithReferencedModel ( entry . getField ( ) , model ) ; } }
Reload the references which have changed in the actual update and update the Engineering Object accordingly .
62
18
4,899
private List < AdvancedModelWrapper > getReferenceBasedUpdates ( AdvancedModelWrapper model , Map < Object , AdvancedModelWrapper > updated , EKBCommit commit ) throws EKBException { List < AdvancedModelWrapper > updates = new ArrayList < AdvancedModelWrapper > ( ) ; List < EDBObject > references = model . getModelsReferringToThisModel ( edbService ) ; for ( EDBObject reference : references ) { EDBModelObject modelReference = new EDBModelObject ( reference , modelRegistry , edbConverter ) ; AdvancedModelWrapper ref = updateEOByUpdatedModel ( modelReference , model , updated ) ; if ( ! updated . containsKey ( ref . getCompleteModelOID ( ) ) ) { updates . add ( ref ) ; } } return updates ; }
Returns engineering objects to the commit which are changed by a model which was committed in the EKBCommit
177
22