idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
33,300 | static Set < String > validatePlaysAndRelatesStructure ( Casting casting ) { Set < String > errors = new HashSet < > ( ) ; Thing thing = casting . getRolePlayer ( ) ; Role role = casting . getRole ( ) ; Relation relation = casting . getRelation ( ) ; roleNotAllowedToBePlayed ( role , thing ) . ifPresent ( errors :: add ) ; roleNotLinkedToRelation ( role , relation . type ( ) , relation ) . ifPresent ( errors :: add ) ; return errors ; } | This method checks if the plays edge has been added between the roleplayer s Type and the Role being played . It also checks if the Role of the Casting has been linked to the RelationType of the Relation which the Casting connects to . |
33,301 | private static Optional < String > roleNotLinkedToRelation ( Role role , RelationType relationType , Relation relation ) { boolean notFound = role . relations ( ) . noneMatch ( innerRelationType -> innerRelationType . label ( ) . equals ( relationType . label ( ) ) ) ; if ( notFound ) { return Optional . of ( VALIDATION_RELATION_CASTING_LOOP_FAIL . getMessage ( relation . id ( ) , role . label ( ) , relationType . label ( ) ) ) ; } return Optional . empty ( ) ; } | Checks if the Role of the Casting has been linked to the RelationType of the Relation which the Casting connects to . |
33,302 | private static Optional < String > roleNotAllowedToBePlayed ( Role role , Thing thing ) { TypeImpl < ? , ? > currentConcept = ( TypeImpl < ? , ? > ) thing . type ( ) ; boolean satisfiesPlays = false ; while ( currentConcept != null ) { Map < Role , Boolean > plays = currentConcept . directPlays ( ) ; for ( Map . Entry < Role , Boolean > playsEntry : plays . entrySet ( ) ) { Role rolePlayed = playsEntry . getKey ( ) ; Boolean required = playsEntry . getValue ( ) ; if ( rolePlayed . label ( ) . equals ( role . label ( ) ) ) { satisfiesPlays = true ; if ( required && ! CommonUtil . containsOnly ( thing . relations ( role ) , 1 ) ) { return Optional . of ( VALIDATION_REQUIRED_RELATION . getMessage ( thing . id ( ) , thing . type ( ) . label ( ) , role . label ( ) , thing . relations ( role ) . count ( ) ) ) ; } } } currentConcept = ( TypeImpl ) currentConcept . sup ( ) ; } if ( satisfiesPlays ) { return Optional . empty ( ) ; } else { return Optional . of ( VALIDATION_CASTING . getMessage ( thing . type ( ) . label ( ) , thing . id ( ) , role . label ( ) ) ) ; } } | Checks if the plays edge has been added between the roleplayer s Type and the Role being played . Also checks that required Role are satisfied |
33,303 | static Optional < String > validateRelationHasRolePlayers ( Relation relation ) { if ( ! relation . rolePlayers ( ) . findAny ( ) . isPresent ( ) ) { return Optional . of ( ErrorMessage . VALIDATION_RELATION_WITH_NO_ROLE_PLAYERS . getMessage ( relation . id ( ) , relation . type ( ) . label ( ) ) ) ; } return Optional . empty ( ) ; } | Checks if a Relation has at least one role player . |
33,304 | public Atom rewriteWithTypeVariable ( Atom parentAtom ) { if ( parentAtom . getPredicateVariable ( ) . isReturned ( ) && ! this . getPredicateVariable ( ) . isReturned ( ) && this . getClass ( ) == parentAtom . getClass ( ) ) { return rewriteWithTypeVariable ( ) ; } return this ; } | rewrites the atom to user - defined type variable |
33,305 | private RelationReified reify ( ) { if ( relationStructure . isReified ( ) ) return relationStructure . reify ( ) ; Map < Role , Set < Thing > > rolePlayers = structure ( ) . allRolePlayers ( ) ; relationStructure = relationStructure . reify ( ) ; rolePlayers . forEach ( ( role , things ) -> { Thing thing = Iterables . getOnlyElement ( things ) ; assign ( role , thing ) ; } ) ; return relationStructure . reify ( ) ; } | Reifys and returns the RelationReified |
33,306 | private < X > Stream < X > readFromReified ( Function < RelationReified , Stream < X > > producer ) { return reified ( ) . map ( producer ) . orElseGet ( Stream :: empty ) ; } | Reads some data from a RelationReified . If the Relation has not been reified then an empty Stream is returned . |
33,307 | public Relation assign ( Role role , Thing player ) { reify ( ) . addRolePlayer ( role , player ) ; return this ; } | Expands this Relation to include a new role player which is playing a specific Role . |
33,308 | void cleanUp ( ) { Stream < Thing > rolePlayers = rolePlayers ( ) ; boolean performDeletion = rolePlayers . noneMatch ( thing -> thing != null && thing . id ( ) != null ) ; if ( performDeletion ) delete ( ) ; } | When a relation is deleted this cleans up any solitary casting and resources . |
33,309 | public void delete ( ) { if ( deletionAllowed ( ) ) { T superConcept = cachedSuperType . get ( ) ; deleteNode ( ) ; SchemaConceptImpl . from ( superConcept ) . deleteCachedDirectedSubType ( getThis ( ) ) ; vertex ( ) . tx ( ) . ruleCache ( ) . clear ( ) ; } else { throw TransactionException . cannotBeDeleted ( this ) ; } } | Deletes the concept as a SchemaConcept |
33,310 | private static ImmutableList < ReasonerQueryImpl > queryPlan ( ReasonerQueryImpl query ) { ResolutionPlan resolutionPlan = query . resolutionPlan ( ) ; ImmutableList < Atom > plan = resolutionPlan . plan ( ) ; TransactionOLTP tx = query . tx ( ) ; LinkedList < Atom > atoms = new LinkedList < > ( plan ) ; List < ReasonerQueryImpl > queries = new LinkedList < > ( ) ; List < Atom > nonResolvableAtoms = new ArrayList < > ( ) ; while ( ! atoms . isEmpty ( ) ) { Atom top = atoms . remove ( ) ; if ( top . isRuleResolvable ( ) ) { if ( ! nonResolvableAtoms . isEmpty ( ) ) { queries . add ( ReasonerQueries . create ( nonResolvableAtoms , tx ) ) ; nonResolvableAtoms . clear ( ) ; } queries . add ( ReasonerQueries . atomic ( top ) ) ; } else { nonResolvableAtoms . add ( top ) ; if ( atoms . isEmpty ( ) ) queries . add ( ReasonerQueries . create ( nonResolvableAtoms , tx ) ) ; } } boolean refine = plan . size ( ) != queries . size ( ) && ! query . requiresSchema ( ) ; return refine ? refine ( queries ) : ImmutableList . copyOf ( queries ) ; } | compute the query resolution plan - list of queries ordered by their cost as computed by the graql traversal planner |
33,311 | public static boolean areDisjointTypes ( SchemaConcept parent , SchemaConcept child , boolean direct ) { return parent != null && child == null || ! typesCompatible ( parent , child , direct ) && ! typesCompatible ( child , parent , direct ) ; } | determines disjointness of parent - child types parent defines the bound on the child |
33,312 | public List < Set < T > > getCycles ( ) { return scc . stream ( ) . filter ( cc -> cc . size ( ) > 1 || graph . get ( Iterables . getOnlyElement ( cc ) ) . contains ( Iterables . getOnlyElement ( cc ) ) ) . collect ( Collectors . toList ( ) ) ; } | A cycle isa a connected component that has more than one vertex or a single vertex linked to itself . |
33,313 | public void delete ( ) { Set < Relation > relations = castingsInstance ( ) . map ( casting -> { Relation relation = casting . getRelation ( ) ; Role role = casting . getRole ( ) ; relation . unassign ( role , this ) ; return relation ; } ) . collect ( toSet ( ) ) ; vertex ( ) . tx ( ) . cache ( ) . removedInstance ( type ( ) . id ( ) ) ; deleteNode ( ) ; relations . forEach ( relation -> { if ( relation . type ( ) . isImplicit ( ) ) { relation . delete ( ) ; } else { RelationImpl rel = ( RelationImpl ) relation ; rel . cleanUp ( ) ; } } ) ; } | Deletes the concept as an Thing |
33,314 | private < X extends Concept > Stream < Attribute < ? > > attributes ( Stream < X > conceptStream , Set < ConceptId > attributeTypesIds ) { Stream < Attribute < ? > > attributeStream = conceptStream . filter ( concept -> concept . isAttribute ( ) && ! this . equals ( concept ) ) . map ( Concept :: asAttribute ) ; if ( ! attributeTypesIds . isEmpty ( ) ) { attributeStream = attributeStream . filter ( attribute -> attributeTypesIds . contains ( attribute . type ( ) . id ( ) ) ) ; } return attributeStream ; } | Helper class which filters a Stream of Attribute to those of a specific set of AttributeType . |
33,315 | Stream < Casting > castingsInstance ( ) { return vertex ( ) . getEdgesOfType ( Direction . IN , Schema . EdgeLabel . ROLE_PLAYER ) . map ( edge -> Casting . withThing ( edge , this ) ) ; } | Castings are retrieved from the perspective of the Thing which is a role player in a Relation |
33,316 | private Role [ ] filterNulls ( Role ... roles ) { return Arrays . stream ( roles ) . filter ( Objects :: nonNull ) . toArray ( Role [ ] :: new ) ; } | Returns an array with all the nulls filtered out . |
33,317 | public void shutdown ( ) { transactionListenerSet . forEach ( transactionListener -> transactionListener . close ( null ) ) ; transactionListenerSet . clear ( ) ; openSessions . values ( ) . forEach ( SessionImpl :: close ) ; } | Close all open transactions sessions and connections with clients - this is invoked by JVM shutdown hook |
33,318 | public void deleteEdge ( Direction direction , Schema . EdgeLabel label , VertexElement ... targets ) { Iterator < Edge > edges = element ( ) . edges ( direction , label . getLabel ( ) ) ; if ( targets . length == 0 ) { edges . forEachRemaining ( Edge :: remove ) ; } else { Set < Vertex > verticesToDelete = Arrays . stream ( targets ) . map ( AbstractElement :: element ) . collect ( Collectors . toSet ( ) ) ; edges . forEachRemaining ( edge -> { boolean delete = false ; switch ( direction ) { case BOTH : delete = verticesToDelete . contains ( edge . inVertex ( ) ) || verticesToDelete . contains ( edge . outVertex ( ) ) ; break ; case IN : delete = verticesToDelete . contains ( edge . outVertex ( ) ) ; break ; case OUT : delete = verticesToDelete . contains ( edge . inVertex ( ) ) ; break ; } if ( delete ) edge . remove ( ) ; } ) ; } } | Deletes all the edges of a specific Schema . EdgeLabel to or from a specific set of targets . If no targets are provided then all the edges of the specified type are deleted |
33,319 | public static < T > Weighted < T > weighted ( T value , double weight ) { return new Weighted < > ( value , weight ) ; } | Convenience static constructor |
33,320 | public int compareTo ( Weighted < DirectedEdge > other ) { return ComparisonChain . start ( ) . compare ( other . weight , weight ) . compare ( Objects . hashCode ( other . val ) , Objects . hashCode ( val ) ) . result ( ) ; } | High weights first use val . hashCode to break ties |
33,321 | public void insert ( Attribute attribute ) { queue . put ( attribute . conceptId ( ) . getValue ( ) , attribute ) ; synchronized ( this ) { notifyAll ( ) ; } } | insert a new attribute at the end of the queue . |
33,322 | public void ack ( List < Attribute > attributes ) { for ( Attribute attr : attributes ) { queue . remove ( attr . conceptId ( ) . getValue ( ) ) ; } } | Remove attributes from the queue . |
33,323 | public static void deduplicate ( SessionFactory sessionFactory , KeyspaceIndexPair keyspaceIndexPair ) { SessionImpl session = sessionFactory . session ( keyspaceIndexPair . keyspace ( ) ) ; try ( TransactionOLTP tx = session . transaction ( ) . write ( ) ) { GraphTraversalSource tinker = tx . getTinkerTraversal ( ) ; GraphTraversal < Vertex , Vertex > duplicates = tinker . V ( ) . has ( Schema . VertexProperty . INDEX . name ( ) , keyspaceIndexPair . index ( ) ) ; if ( duplicates . hasNext ( ) ) { Vertex mergeTargetV = duplicates . next ( ) ; while ( duplicates . hasNext ( ) ) { Vertex duplicate = duplicates . next ( ) ; try { duplicate . vertices ( Direction . IN ) . forEachRemaining ( connectedVertex -> { GraphTraversal < Vertex , Edge > attributeEdge = tinker . V ( duplicate ) . inE ( Schema . EdgeLabel . ATTRIBUTE . getLabel ( ) ) . filter ( __ . outV ( ) . is ( connectedVertex ) ) ; if ( attributeEdge . hasNext ( ) ) { mergeAttributeEdge ( mergeTargetV , connectedVertex , attributeEdge ) ; } GraphTraversal < Vertex , Edge > rolePlayerEdge = tinker . V ( duplicate ) . inE ( Schema . EdgeLabel . ROLE_PLAYER . getLabel ( ) ) . filter ( __ . outV ( ) . is ( connectedVertex ) ) ; if ( rolePlayerEdge . hasNext ( ) ) { mergeRolePlayerEdge ( mergeTargetV , rolePlayerEdge ) ; } try { attributeEdge . close ( ) ; rolePlayerEdge . close ( ) ; } catch ( Exception e ) { LOG . warn ( "Exception while closing traversals:" , e ) ; } } ) ; duplicate . remove ( ) ; } catch ( IllegalStateException vertexAlreadyRemovedException ) { LOG . warn ( "Trying to call the method vertices(Direction.IN) on vertex {} which is already removed." , duplicate . id ( ) ) ; } } tx . commit ( ) ; } else { tx . close ( ) ; } try { tinker . close ( ) ; duplicates . close ( ) ; } catch ( Exception e ) { LOG . warn ( "Exception while closing traversals:" , e ) ; } } finally { session . close ( ) ; } } | Deduplicate attributes that has the same value . A de - duplication process consists of picking a single attribute in the duplicates as the merge target copying every edges from every other duplicates to the merge target and finally deleting that other duplicates . |
33,324 | public QueryAnswers unify ( Unifier unifier ) { if ( unifier . isEmpty ( ) ) return new QueryAnswers ( this ) ; QueryAnswers unifiedAnswers = new QueryAnswers ( ) ; this . stream ( ) . map ( unifier :: apply ) . filter ( a -> ! a . isEmpty ( ) ) . forEach ( unifiedAnswers :: add ) ; return unifiedAnswers ; } | unify the answers by applying unifier to variable set |
33,325 | public QueryAnswers unify ( MultiUnifier multiUnifier ) { QueryAnswers unifiedAnswers = new QueryAnswers ( ) ; this . stream ( ) . flatMap ( multiUnifier :: apply ) . filter ( ans -> ! ans . isEmpty ( ) ) . forEach ( unifiedAnswers :: add ) ; return unifiedAnswers ; } | unify the answers by applying multiunifier to variable set |
33,326 | RelationImpl buildRelation ( EdgeElement edge ) { return getOrBuildConcept ( edge , ( e ) -> RelationImpl . create ( RelationEdge . get ( edge ) ) ) ; } | Used by RelationEdge to build a RelationImpl object out of a provided Edge |
33,327 | RelationReified buildRelationReified ( VertexElement vertex , RelationType type ) { return RelationReified . create ( vertex , type ) ; } | Used by RelationEdge when it needs to reify a relation . Used by this factory when need to build an explicit relation |
33,328 | RelationImpl buildRelation ( VertexElement vertex , RelationType type ) { return getOrBuildConcept ( vertex , ( v ) -> RelationImpl . create ( buildRelationReified ( v , type ) ) ) ; } | Used by RelationTypeImpl to create a new instance of RelationImpl first build a ReifiedRelation and then inject it to RelationImpl |
33,329 | private Schema . BaseType getBaseType ( VertexElement vertex ) { try { return Schema . BaseType . valueOf ( vertex . label ( ) ) ; } catch ( IllegalArgumentException e ) { Optional < VertexElement > type = vertex . getEdgesOfType ( Direction . OUT , Schema . EdgeLabel . SHARD ) . map ( EdgeElement :: target ) . findAny ( ) ; if ( type . isPresent ( ) ) { String label = type . get ( ) . label ( ) ; if ( label . equals ( Schema . BaseType . ENTITY_TYPE . name ( ) ) ) return Schema . BaseType . ENTITY ; if ( label . equals ( RELATION_TYPE . name ( ) ) ) return Schema . BaseType . RELATION ; if ( label . equals ( Schema . BaseType . ATTRIBUTE_TYPE . name ( ) ) ) return Schema . BaseType . ATTRIBUTE ; } } throw new IllegalStateException ( "Could not determine the base type of vertex [" + vertex + "]" ) ; } | This is a helper method to get the base type of a vertex . It first tried to get the base type via the label . If this is not possible it then tries to get the base type via the Shard Edge . |
33,330 | public VertexElement addVertexElement ( Schema . BaseType baseType ) { Vertex vertex = graph . addVertex ( baseType . name ( ) ) ; return new VertexElement ( tx , vertex ) ; } | Creates a new Vertex in the graph and builds a VertexElement which wraps the newly created vertex |
33,331 | private String colorKeyword ( String keyword ) { if ( colorize ) { return ANSI . color ( keyword , ANSI . BLUE ) ; } else { return keyword ; } } | Color - codes the keyword if colorization enabled |
33,332 | private String colorType ( SchemaConcept schemaConcept ) { if ( colorize ) { return ANSI . color ( label ( schemaConcept . label ( ) ) , ANSI . PURPLE ) ; } else { return label ( schemaConcept . label ( ) ) ; } } | Color - codes the given type if colorization enabled |
33,333 | void populateSchemaTxCache ( TransactionCache transactionCache ) { try { lock . writeLock ( ) . lock ( ) ; Map < Label , LabelId > cachedLabelsSnapshot = getCachedLabels ( ) ; cachedLabelsSnapshot . forEach ( transactionCache :: cacheLabel ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } } | Copy the contents of the Keyspace cache into a TransactionOLTP Cache |
33,334 | void readTxCache ( TransactionCache transactionCache ) { if ( ! cachedLabels . equals ( transactionCache . getLabelCache ( ) ) ) { try { lock . writeLock ( ) . lock ( ) ; cachedLabels . clear ( ) ; cachedLabels . putAll ( transactionCache . getLabelCache ( ) ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } } } | Reads the SchemaConcept labels currently in the transaction cache into the keyspace cache . This happens when a commit occurs and allows us to track schema mutations without having to read the graph . |
33,335 | public Set < Weighted < DirectedEdge > > directedEdges ( Map < NodeId , Node > nodes ) { return Collections . emptySet ( ) ; } | Convert the fragment to a set of weighted edges for query planning |
33,336 | private Attribute < D > putInstance ( Schema . BaseType instanceBaseType , Supplier < Attribute < D > > finder , BiFunction < VertexElement , AttributeType < D > , Attribute < D > > producer , boolean isInferred ) { Attribute < D > instance = finder . get ( ) ; if ( instance == null ) { instance = addInstance ( instanceBaseType , producer , isInferred ) ; } else { if ( isInferred && ! instance . isInferred ( ) ) { throw TransactionException . nonInferredThingExists ( instance ) ; } } return instance ; } | Utility method used to create or find an instance of this type |
33,337 | private void checkConformsToRegexes ( String value ) { this . sups ( ) . forEach ( sup -> { String regex = sup . regex ( ) ; if ( regex != null && ! Pattern . matches ( regex , value ) ) { throw TransactionException . regexFailure ( this , value , regex ) ; } } ) ; } | Checks if all the regex s of the types of this resource conforms to the value provided . |
33,338 | @ SuppressWarnings ( { "unchecked" } ) public DataType < D > dataType ( ) { String className = vertex ( ) . property ( Schema . VertexProperty . DATA_TYPE ) ; if ( className == null ) return null ; try { return ( DataType < D > ) DataType . of ( Class . forName ( className ) ) ; } catch ( ClassNotFoundException e ) { throw TransactionException . unsupportedDataType ( className ) ; } } | This unsafe cast is suppressed because at this stage we do not know what the type is when reading from the rootGraph . |
33,339 | static < T > GraphTraversal < T , Vertex > outSubs ( GraphTraversal < T , Vertex > traversal ) { return outSubs ( traversal , TRAVERSE_ALL_SUB_EDGES ) ; } | Default unlimiteid depth sub - edge traversal |
33,340 | static < T > GraphTraversal < T , Vertex > inSubs ( GraphTraversal < T , Vertex > traversal ) { return inSubs ( traversal , TRAVERSE_ALL_SUB_EDGES ) ; } | Default unlimited - depth sub - edge traversal |
33,341 | static < T > GraphTraversal < T , Vertex > isVertex ( GraphTraversal < T , ? extends Element > traversal ) { return ( GraphTraversal < T , Vertex > ) traversal . filter ( e -> e . get ( ) instanceof Vertex ) ; } | Create a traversal that filters to only vertices |
33,342 | static < T > GraphTraversal < T , Edge > isEdge ( GraphTraversal < T , ? extends Element > traversal ) { return ( GraphTraversal < T , Edge > ) traversal . filter ( e -> e . get ( ) instanceof Edge ) ; } | Create a traversal that filters to only edges |
33,343 | private RolePlayerFragmentSet removeRoleVar ( ) { Preconditions . checkNotNull ( role ( ) ) ; return new AutoValue_RolePlayerFragmentSet ( varProperty ( ) , relation ( ) , edge ( ) , rolePlayer ( ) , null , roleLabels ( ) , relationTypeLabels ( ) ) ; } | Remove any specified role variable |
33,344 | public Connection getFrom ( ) { final List < Connection > list = getIncomingConnections ( org . jbpm . workflow . core . Node . CONNECTION_DEFAULT_TYPE ) ; if ( list . size ( ) == 0 ) { return null ; } if ( list . size ( ) == 1 ) { return list . get ( 0 ) ; } if ( "true" . equals ( System . getProperty ( "jbpm.enable.multi.con" ) ) ) { return list . get ( 0 ) ; } else { throw new IllegalArgumentException ( "Trying to retrieve the from connection but multiple connections are present" ) ; } } | Helper method for nodes that have at most one default incoming connection |
33,345 | public List < Connection > getDefaultIncomingConnections ( ) { return getIncomingConnections ( org . jbpm . workflow . core . Node . CONNECTION_DEFAULT_TYPE ) ; } | Helper method for nodes that have multiple default incoming connections |
33,346 | public List < Connection > getDefaultOutgoingConnections ( ) { return getOutgoingConnections ( org . jbpm . workflow . core . Node . CONNECTION_DEFAULT_TYPE ) ; } | Helper method for nodes that have multiple default outgoing connections |
33,347 | private void connectProcessInstanceToRuntimeAndProcess ( ProcessInstance processInstance , Object streamContext ) { ProcessInstanceImpl processInstanceImpl = ( ProcessInstanceImpl ) processInstance ; InternalKnowledgeRuntime kruntime = processInstanceImpl . getKnowledgeRuntime ( ) ; if ( kruntime == null ) { kruntime = retrieveKnowledgeRuntime ( streamContext ) ; processInstanceImpl . setKnowledgeRuntime ( kruntime ) ; } if ( processInstance . getProcess ( ) == null ) { String processId = processInstance . getProcessId ( ) ; if ( processId != null ) { Process process = kruntime . getKieBase ( ) . getProcess ( processId ) ; if ( process != null ) { processInstanceImpl . setProcess ( process ) ; } } } } | Fill the process instance . kruntime and . process fields with the appropriate values . |
33,348 | private EntityManager getEntityManager ( KieRuntimeEvent event ) { Environment env = event . getKieRuntime ( ) . getEnvironment ( ) ; sharedEM = false ; if ( emf != null ) { return emf . createEntityManager ( ) ; } else if ( env != null ) { EntityManagerFactory emf = ( EntityManagerFactory ) env . get ( EnvironmentName . ENTITY_MANAGER_FACTORY ) ; EntityManager em = getEntityManagerFromTransaction ( env ) ; if ( em != null && em . isOpen ( ) && em . getEntityManagerFactory ( ) . equals ( emf ) ) { sharedEM = true ; return em ; } em = ( EntityManager ) env . get ( EnvironmentName . CMD_SCOPED_ENTITY_MANAGER ) ; if ( em != null ) { sharedEM = true ; return em ; } if ( emf != null ) { return emf . createEntityManager ( ) ; } } throw new RuntimeException ( "Could not find or create a new EntityManager!" ) ; } | This method creates a entity manager . |
33,349 | protected Long getPersistedSessionId ( String location , String identifier ) { File sessionIdStore = new File ( location + File . separator + identifier + "-jbpmSessionId.ser" ) ; if ( sessionIdStore . exists ( ) ) { Long knownSessionId = null ; FileInputStream fis = null ; ObjectInputStream in = null ; try { fis = new FileInputStream ( sessionIdStore ) ; in = new ObjectInputStream ( fis ) ; Object tmp = in . readObject ( ) ; if ( tmp instanceof Integer ) { tmp = new Long ( ( Integer ) tmp ) ; } knownSessionId = ( Long ) tmp ; return knownSessionId . longValue ( ) ; } catch ( Exception e ) { return 0L ; } finally { if ( in != null ) { try { in . close ( ) ; } catch ( IOException e ) { } } if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { } } } } else { return 0L ; } } | Retrieves session id from serialized file named jbpmSessionId . ser from given location . |
33,350 | protected void persistSessionId ( String location , String identifier , Long ksessionId ) { if ( location == null ) { return ; } FileOutputStream fos = null ; ObjectOutputStream out = null ; try { fos = new FileOutputStream ( location + File . separator + identifier + "-jbpmSessionId.ser" ) ; out = new ObjectOutputStream ( fos ) ; out . writeObject ( Long . valueOf ( ksessionId ) ) ; out . close ( ) ; } catch ( IOException ex ) { } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { } } if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { } } } } | Stores gives ksessionId in a serialized file in given location under jbpmSessionId . ser file name |
33,351 | protected String generateUniquePath ( ) { File parent ; String destinationPath ; do { destinationPath = UUID . randomUUID ( ) . toString ( ) ; parent = getFileByPath ( destinationPath ) ; } while ( parent . exists ( ) ) ; return destinationPath ; } | Generates a random path to store the file to avoid overwritting files with the same name |
33,352 | protected void readDataOutput ( org . w3c . dom . Node xmlNode , StartNode startNode ) { String id = ( ( Element ) xmlNode ) . getAttribute ( "id" ) ; String outputName = ( ( Element ) xmlNode ) . getAttribute ( "name" ) ; dataOutputs . put ( id , outputName ) ; } | The results of this method are only used to check syntax |
33,353 | public Command findCommand ( String name , ClassLoader cl ) { synchronized ( commandCache ) { if ( ! commandCache . containsKey ( name ) ) { try { Command commandInstance = ( Command ) Class . forName ( name , true , cl ) . newInstance ( ) ; commandCache . put ( name , commandInstance ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Unknown Command implementation with name '" + name + "'" ) ; } } else { Command cmd = commandCache . get ( name ) ; if ( ! cmd . getClass ( ) . getClassLoader ( ) . equals ( cl ) ) { commandCache . remove ( name ) ; try { Command commandInstance = ( Command ) Class . forName ( name , true , cl ) . newInstance ( ) ; commandCache . put ( name , commandInstance ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Unknown Command implementation with name '" + name + "'" ) ; } } } } return commandCache . get ( name ) ; } | Finds command by FQCN and if not found loads the class and store the instance in the cache . |
33,354 | public CommandCallback findCommandCallback ( String name , ClassLoader cl ) { synchronized ( callbackCache ) { if ( ! callbackCache . containsKey ( name ) ) { try { CommandCallback commandCallbackInstance = ( CommandCallback ) Class . forName ( name , true , cl ) . newInstance ( ) ; return commandCallbackInstance ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Unknown Command implementation with name '" + name + "'" ) ; } } else { CommandCallback cmdCallback = callbackCache . get ( name ) ; if ( ! cmdCallback . getClass ( ) . getClassLoader ( ) . equals ( cl ) ) { callbackCache . remove ( name ) ; try { CommandCallback commandCallbackInstance = ( CommandCallback ) Class . forName ( name , true , cl ) . newInstance ( ) ; callbackCache . put ( name , commandCallbackInstance ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Unknown Command implementation with name '" + name + "'" ) ; } } } } return callbackCache . get ( name ) ; } | Finds command callback by FQCN and if not found loads the class and store the instance in the cache . |
33,355 | public List < CommandCallback > buildCommandCallback ( CommandContext ctx , ClassLoader cl ) { List < CommandCallback > callbackList = new ArrayList < CommandCallback > ( ) ; if ( ctx != null && ctx . getData ( "callbacks" ) != null ) { logger . debug ( "Callback: {}" , ctx . getData ( "callbacks" ) ) ; String [ ] callbacksArray = ( ( String ) ctx . getData ( "callbacks" ) ) . split ( "," ) ; List < String > callbacks = ( List < String > ) Arrays . asList ( callbacksArray ) ; for ( String callbackName : callbacks ) { CommandCallback handler = findCommandCallback ( callbackName . trim ( ) , cl ) ; callbackList . add ( handler ) ; } } return callbackList ; } | Builds completely initialized list of callbacks for given context . |
33,356 | public void clear ( ) { this . union = true ; this . type = QueryCriteriaType . NORMAL ; this . ancestry . clear ( ) ; if ( this . criteria != null ) { this . criteria . clear ( ) ; } this . currentCriteria = this . criteria ; this . maxResults = null ; this . offset = null ; this . orderByListId = null ; this . ascOrDesc = null ; this . joinPredicates = null ; } | clear & clone |
33,357 | @ SuppressWarnings ( "unchecked" ) public T date ( Date ... date ) { if ( checkIfNull ( date ) ) { return ( T ) this ; } date = ensureDateNotTimestamp ( date ) ; addObjectParameter ( DATE_LIST , "date" , date ) ; return ( T ) this ; } | query builder methods |
33,358 | static AssignmentService override ( AssignmentStrategy strategy ) { Holder . INSTANCE . setAssignmentService ( new AssignmentServiceImpl ( strategy ) ) ; return get ( ) ; } | for test purpose |
33,359 | public CaseMarshallerFactory withJpa ( String puName ) { marshallers . add ( new JPAPlaceholderResolverStrategy ( puName , classLoader ) ) ; this . toString . append ( ".withJpa(\"" + puName + "\")" ) ; return this ; } | Add JPA marshalling strategy to be used by CaseFileMarshaller |
33,360 | public CaseMarshallerFactory with ( ObjectMarshallingStrategy custom ) { marshallers . add ( custom ) ; this . toString . append ( ".with(new " + custom . getClass ( ) . getName ( ) + "())" ) ; return this ; } | Adds given custom marshalling strategy to be used by CaseFileMarshaller |
33,361 | public Date getScheduleTime ( ) { if ( nextScheduleTimeAdd < 0 ) { return null ; } long current = System . currentTimeMillis ( ) ; Date nextSchedule = new Date ( current + nextScheduleTimeAdd ) ; logger . debug ( "Next schedule for job {} is set to {}" , this . getClass ( ) . getSimpleName ( ) , nextSchedule ) ; return nextSchedule ; } | one day in milliseconds |
33,362 | public LdapSearcher search ( String context , String filterExpr , Object ... filterArgs ) { searchResults . clear ( ) ; LdapContext ldapContext = null ; NamingEnumeration < SearchResult > ldapResult = null ; try { ldapContext = buildLdapContext ( ) ; ldapResult = ldapContext . search ( context , filterExpr , filterArgs , createSearchControls ( ) ) ; while ( ldapResult . hasMore ( ) ) { searchResults . add ( ldapResult . next ( ) ) ; } } catch ( NamingException ex ) { throw new RuntimeException ( "LDAP search has failed" , ex ) ; } finally { if ( ldapResult != null ) { try { ldapResult . close ( ) ; } catch ( NamingException ex ) { log . error ( "Failed to close LDAP results enumeration" , ex ) ; } } if ( ldapContext != null ) { try { ldapContext . close ( ) ; } catch ( NamingException ex ) { log . error ( "Failed to close LDAP context" , ex ) ; } } } return this ; } | Search LDAP and stores the results in searchResults field . |
33,363 | public List < Object > getParameters ( ) { List < Object > parameters = new ArrayList < Object > ( getValues ( ) ) ; if ( this . dateValues != null && ! this . dateValues . isEmpty ( ) ) { parameters . addAll ( this . dateValues ) ; } if ( parameters . isEmpty ( ) ) { return parameters ; } return parameters ; } | This method returns a list that should only be read |
33,364 | public boolean acceptsEvent ( String type , Object event , Function < String , String > resolver ) { return false ; } | Nodes that use this event filter should never be triggered by this event |
33,365 | public Object service ( String name ) { Object service = this . services . get ( name ) ; if ( service == null ) { throw new IllegalArgumentException ( "Service '" + name + "' not found" ) ; } return service ; } | Retrieves service registered under given name |
33,366 | public static AsyncTaskLifeCycleEventProducer newJMSInstance ( boolean transacted , ConnectionFactory connFactory , Queue queue ) { AsyncTaskLifeCycleEventProducer logger = new AsyncTaskLifeCycleEventProducer ( ) ; logger . setTransacted ( transacted ) ; logger . setConnectionFactory ( connFactory ) ; logger . setQueue ( queue ) ; return logger ; } | Creates new instance of JMS task audit logger based on given connection factory and queue . |
33,367 | public void addAsset ( Resource resource , ResourceType type ) { boolean replaced = false ; if ( resource . getSourcePath ( ) != null ) { String path = resource . getSourcePath ( ) ; String typeStr = null ; if ( path . toLowerCase ( ) . endsWith ( ".csv" ) ) { typeStr = DecisionTableInputType . CSV . toString ( ) ; } else if ( path . toLowerCase ( ) . endsWith ( ".xls" ) ) { typeStr = DecisionTableInputType . XLS . toString ( ) ; } if ( typeStr != null ) { String worksheetName = null ; boolean replaceConfig = true ; ResourceConfiguration config = resource . getConfiguration ( ) ; if ( config != null && config instanceof DecisionTableConfiguration ) { DecisionTableInputType realType = DecisionTableInputType . valueOf ( typeStr ) ; if ( ( ( DecisionTableConfiguration ) config ) . getInputType ( ) . equals ( realType ) ) { replaceConfig = false ; } else { worksheetName = ( ( DecisionTableConfiguration ) config ) . getWorksheetName ( ) ; } } if ( replaceConfig ) { Properties prop = new Properties ( ) ; prop . setProperty ( ResourceTypeImpl . KIE_RESOURCE_CONF_CLASS , DecisionTableConfigurationImpl . class . getName ( ) ) ; prop . setProperty ( DecisionTableConfigurationImpl . DROOLS_DT_TYPE , typeStr ) ; if ( worksheetName != null ) { prop . setProperty ( DecisionTableConfigurationImpl . DROOLS_DT_WORKSHEET , worksheetName ) ; } ResourceConfiguration conf = ResourceTypeImpl . fromProperties ( prop ) ; this . kbuilder . add ( resource , type , conf ) ; replaced = true ; } } } if ( ! replaced ) { this . kbuilder . add ( resource , type ) ; } if ( this . kbuilder . hasErrors ( ) ) { StringBuffer errorMessage = new StringBuffer ( ) ; for ( KnowledgeBuilderError error : kbuilder . getErrors ( ) ) { errorMessage . append ( error . getMessage ( ) + "," ) ; } this . kbuilder . undo ( ) ; throw new IllegalArgumentException ( "Cannot add asset: " + errorMessage . toString ( ) ) ; } } | Adds given asset to knowledge builder to produce KieBase |
33,368 | public void addComment ( Comment comment ) { if ( comments == null || comments . size ( ) == 0 ) { comments = new ArrayList < Comment > ( ) ; } comments . add ( ( CommentImpl ) comment ) ; } | Adds the specified comment to our list of comments . |
33,369 | public Comment removeComment ( final long commentId ) { Comment removedComment = null ; if ( comments != null ) { for ( int index = comments . size ( ) - 1 ; index >= 0 ; -- index ) { Comment currentComment = comments . get ( index ) ; if ( currentComment . getId ( ) == commentId ) { removedComment = comments . remove ( index ) ; break ; } } } return removedComment ; } | Removes the Comment specified by the commentId . |
33,370 | public void addAttachment ( Attachment attachment ) { if ( attachments == null || attachments == Collections . < Attachment > emptyList ( ) ) { attachments = new ArrayList < Attachment > ( ) ; } attachments . add ( ( AttachmentImpl ) attachment ) ; } | Adds the specified attachment to our list of Attachments . |
33,371 | public Attachment removeAttachment ( final long attachmentId ) { Attachment removedAttachment = null ; if ( attachments != null ) { for ( int index = attachments . size ( ) - 1 ; index >= 0 ; -- index ) { Attachment currentAttachment = attachments . get ( index ) ; if ( currentAttachment . getId ( ) == attachmentId ) { removedAttachment = attachments . remove ( index ) ; break ; } } } return removedAttachment ; } | Removes the Attachment specified by the attachmentId . |
33,372 | @ EJB ( beanInterface = DefinitionServiceEJBLocal . class ) public void setBpmn2Service ( DefinitionService bpmn2Service ) { super . setBpmn2Service ( bpmn2Service ) ; super . addListener ( ( DeploymentEventListener ) bpmn2Service ) ; } | inject ejb beans |
33,373 | public void complete ( ) { this . endDate = new Date ( ) ; if ( reports . stream ( ) . allMatch ( report -> report . isSuccessful ( ) == true ) ) { this . successful = true ; } } | Completes the migration and calculates the status . |
33,374 | public QueryResultMapper < ? > mapperFor ( String name , Map < String , String > columnMapping ) { if ( ! knownMappers . containsKey ( name ) ) { throw new IllegalArgumentException ( "No mapper found with name " + name ) ; } if ( columnMapping == null ) { return knownMappers . get ( name ) ; } else { return knownMappers . get ( name ) . forColumnMapping ( columnMapping ) ; } } | Returns mapper for given name if found |
33,375 | public void registerTimerService ( String id , TimerService timerService ) { if ( timerService instanceof GlobalTimerService ) { ( ( GlobalTimerService ) timerService ) . setTimerServiceId ( id ) ; } this . registeredServices . put ( id , timerService ) ; } | Registers timerServie under given id . In case timer service is already registered with this id it will be overridden . |
33,376 | public TimerService get ( String id ) { if ( id == null ) { return null ; } return this . registeredServices . get ( id ) ; } | Returns TimerService instance registered under given key |
33,377 | @ SubscribeEvent ( priority = EventPriority . LOWEST ) public void onBiomeGenInit ( WorldTypeEvent . InitBiomeGens event ) { if ( bparams . getBiome ( ) == - 1 ) return ; GenLayer [ ] replacement = new GenLayer [ 2 ] ; replacement [ 0 ] = new GenLayerConstant ( bparams . getBiome ( ) ) ; replacement [ 1 ] = replacement [ 0 ] ; event . setNewBiomeGens ( replacement ) ; } | Make sure that the biome is one type with an event on biome gen |
33,378 | private static boolean itemStackIngredientsMatch ( ItemStack A , ItemStack B ) { if ( A == null && B == null ) return true ; if ( A == null || B == null ) return false ; if ( A . getMetadata ( ) == OreDictionary . WILDCARD_VALUE || B . getMetadata ( ) == OreDictionary . WILDCARD_VALUE ) return A . getItem ( ) == B . getItem ( ) ; return ItemStack . areItemsEqual ( A , B ) ; } | Compare two ItemStacks and see if their items match - take wildcards into account don t take stacksize into account . |
33,379 | public static int totalBurnTimeInInventory ( EntityPlayerMP player ) { Integer fromCache = fuelCaches . get ( player ) ; int total = ( fromCache != null ) ? fromCache : 0 ; for ( int i = 0 ; i < player . inventory . mainInventory . size ( ) ; i ++ ) { ItemStack is = player . inventory . mainInventory . get ( i ) ; total += TileEntityFurnace . getItemBurnTime ( is ) ; } return total ; } | Go through player s inventory and see how much fuel they have . |
33,380 | public static List < IRecipe > getRecipesForRequestedOutput ( String output ) { List < IRecipe > matchingRecipes = new ArrayList < IRecipe > ( ) ; ItemStack target = MinecraftTypeHelper . getItemStackFromParameterString ( output ) ; List < ? > recipes = CraftingManager . getInstance ( ) . getRecipeList ( ) ; for ( Object obj : recipes ) { if ( obj == null ) continue ; if ( obj instanceof IRecipe ) { ItemStack is = ( ( IRecipe ) obj ) . getRecipeOutput ( ) ; if ( is == null ) continue ; if ( ItemStack . areItemsEqual ( is , target ) ) { matchingRecipes . add ( ( IRecipe ) obj ) ; } } } return matchingRecipes ; } | Attempt to find all recipes that result in an item of the requested output . |
33,381 | public static ItemStack getSmeltingRecipeForRequestedOutput ( String output ) { ItemStack target = MinecraftTypeHelper . getItemStackFromParameterString ( output ) ; Iterator < ? > furnaceIt = FurnaceRecipes . instance ( ) . getSmeltingList ( ) . keySet ( ) . iterator ( ) ; while ( furnaceIt . hasNext ( ) ) { ItemStack isInput = ( ItemStack ) furnaceIt . next ( ) ; ItemStack isOutput = ( ItemStack ) FurnaceRecipes . instance ( ) . getSmeltingList ( ) . get ( isInput ) ; if ( itemStackIngredientsMatch ( target , isOutput ) ) return isInput ; } return null ; } | Attempt to find a smelting recipe that results in the requested output . |
33,382 | public static void dumpRecipes ( String filename ) throws IOException { FileOutputStream fos = new FileOutputStream ( filename ) ; OutputStreamWriter osw = new OutputStreamWriter ( fos , "utf-8" ) ; BufferedWriter writer = new BufferedWriter ( osw ) ; List < ? > recipes = CraftingManager . getInstance ( ) . getRecipeList ( ) ; for ( Object obj : recipes ) { if ( obj == null ) continue ; if ( obj instanceof IRecipe ) { ItemStack is = ( ( IRecipe ) obj ) . getRecipeOutput ( ) ; if ( is == null ) continue ; String s = is . getCount ( ) + "x" + is . getUnlocalizedName ( ) + " = " ; List < ItemStack > ingredients = getIngredients ( ( IRecipe ) obj ) ; if ( ingredients == null ) continue ; boolean first = true ; for ( ItemStack isIngredient : ingredients ) { if ( ! first ) s += ", " ; s += isIngredient . getCount ( ) + "x" + isIngredient . getUnlocalizedName ( ) ; s += "(" + isIngredient . getDisplayName ( ) + ")" ; first = false ; } s += "\n" ; writer . write ( s ) ; } } Iterator < ? > furnaceIt = FurnaceRecipes . instance ( ) . getSmeltingList ( ) . keySet ( ) . iterator ( ) ; while ( furnaceIt . hasNext ( ) ) { ItemStack isInput = ( ItemStack ) furnaceIt . next ( ) ; ItemStack isOutput = ( ItemStack ) FurnaceRecipes . instance ( ) . getSmeltingList ( ) . get ( isInput ) ; String s = isOutput . getCount ( ) + "x" + isOutput . getUnlocalizedName ( ) + " = FUEL + " + isInput . getCount ( ) + "x" + isInput . getUnlocalizedName ( ) + "\n" ; writer . write ( s ) ; } writer . close ( ) ; } | Little utility method for dumping out a list of all the recipes we understand . |
33,383 | public void onCheckSpawn ( CheckSpawn cs ) { boolean allowSpawning = false ; if ( currentMissionInit ( ) != null && currentMissionInit ( ) . getMission ( ) != null ) { ServerSection ss = currentMissionInit ( ) . getMission ( ) . getServerSection ( ) ; ServerInitialConditions sic = ( ss != null ) ? ss . getServerInitialConditions ( ) : null ; if ( sic != null ) allowSpawning = ( sic . isAllowSpawning ( ) == Boolean . TRUE ) ; if ( allowSpawning && sic . getAllowedMobs ( ) != null && ! sic . getAllowedMobs ( ) . isEmpty ( ) ) { String mobName = EntityList . getEntityString ( cs . getEntity ( ) ) ; allowSpawning = false ; for ( EntityTypes mob : sic . getAllowedMobs ( ) ) { if ( mob . value ( ) . equals ( mobName ) ) { allowSpawning = true ; break ; } } } } if ( allowSpawning ) cs . setResult ( Result . DEFAULT ) ; else cs . setResult ( Result . DENY ) ; } | Called by Forge - return ALLOW DENY or DEFAULT to control spawning in our world . |
33,384 | public static void buildAchievementStats ( JsonObject json , EntityPlayerMP player ) { StatisticsManagerServer sfw = player . getStatFile ( ) ; json . addProperty ( "DistanceTravelled" , sfw . readStat ( ( StatBase ) StatList . WALK_ONE_CM ) + sfw . readStat ( ( StatBase ) StatList . SWIM_ONE_CM ) + sfw . readStat ( ( StatBase ) StatList . DIVE_ONE_CM ) + sfw . readStat ( ( StatBase ) StatList . FALL_ONE_CM ) ) ; json . addProperty ( "TimeAlive" , sfw . readStat ( ( StatBase ) StatList . TIME_SINCE_DEATH ) ) ; json . addProperty ( "MobsKilled" , sfw . readStat ( ( StatBase ) StatList . MOB_KILLS ) ) ; json . addProperty ( "PlayersKilled" , sfw . readStat ( ( StatBase ) StatList . PLAYER_KILLS ) ) ; json . addProperty ( "DamageTaken" , sfw . readStat ( ( StatBase ) StatList . DAMAGE_TAKEN ) ) ; json . addProperty ( "DamageDealt" , sfw . readStat ( ( StatBase ) StatList . DAMAGE_DEALT ) ) ; } | Builds the basic achievement world data to be used as observation signals by the listener . |
33,385 | public static void buildLifeStats ( JsonObject json , EntityPlayerMP player ) { json . addProperty ( "Life" , player . getHealth ( ) ) ; json . addProperty ( "Score" , player . getScore ( ) ) ; json . addProperty ( "Food" , player . getFoodStats ( ) . getFoodLevel ( ) ) ; json . addProperty ( "XP" , player . experienceTotal ) ; json . addProperty ( "IsAlive" , ! player . isDead ) ; json . addProperty ( "Air" , player . getAir ( ) ) ; json . addProperty ( "Name" , player . getName ( ) ) ; } | Builds the basic life world data to be used as observation signals by the listener . |
33,386 | public static void buildPositionStats ( JsonObject json , EntityPlayerMP player ) { json . addProperty ( "XPos" , player . posX ) ; json . addProperty ( "YPos" , player . posY ) ; json . addProperty ( "ZPos" , player . posZ ) ; json . addProperty ( "Pitch" , player . rotationPitch ) ; json . addProperty ( "Yaw" , player . rotationYaw ) ; } | Builds the player position data to be used as observation signals by the listener . |
33,387 | static public File copyMapFiles ( File mapFile , boolean isTemporary ) { System . out . println ( "Current directory: " + System . getProperty ( "user.dir" ) ) ; File savesDir = FMLClientHandler . instance ( ) . getSavesDir ( ) ; File dst = null ; if ( mapFile != null && mapFile . exists ( ) ) { dst = new File ( savesDir , getNewSaveFileLocation ( isTemporary ) ) ; try { FileUtils . copyDirectory ( mapFile , dst ) ; } catch ( IOException e ) { System . out . println ( "Failed to load file: " + mapFile . getPath ( ) ) ; return null ; } } return dst ; } | Attempt to copy the specified file into the Minecraft saves folder . |
33,388 | public static boolean createAndLaunchWorld ( WorldSettings worldsettings , boolean isTemporary ) { String s = getNewSaveFileLocation ( isTemporary ) ; Minecraft . getMinecraft ( ) . launchIntegratedServer ( s , s , worldsettings ) ; cleanupTemporaryWorlds ( s ) ; return true ; } | Creates and launches a unique world according to the settings . |
33,389 | public static void cleanupTemporaryWorlds ( String currentWorld ) { List < WorldSummary > saveList ; ISaveFormat isaveformat = Minecraft . getMinecraft ( ) . getSaveLoader ( ) ; isaveformat . flushCache ( ) ; try { saveList = isaveformat . getSaveList ( ) ; } catch ( AnvilConverterException e ) { e . printStackTrace ( ) ; return ; } String searchString = tempMark + AddressHelper . getMissionControlPort ( ) + "_" ; for ( WorldSummary s : saveList ) { String folderName = s . getFileName ( ) ; if ( folderName . startsWith ( searchString ) && ! folderName . equals ( currentWorld ) ) { isaveformat . deleteWorldDirectory ( folderName ) ; } } } | Attempts to delete all Minecraft Worlds with TEMP_ in front of the name |
33,390 | public void Draw ( DrawingDecorator drawingNode , World world ) throws Exception { beginDrawing ( world ) ; for ( JAXBElement < ? > jaxbobj : drawingNode . getDrawObjectType ( ) ) { Object obj = jaxbobj . getValue ( ) ; if ( obj instanceof DrawBlock ) DrawPrimitive ( ( DrawBlock ) obj , world ) ; else if ( obj instanceof DrawItem ) DrawPrimitive ( ( DrawItem ) obj , world ) ; else if ( obj instanceof DrawCuboid ) DrawPrimitive ( ( DrawCuboid ) obj , world ) ; else if ( obj instanceof DrawSphere ) DrawPrimitive ( ( DrawSphere ) obj , world ) ; else if ( obj instanceof DrawLine ) DrawPrimitive ( ( DrawLine ) obj , world ) ; else if ( obj instanceof DrawEntity ) DrawPrimitive ( ( DrawEntity ) obj , world ) ; else if ( obj instanceof DrawContainer ) DrawPrimitive ( ( DrawContainer ) obj , world ) ; else if ( obj instanceof DrawSign ) DrawPrimitive ( ( DrawSign ) obj , world ) ; else throw new Exception ( "Unsupported drawing primitive: " + obj . getClass ( ) . getName ( ) ) ; } endDrawing ( world ) ; } | Draws the specified drawing into the Minecraft world supplied . |
33,391 | private void DrawPrimitive ( DrawBlock b , World w ) throws Exception { XMLBlockState blockType = new XMLBlockState ( b . getType ( ) , b . getColour ( ) , b . getFace ( ) , b . getVariant ( ) ) ; if ( ! blockType . isValid ( ) ) throw new Exception ( "Unrecogised item type: " + b . getType ( ) . value ( ) ) ; BlockPos pos = new BlockPos ( b . getX ( ) , b . getY ( ) , b . getZ ( ) ) ; clearEntities ( w , b . getX ( ) , b . getY ( ) , b . getZ ( ) , b . getX ( ) + 1 , b . getY ( ) + 1 , b . getZ ( ) + 1 ) ; setBlockState ( w , pos , blockType ) ; } | Draw a single Minecraft block . |
33,392 | private void DrawPrimitive ( DrawSphere s , World w ) throws Exception { XMLBlockState blockType = new XMLBlockState ( s . getType ( ) , s . getColour ( ) , null , s . getVariant ( ) ) ; if ( ! blockType . isValid ( ) ) throw new Exception ( "Unrecognised block type: " + s . getType ( ) . value ( ) ) ; int radius = s . getRadius ( ) ; for ( int x = s . getX ( ) - radius ; x <= s . getX ( ) + radius ; x ++ ) { for ( int y = s . getY ( ) - radius ; y <= s . getY ( ) + radius ; y ++ ) { for ( int z = s . getZ ( ) - radius ; z <= s . getZ ( ) + radius ; z ++ ) { if ( ( z - s . getZ ( ) ) * ( z - s . getZ ( ) ) + ( y - s . getY ( ) ) * ( y - s . getY ( ) ) + ( x - s . getX ( ) ) * ( x - s . getX ( ) ) <= ( radius * radius ) ) { BlockPos pos = new BlockPos ( x , y , z ) ; setBlockState ( w , pos , blockType ) ; AxisAlignedBB aabb = new AxisAlignedBB ( pos , new BlockPos ( x + 1 , y + 1 , z + 1 ) ) ; clearEntities ( w , aabb . minX , aabb . minY , aabb . minZ , aabb . maxX , aabb . maxY , aabb . maxZ ) ; } } } } } | Draw a solid sphere made up of Minecraft blocks . |
33,393 | private void DrawPrimitive ( DrawEntity e , World w ) throws Exception { String oldEntityName = e . getType ( ) . getValue ( ) ; String id = null ; for ( EntityEntry ent : net . minecraftforge . fml . common . registry . ForgeRegistries . ENTITIES ) { if ( ent . getName ( ) . equals ( oldEntityName ) ) { id = ent . getRegistryName ( ) . toString ( ) ; break ; } } if ( id == null ) return ; NBTTagCompound nbttagcompound = new NBTTagCompound ( ) ; nbttagcompound . setString ( "id" , id ) ; nbttagcompound . setBoolean ( "PersistenceRequired" , true ) ; Entity entity ; try { entity = EntityList . createEntityFromNBT ( nbttagcompound , w ) ; if ( entity != null ) { positionEntity ( entity , e . getX ( ) . doubleValue ( ) , e . getY ( ) . doubleValue ( ) , e . getZ ( ) . doubleValue ( ) , e . getYaw ( ) . floatValue ( ) , e . getPitch ( ) . floatValue ( ) ) ; entity . setVelocity ( e . getXVel ( ) . doubleValue ( ) , e . getYVel ( ) . doubleValue ( ) , e . getZVel ( ) . doubleValue ( ) ) ; if ( entity instanceof EntityLivingBase ) { ( ( EntityLivingBase ) entity ) . rotationYaw = e . getYaw ( ) . floatValue ( ) ; ( ( EntityLivingBase ) entity ) . prevRotationYaw = e . getYaw ( ) . floatValue ( ) ; ( ( EntityLivingBase ) entity ) . prevRotationYawHead = e . getYaw ( ) . floatValue ( ) ; ( ( EntityLivingBase ) entity ) . rotationYawHead = e . getYaw ( ) . floatValue ( ) ; ( ( EntityLivingBase ) entity ) . prevRenderYawOffset = e . getYaw ( ) . floatValue ( ) ; ( ( EntityLivingBase ) entity ) . renderYawOffset = e . getYaw ( ) . floatValue ( ) ; } w . getBlockState ( entity . getPosition ( ) ) ; if ( ! w . spawnEntity ( entity ) ) { System . out . println ( "WARNING: Failed to spawn entity! Chunk not loaded?" ) ; } } } catch ( RuntimeException runtimeexception ) { throw new Exception ( "Couldn't create entity type: " + e . getType ( ) . getValue ( ) ) ; } } | Spawn a single entity at the specified position . |
33,394 | private void DrawPrimitive ( DrawCuboid c , World w ) throws Exception { XMLBlockState blockType = new XMLBlockState ( c . getType ( ) , c . getColour ( ) , c . getFace ( ) , c . getVariant ( ) ) ; if ( ! blockType . isValid ( ) ) throw new Exception ( "Unrecogised item type: " + c . getType ( ) . value ( ) ) ; int x1 = Math . min ( c . getX1 ( ) , c . getX2 ( ) ) ; int x2 = Math . max ( c . getX1 ( ) , c . getX2 ( ) ) ; int y1 = Math . min ( c . getY1 ( ) , c . getY2 ( ) ) ; int y2 = Math . max ( c . getY1 ( ) , c . getY2 ( ) ) ; int z1 = Math . min ( c . getZ1 ( ) , c . getZ2 ( ) ) ; int z2 = Math . max ( c . getZ1 ( ) , c . getZ2 ( ) ) ; clearEntities ( w , x1 , y1 , z1 , x2 + 1 , y2 + 1 , z2 + 1 ) ; for ( int x = x1 ; x <= x2 ; x ++ ) { for ( int y = y1 ; y <= y2 ; y ++ ) { for ( int z = z1 ; z <= z2 ; z ++ ) { BlockPos pos = new BlockPos ( x , y , z ) ; setBlockState ( w , pos , blockType ) ; } } } } | Draw a filled cuboid of Minecraft blocks of a single type . |
33,395 | public static ServerSocket getSocketInRange ( int minPort , int maxPort , boolean random ) { TCPUtils . Log ( Level . INFO , "Attempting to create a ServerSocket in range (" + minPort + "-" + maxPort + ( random ? ") at random..." : ") sequentially..." ) ) ; ServerSocket s = null ; int port = minPort - 1 ; Random r = new Random ( System . currentTimeMillis ( ) ) ; while ( s == null && port <= maxPort ) { if ( random ) port = minPort + r . nextInt ( maxPort - minPort ) ; else port ++ ; try { TCPUtils . Log ( Level . INFO , " - trying " + port + "..." ) ; s = new ServerSocket ( port ) ; TCPUtils . Log ( Level . INFO , "Succeeded!" ) ; return s ; } catch ( IOException e ) { TCPUtils . Log ( Level . INFO , " - failed: " + e ) ; } } TCPUtils . Log ( Level . SEVERE , "Could find no available port!" ) ; return null ; } | Choose a port from the specified range - either sequentially or at random . |
33,396 | public static float calcDistanceFromPlayerToPosition ( EntityPlayerSP player , Pos targetPos ) { double x = player . posX - targetPos . getX ( ) . doubleValue ( ) ; double y = player . posY - targetPos . getY ( ) . doubleValue ( ) ; double z = player . posZ - targetPos . getZ ( ) . doubleValue ( ) ; return ( float ) Math . sqrt ( x * x + y * y + z * z ) ; } | Calculate the Euclidean distance between the player and the target position . |
33,397 | protected boolean updateState ( ) { if ( ! overrideKeyboardInput ) { return false ; } mTicksSinceLastVelocityChange ++ ; if ( mTicksSinceLastVelocityChange <= mInertiaTicks ) { mVelocity += ( mTargetVelocity - mVelocity ) * ( ( float ) mTicksSinceLastVelocityChange / ( float ) mInertiaTicks ) ; } else { mVelocity = mTargetVelocity ; } this . overrideMovement . moveForward = mVelocity ; if ( this . overrideMovement . sneak ) { this . overrideMovement . moveStrafe = ( float ) ( ( double ) this . overrideMovement . moveStrafe * 0.3D ) ; this . overrideMovement . moveForward = ( float ) ( ( double ) this . overrideMovement . moveForward * 0.3D ) ; } updateYawAndPitch ( ) ; return true ; } | Called by our overridden MovementInputFromOptions class . |
33,398 | public void addQuitter ( IWantToQuit quitter ) { if ( this . quitters == null ) { this . quitters = new ArrayList < IWantToQuit > ( ) ; } this . quitters . add ( quitter ) ; } | Add another IWantToQuit object to the children . |
33,399 | public void start ( MissionInit missionInit , IVideoProducer videoProducer , VideoProducedObserver observer , MalmoEnvServer envServer ) { if ( videoProducer == null ) { return ; } videoProducer . prepare ( missionInit ) ; this . missionInit = missionInit ; this . videoProducer = videoProducer ; this . observer = observer ; this . envServer = envServer ; this . buffer = BufferUtils . createByteBuffer ( this . videoProducer . getRequiredBufferSize ( ) ) ; this . headerbuffer = ByteBuffer . allocate ( 20 ) . order ( ByteOrder . BIG_ENDIAN ) ; this . renderWidth = videoProducer . getWidth ( ) ; this . renderHeight = videoProducer . getHeight ( ) ; resizeIfNeeded ( ) ; Display . setResizable ( false ) ; ClientAgentConnection cac = missionInit . getClientAgentConnection ( ) ; if ( cac == null ) return ; String agentIPAddress = cac . getAgentIPAddress ( ) ; int agentPort = 0 ; switch ( videoProducer . getVideoType ( ) ) { case LUMINANCE : agentPort = cac . getAgentLuminancePort ( ) ; break ; case DEPTH_MAP : agentPort = cac . getAgentDepthPort ( ) ; break ; case VIDEO : agentPort = cac . getAgentVideoPort ( ) ; break ; case COLOUR_MAP : agentPort = cac . getAgentColourMapPort ( ) ; break ; } this . connection = new TCPSocketChannel ( agentIPAddress , agentPort , "vid" ) ; this . failedTCPSendCount = 0 ; try { MinecraftForge . EVENT_BUS . register ( this ) ; } catch ( Exception e ) { System . out . println ( "Failed to register video hook: " + e ) ; } this . isRunning = true ; } | Resize the rendering and start sending video over TCP . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.