idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
7,900
public void close ( ) { try { if ( this . isOpened ( ) == true ) { this . getTracePrintStream ( ) . println ( ) ; this . getTracePrintStream ( ) . printf ( " ) ; this . getTracePrintStream ( ) . printf ( " Time : %tc%n" , new Date ( ) ) ; System . out . println ( formatStreamErrorState ( ) + " Closing ..." ) ; this . getTracePrintStream ( ) . close ( ) ; this . getBufferedOutputStream ( ) . close ( ) ; this . fileOutputStream . close ( ) ; this . setOpened ( false ) ; } else { System . err . println ( "WARNING: Tracelog is closed already." ) ; } } catch ( IOException ex ) { ex . printStackTrace ( System . err ) ; } }
Closes the associated trace streams .
7,901
protected void checkLimit ( ) { synchronized ( this . getSyncObject ( ) ) { if ( this . byteLimit != - 1 && this . traceLogfile != null && this . traceLogfile . length ( ) > this . byteLimit ) { close ( ) ; int pos = this . traceLogfile . getAbsolutePath ( ) . lastIndexOf ( '\u002e' ) ; String splitFilename = this . traceLogfile . getAbsolutePath ( ) . substring ( 0 , pos ) + "." + ( ++ this . counter ) + ".log" ; File splitFile = new File ( splitFilename ) ; if ( splitFile . exists ( ) ) { if ( ! splitFile . delete ( ) ) System . err . printf ( "WARNING: Couldn't delete old file: %s%n" , splitFile . getName ( ) ) ; } this . traceLogfile . renameTo ( splitFile ) ; open ( ) ; } } }
Checks if the file size limit has been exceeded and splits the trace file if need be .
7,902
public HalCuriAugmenter register ( String name , String href ) { Link link = new Link ( href ) . setName ( name ) ; return register ( link ) ; }
Registers a CURI link by the given name and HREF .
7,903
public HalCuriAugmenter augment ( HalResource hal ) { Set < String > existingCurieNames = getExistingCurieNames ( hal ) ; Set < Link > curieLinks = getCuriLinks ( hal , existingCurieNames ) ; hal . addLinks ( LINK_RELATION_CURIES , curieLinks ) ; return this ; }
Augments a HAL resource by CURI links . Only adds CURIES being registered and referenced in the HAL resource . Will not override existing CURI links .
7,904
protected synchronized List < Message > getAllMessages ( final Follower follower ) { final int end = this . getEndingMessageId ( follower ) ; final int start = Math . max ( this . messages . getFirstPosition ( ) , this . getStartingMessageId ( follower ) ) ; if ( start > end ) { return Collections . unmodifiableList ( Collections . emptyList ( ) ) ; } else { return Collections . unmodifiableList ( this . messages . getFromRange ( start , end + 1 ) ) ; } }
Return all messages that have been sent to the follower from its start until either its termination or to this moment whichever is relevant .
7,905
private synchronized int getEndingMessageId ( final Follower follower ) { if ( this . isFollowerActive ( follower ) ) { return this . messages . getLatestPosition ( ) ; } else if ( this . isFollowerTerminated ( follower ) ) { return this . terminatedFollowerRanges . get ( follower ) [ 1 ] ; } else { throw new IllegalStateException ( "Follower never before seen." ) ; } }
Get index of the last plus one message that the follower has access to .
7,906
protected synchronized int getFirstReachableMessageId ( ) { final boolean followersRunning = ! this . runningFollowerStartMarks . isEmpty ( ) ; if ( ! followersRunning && this . terminatedFollowerRanges . isEmpty ( ) ) { return - 1 ; } final IntSortedSet set = new IntAVLTreeSet ( this . runningFollowerStartMarks . values ( ) ) ; if ( ! set . isEmpty ( ) ) { final int first = this . messages . getFirstPosition ( ) ; if ( set . firstInt ( ) <= first ) { return first ; } } set . addAll ( this . terminatedFollowerRanges . values ( ) . stream ( ) . map ( pair -> pair [ 0 ] ) . collect ( Collectors . toList ( ) ) ) ; return set . firstInt ( ) ; }
Will crawl the weak hash maps and make sure we always have the latest information on the availability of messages .
7,907
private synchronized int getStartingMessageId ( final Follower follower ) { if ( this . isFollowerActive ( follower ) ) { return this . runningFollowerStartMarks . getInt ( follower ) ; } else if ( this . isFollowerTerminated ( follower ) ) { return this . terminatedFollowerRanges . get ( follower ) [ 0 ] ; } else { throw new IllegalStateException ( "Follower never before seen." ) ; } }
For a given follower return the starting mark .
7,908
public synchronized void logWatchTerminated ( ) { final Iterable < Follower > followersToTerminate = new ObjectLinkedOpenHashSet < > ( this . runningFollowerStartMarks . keySet ( ) ) ; followersToTerminate . forEach ( this :: followerTerminated ) ; this . sweeping . stop ( ) ; }
Will mean the end of the storage including the termination of sweeping .
7,909
public static Properties getProperties ( URL url ) throws IOException { Properties properties = new Properties ( ) ; InputStream inputStream = url . openStream ( ) ; try { properties . load ( inputStream ) ; } finally { inputStream . close ( ) ; } return properties ; }
Load values from a URL .
7,910
public void drawLink ( Link link ) { List < Device > linkedDevices = link . getLinkedDevices ( ) ; for ( int i = 0 ; i < linkedDevices . size ( ) ; i ++ ) { Device from = linkedDevices . get ( i ) ; for ( int j = i + 1 ; j < linkedDevices . size ( ) ; j ++ ) { Device to = linkedDevices . get ( j ) ; Edge e = new Edge ( from , to , link ) ; links . addEdge ( e ) ; } } }
To draw a link
7,911
public < T > TableFormatter header ( Collection < ? extends T > collection ) { header . addAll ( collection ) ; longestCell = ( int ) Math . max ( longestCell , collection . stream ( ) . mapToDouble ( o -> o . toString ( ) . length ( ) + 2 ) . max ( ) . orElse ( 0 ) ) ; return this ; }
Header table formatter .
7,912
public TableFormatter content ( Collection < ? > collection ) { this . content . add ( new ArrayList < > ( collection ) ) ; longestCell = ( int ) Math . max ( longestCell , collection . stream ( ) . mapToDouble ( o -> { if ( o instanceof Number ) { return Math . max ( MIN_CELL_WIDTH , length ( Cast . as ( o ) ) ) ; } else { return Math . max ( MIN_CELL_WIDTH , o . toString ( ) . length ( ) + 2 ) ; } } ) . max ( ) . orElse ( 0 ) ) ; longestRow = Math . max ( longestRow , collection . size ( ) ) ; return this ; }
Content table formatter .
7,913
public final void execute ( ) throws ParseException , GenerateException { LOG . info ( "Executing full build" ) ; enhanceClasspath ( ) ; cleanFolders ( ) ; final Parsers parsers = config . getParsers ( ) ; if ( parsers == null ) { LOG . warn ( "No parsers element" ) ; } else { final List < ParserConfig > parserConfigs = parsers . getList ( ) ; if ( parserConfigs == null ) { LOG . warn ( "No parsers configured" ) ; } else { for ( final ParserConfig pc : parserConfigs ) { final Parser < Object > parser = pc . getParser ( ) ; final Object model = parser . parse ( ) ; final List < GeneratorConfig > generatorConfigs = config . findGeneratorsForParser ( pc . getName ( ) ) ; for ( final GeneratorConfig gc : generatorConfigs ) { final Generator < Object > generator = gc . getGenerator ( ) ; generator . generate ( model , false ) ; } } } } }
Parse and generate .
7,914
public FileFilter getFileFilter ( ) { if ( fileFilter == null ) { final List < IOFileFilter > filters = new ArrayList < > ( ) ; final Parsers parsers = config . getParsers ( ) ; if ( parsers != null ) { final List < ParserConfig > parserConfigs = parsers . getList ( ) ; if ( parserConfigs != null ) { for ( final ParserConfig pc : parserConfigs ) { final Parser < Object > pars = pc . getParser ( ) ; if ( pars instanceof IncrementalParser ) { final IncrementalParser < ? > parser = ( IncrementalParser < ? > ) pars ; filters . add ( parser . getFileFilter ( ) ) ; } } } } fileFilter = new OrFileFilter ( filters ) ; } return fileFilter ; }
Returns a file filter that combines all filters for all incremental parsers . It should be used for selecting the appropriate files .
7,915
public final void execute ( final Set < File > files ) throws ParseException , GenerateException { Contract . requireArgNotNull ( "files" , files ) ; LOG . info ( "Executing incremental build ({} files)" , files . size ( ) ) ; if ( LOG . isDebugEnabled ( ) ) { for ( final File file : files ) { LOG . debug ( file . toString ( ) ) ; } } if ( files . size ( ) == 0 ) { return ; } final Parsers parsers = config . getParsers ( ) ; if ( parsers == null ) { LOG . warn ( "No parsers element" ) ; } else { final List < ParserConfig > parserConfigs = parsers . getList ( ) ; if ( parserConfigs == null ) { LOG . warn ( "No parsers configured" ) ; } else { for ( final ParserConfig pc : parserConfigs ) { final Parser < Object > pars = pc . getParser ( ) ; if ( pars instanceof IncrementalParser ) { final IncrementalParser < ? > parser = ( IncrementalParser < ? > ) pars ; final Object model = parser . parse ( files ) ; final List < GeneratorConfig > generatorConfigs = config . findGeneratorsForParser ( pc . getName ( ) ) ; for ( final GeneratorConfig gc : generatorConfigs ) { final Generator < Object > generator = gc . getGenerator ( ) ; generator . generate ( model , true ) ; } } else { LOG . debug ( "No incremental parser: {}" , pars . getClass ( ) . getName ( ) ) ; } } } } }
Incremental parse and generate . The class loader of this class will be used .
7,916
public byte [ ] parse ( ) { this . addEntity ( ) ; this . addClassDefaultConstructor ( ) ; this . addClassLevelAnnotations ( ) ; this . addFields ( ) ; this . addMethods ( ) ; this . cw . visitEnd ( ) ; return this . cw . toByteArray ( ) ; }
Mount the class and generate it definition in byte array .
7,917
public static URI getUri ( UriInfo uriInfo , HttpServletRequest req , String path ) { String suffix = "" ; if ( req . getRequestURI ( ) . endsWith ( ".json" ) ) { suffix = ".json" ; } else if ( req . getRequestURI ( ) . endsWith ( ".xml" ) ) { suffix = ".xml" ; } return URI . create ( uriInfo . getBaseUri ( ) + "/" + path + suffix ) ; }
Gets a full URI for the given path based on the request URI .
7,918
public static String getId ( URI uri ) { String s = uri . toString ( ) ; return s . substring ( s . lastIndexOf ( "/" ) + 1 ) ; }
Gets the id for the given task set store user or taskLog URI .
7,919
public final void addArtifact ( final Artifact artifact ) { Contract . requireArgNotNull ( "artifact" , artifact ) ; if ( artifacts == null ) { artifacts = new ArrayList < > ( ) ; } artifacts . add ( artifact ) ; }
Adds a artifact to the list . If the list does not exist it s created .
7,920
public final String getDefProject ( ) { if ( getProject ( ) == null ) { if ( parent == null ) { return null ; } return parent . getProject ( ) ; } return getProject ( ) ; }
Returns the defined project from this object or any of it s parents .
7,921
public final String getDefFolder ( ) { if ( getFolder ( ) == null ) { if ( parent == null ) { return null ; } return parent . getFolder ( ) ; } return getFolder ( ) ; }
Returns the defined folder from this object or any of it s parents .
7,922
@ SuppressWarnings ( "unchecked" ) public final Generator < Object > getGenerator ( ) { if ( generator != null ) { return generator ; } LOG . info ( "Creating generator: {}" , className ) ; if ( className == null ) { throw new IllegalStateException ( "Class name was not set: " + getName ( ) ) ; } if ( context == null ) { throw new IllegalStateException ( "Context class loader was not set: " + getName ( ) + " / " + className ) ; } final Object obj = Utils4J . createInstance ( className , context . getClassLoader ( ) ) ; if ( ! ( obj instanceof Generator < ? > ) ) { throw new IllegalStateException ( "Expected class to be of type '" + Generator . class . getName ( ) + "', but was: " + className ) ; } generator = ( Generator < Object > ) obj ; generator . initialize ( this ) ; return generator ; }
Returns an existing generator instance or creates a new one if it s the first call to this method .
7,923
protected static Module parse ( final File moduleXml ) throws Exception { InputStream is = new FileInputStream ( moduleXml ) ; try { Document document = parseXml ( is ) ; Element root = document . getDocumentElement ( ) ; ModuleIdentifier main = getModuleIdentifier ( root ) ; Module module = new Module ( main ) ; Element dependencies = getChildElement ( root , "dependencies" ) ; if ( dependencies != null ) { for ( Element dependency : getElements ( dependencies , "module" ) ) { module . addDependency ( getModuleIdentifier ( dependency ) ) ; } } return module ; } finally { is . close ( ) ; } }
Parse the module . xml file .
7,924
protected static ModuleIdentifier getModuleIdentifier ( final Element root ) { return new ModuleIdentifier ( root . getAttribute ( "name" ) , root . getAttribute ( "slot" ) , Boolean . parseBoolean ( root . getAttribute ( "optional" ) ) , Boolean . parseBoolean ( root . getAttribute ( "export" ) ) ) ; }
ModuleIdentifier from XML element .
7,925
protected static Document parseXml ( final InputStream inputStream ) throws ParserConfigurationException , SAXException , IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dBuilder = dbFactory . newDocumentBuilder ( ) ; Document doc = dBuilder . parse ( inputStream ) ; doc . getDocumentElement ( ) . normalize ( ) ; return doc ; }
Parse module . xml from an input stream .
7,926
protected static List < Element > getElements ( final Element parent , final String tagName ) { List < Element > elements = new ArrayList < Element > ( ) ; NodeList nodes = parent . getElementsByTagName ( tagName ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { org . w3c . dom . Node node = nodes . item ( i ) ; if ( node instanceof Element ) { elements . add ( Element . class . cast ( node ) ) ; } } return elements ; }
Finds child elements in DOM .
7,927
protected static Element getChildElement ( final Element parent , final String tagName ) { List < Element > elements = getElements ( parent , tagName ) ; if ( elements . size ( ) > 0 ) { return elements . get ( 0 ) ; } else { return null ; } }
Get a single child element .
7,928
public void addTimeChart ( String chartID , String xAxisLabel , String yAxisLabel ) throws ShanksException { Scenario2DPortrayal scenarioPortrayal = ( Scenario2DPortrayal ) this . getSimulation ( ) . getScenarioPortrayal ( ) ; scenarioPortrayal . addTimeChart ( chartID , xAxisLabel , yAxisLabel ) ; }
Add a time chart to the simulation
7,929
public void removeTimeChart ( String chartID ) throws ShanksException { Scenario2DPortrayal scenarioPortrayal = ( Scenario2DPortrayal ) this . getSimulation ( ) . getScenarioPortrayal ( ) ; scenarioPortrayal . removeTimeChart ( chartID ) ; }
Remove a time chart to the simulation
7,930
public void addHistogram ( String histogramID , String xAxisLabel , String yAxisLabel ) throws ShanksException { Scenario2DPortrayal scenarioPortrayal = ( Scenario2DPortrayal ) this . getSimulation ( ) . getScenarioPortrayal ( ) ; scenarioPortrayal . addHistogram ( histogramID , xAxisLabel , yAxisLabel ) ; }
Add a Histogram to the simulation
7,931
protected void registerIfNamed ( Class < ? > from , Serializer < ? > serializer ) { if ( from . isAnnotationPresent ( Named . class ) ) { Named named = from . getAnnotation ( Named . class ) ; QualifiedName key = new QualifiedName ( named . namespace ( ) , named . name ( ) ) ; nameToSerializer . put ( key , serializer ) ; serializerToName . put ( serializer , key ) ; } }
Register the given serializer if it has a name .
7,932
public Expression next ( int precedence ) throws ParseException { ParserToken token ; Expression result ; do { token = tokenStream . consume ( ) ; if ( token == null ) { return null ; } result = grammar . parse ( this , token ) ; } while ( result == null ) ; while ( grammar . skip ( tokenStream . lookAhead ( 0 ) ) ) { tokenStream . consume ( ) ; } while ( precedence < grammar . precedence ( tokenStream . lookAhead ( 0 ) ) ) { token = tokenStream . consume ( ) ; result = grammar . parse ( this , result , token ) ; } return result ; }
Parses the token stream to get the next expression
7,933
private long readLines ( final RandomAccessFile reader ) throws IOException { final ByteArrayOutputStream lineBuf = new ByteArrayOutputStream ( 64 ) ; long pos = reader . getFilePointer ( ) ; long rePos = pos ; int num ; boolean seenCR = false ; while ( ( num = reader . read ( this . inbuf ) ) != - 1 ) { for ( int i = 0 ; i < num ; i ++ ) { final byte ch = this . inbuf [ i ] ; switch ( ch ) { case '\n' : seenCR = false ; this . listener . handle ( new String ( lineBuf . toByteArray ( ) , this . cset ) ) ; lineBuf . reset ( ) ; rePos = pos + i + 1 ; break ; case '\r' : if ( seenCR ) { lineBuf . write ( '\r' ) ; } seenCR = true ; break ; default : if ( seenCR ) { seenCR = false ; this . listener . handle ( new String ( lineBuf . toByteArray ( ) , this . cset ) ) ; lineBuf . reset ( ) ; rePos = pos + i + 1 ; } lineBuf . write ( ch ) ; } } pos = reader . getFilePointer ( ) ; } IOUtils . closeQuietly ( lineBuf ) ; reader . seek ( rePos ) ; return rePos ; }
Read new lines .
7,934
List < ColumnMetadata > getFieldMetaData ( ) { return columnsMetadata . entrySet ( ) . stream ( ) . map ( entry -> entry . getValue ( ) ) . collect ( Collectors . toList ( ) ) ; }
Get field metadata
7,935
private String getServiceIdFromMavenBundlePlugin ( ) { Plugin bundlePlugin = project . getBuildPlugins ( ) . stream ( ) . filter ( plugin -> StringUtils . equals ( plugin . getKey ( ) , MAVEN_BUNDLE_PLUGIN_ID ) ) . findFirst ( ) . orElse ( null ) ; if ( bundlePlugin != null ) { Xpp3Dom configuration = ( Xpp3Dom ) bundlePlugin . getConfiguration ( ) ; if ( configuration != null ) { Xpp3Dom instructions = configuration . getChild ( "instructions" ) ; if ( instructions != null ) { Xpp3Dom applicationPath = instructions . getChild ( ApplicationPath . HEADER_APPLICATON_PATH ) ; if ( applicationPath != null ) { return applicationPath . getValue ( ) ; } } } } return null ; }
Tries to detect the service id automatically from maven bundle plugin definition in same POM .
7,936
private Service getServiceInfos ( ClassLoader compileClassLoader ) { Service service = new Service ( ) ; service . setServiceId ( serviceId ) ; service . setName ( project . getName ( ) ) ; JavaProjectBuilder builder = new JavaProjectBuilder ( ) ; builder . addSourceTree ( new File ( source ) ) ; JavaClass serviceInfo = builder . getSources ( ) . stream ( ) . flatMap ( javaSource -> javaSource . getClasses ( ) . stream ( ) ) . filter ( javaClass -> hasAnnotation ( javaClass , ServiceDoc . class ) ) . findFirst ( ) . orElse ( null ) ; if ( serviceInfo != null ) { service . setDescriptionMarkup ( serviceInfo . getComment ( ) ) ; serviceInfo . getFields ( ) . stream ( ) . filter ( field -> hasAnnotation ( field , LinkRelationDoc . class ) ) . map ( field -> toLinkRelation ( serviceInfo , field , compileClassLoader ) ) . forEach ( service :: addLinkRelation ) ; } service . resolve ( ) ; return service ; }
Get service infos from current maven project .
7,937
private String buildJsonSchemaRefForModel ( Class < ? > modelClass , File artifactFile ) { try { ZipFile zipFile = new ZipFile ( artifactFile ) ; String halDocsDomainPath = getHalDocsDomainPath ( zipFile ) ; if ( halDocsDomainPath != null && hasJsonSchemaFile ( zipFile , modelClass ) ) { return JsonSchemaBundleTracker . SCHEMA_URI_PREFIX + halDocsDomainPath + "/" + modelClass . getName ( ) + ".json" ; } return null ; } catch ( IOException ex ) { throw new RuntimeException ( "Unable to read artifact file: " + artifactFile . getAbsolutePath ( ) + "\n" + ex . getMessage ( ) , ex ) ; } }
Check if JAR file has a doc domain path and corresponding schema file and then builds a documenation path for it .
7,938
private boolean hasAnnotation ( JavaAnnotatedElement clazz , Class < ? extends Annotation > annotationClazz ) { return clazz . getAnnotations ( ) . stream ( ) . filter ( item -> item . getType ( ) . isA ( annotationClazz . getName ( ) ) ) . count ( ) > 0 ; }
Checks if the given element has an annotation set .
7,939
@ SuppressWarnings ( "unchecked" ) private < T > T getStaticFieldValue ( JavaClass javaClazz , JavaField javaField , ClassLoader compileClassLoader , Class < T > fieldType ) { try { Class < ? > clazz = compileClassLoader . loadClass ( javaClazz . getFullyQualifiedName ( ) ) ; Field field = clazz . getField ( javaField . getName ( ) ) ; return ( T ) field . get ( fieldType ) ; } catch ( ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex ) { throw new RuntimeException ( "Unable to get contanst value of field '" + javaClazz . getName ( ) + "#" + javaField . getName ( ) + ":\n" + ex . getMessage ( ) , ex ) ; } }
Get constant field value .
7,940
private < T extends Annotation > T getAnnotation ( JavaClass javaClazz , JavaField javaField , ClassLoader compileClassLoader , Class < T > annotationType ) { try { Class < ? > clazz = compileClassLoader . loadClass ( javaClazz . getFullyQualifiedName ( ) ) ; Field field = clazz . getField ( javaField . getName ( ) ) ; return field . getAnnotation ( annotationType ) ; } catch ( ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException ex ) { throw new RuntimeException ( "Unable to get contanst value of field '" + javaClazz . getName ( ) + "#" + javaField . getName ( ) + ":\n" + ex . getMessage ( ) , ex ) ; } }
Get annotation for field .
7,941
@ SuppressWarnings ( "unchecked" ) public static < K , V > Cache < K , V > getGlobalCache ( ) { if ( caches . containsKey ( GLOBAL_CACHE ) ) { return Cast . as ( caches . get ( GLOBAL_CACHE ) ) ; } return register ( getCacheSpec ( GLOBAL_CACHE ) ) ; }
Gets global cache .
7,942
public void log ( final LogEntry entry ) { if ( entry . getLevel ( ) . compareTo ( this . level ) < 0 ) { return ; } if ( ! this . filters . isEmpty ( ) ) { for ( LogFilter filter : this . filters ) { if ( ! filter . accept ( entry ) ) { return ; } } } this . publish ( entry ) ; }
Checks if the LogLevel is higher than the set LogLevel and all registered Filters pass and then publishes the LogEntry
7,943
public static < K , V > CacheSpec < K , V > from ( String specification ) { return CacheSpec . < K , V > create ( ) . fromString ( specification ) ; }
From cache spec .
7,944
public CacheSpec < K , V > loadingFunction ( Function < K , V > loadingFunction ) { this . cacheFunction = loadingFunction ; return this ; }
Loading function cache spec .
7,945
public CacheEngine getEngine ( ) { if ( StringUtils . isNullOrBlank ( cacheEngine ) ) { return CacheEngines . get ( "Guava" ) ; } return CacheEngines . get ( cacheEngine ) ; }
Gets cache type .
7,946
public < T extends CacheSpec < K , V > > T concurrencyLevel ( int concurrencyLevel ) { checkArgument ( concurrencyLevel > 0 , "Concurrency Level must be > 0" ) ; this . concurrencyLevel = concurrencyLevel ; return Cast . as ( this ) ; }
Concurrency level t .
7,947
public < T extends CacheSpec < K , V > > T initialCapacity ( int initialCapacity ) { checkArgument ( initialCapacity > 0 , "Capacity must be > 0" ) ; this . initialCapacity = initialCapacity ; return Cast . as ( this ) ; }
Sets the initial capacity
7,948
public < T extends CacheSpec < K , V > > T weakValues ( ) { this . weakValues = true ; return Cast . as ( this ) ; }
Sets to use weak values
7,949
public < T extends CacheSpec < K , V > > T weakKeys ( ) { this . weakKeys = true ; return Cast . as ( this ) ; }
Sets to use weak keys
7,950
public < T extends CacheSpec < K , V > > T expiresAfterWrite ( String duration ) { this . expiresAfterWrite = convertStringToTime ( duration ) ; return Cast . as ( this ) ; }
The time in milliseconds after write that an item is removed
7,951
public < T extends CacheSpec < K , V > > T name ( String name ) { this . name = name ; return Cast . as ( this ) ; }
Sets the name
7,952
public < T extends CacheSpec < K , V > > T removalListener ( RemovalListener < K , V > listener ) { this . removalListener = listener ; return Cast . as ( this ) ; }
Sets the removal listener
7,953
private static Class < ? > loadClass ( final String className ) throws ClassNotFoundException { ClassLoader ctxCL = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( ctxCL == null ) { return Class . forName ( className ) ; } return ctxCL . loadClass ( className ) ; }
Loads the class specified by name using the Thread s context class loader - if defined - otherwise the default classloader .
7,954
public synchronized JarFile getFilteredJarFile ( JarEntryFilter ... filters ) throws IOException { return new JarFile ( this . rootFile , this . pathFromRoot , this . data , this . entries , filters ) ; }
Return a new jar based on the filtered contents of this file .
7,955
public static void main ( String [ ] args ) throws IOException , FontFormatException , URISyntaxException { CliArgumentParser parser = new CliArgumentParser ( args ) ; LwjgFontFactory lwjgFont = new LwjgFontFactory ( parser . get ( _p ) ) ; if ( parser . hasArgument ( _x ) ) { lwjgFont . extractCharacterFiles ( ) ; } else if ( parser . hasArgument ( _v ) ) { lwjgFont . printVersion ( ) ; } else if ( parser . hasArgument ( _l ) ) { SystemFont . listLogicalFont ( ) ; } else if ( parser . hasFontSettings ( ) ) { for ( FontSetting fontSetting : parser . listFontSettings ( ) ) { lwjgFont . create ( fontSetting ) ; } lwjgFont . makePackage ( ) ; lwjgFont . writeProcessLog ( ) ; } }
Main method of LWJGFont in command line mode .
7,956
private static Queue < String > removePrefix ( final List < String > input ) { if ( input . size ( ) < 2 ) { return new LinkedList < > ( input ) ; } String resultingPrefix = "" ; final String previousGreatestCommonPrefix = input . get ( 0 ) . trim ( ) ; String greatestCommonPrefix = "" ; for ( int i = 1 ; i < input . size ( ) ; i ++ ) { final String previousLine = input . get ( i - 1 ) . trim ( ) ; final String currentLine = input . get ( i ) . trim ( ) ; greatestCommonPrefix = ExceptionParser . greatestCommonPrefix ( previousLine , currentLine ) ; resultingPrefix = ExceptionParser . greatestCommonPrefix ( previousGreatestCommonPrefix , greatestCommonPrefix ) ; if ( resultingPrefix . length ( ) == 0 ) { break ; } } final int prefixLength = resultingPrefix . length ( ) ; final boolean hasPrefix = prefixLength > 0 ; final Queue < String > result = new LinkedList < > ( ) ; for ( final String line : input ) { final String line2 = line . trim ( ) ; if ( hasPrefix ) { result . add ( line2 . substring ( prefixLength ) ) ; } else { result . add ( line2 ) ; } } return result ; }
Identifies and removes the common prefix - the longest beginning substring that all the lines share .
7,957
public synchronized Collection < ExceptionLine > parse ( final Collection < String > input ) throws ExceptionParseException { this . parsedLines . clear ( ) ; final Queue < String > linesFromInput = ExceptionParser . removePrefix ( new LinkedList < > ( input ) ) ; LineType previousLineType = LineType . PRE_START ; String currentLine = null ; boolean isFirstLine = true ; while ( ! linesFromInput . isEmpty ( ) ) { currentLine = linesFromInput . poll ( ) ; previousLineType = this . parseLine ( previousLineType , currentLine ) ; if ( isFirstLine ) { if ( ! previousLineType . isAcceptableAsFirstLine ( ) ) { throw new ExceptionParseException ( currentLine , "Invalid line type detected at the beginning: " + previousLineType ) ; } isFirstLine = false ; } } if ( ! previousLineType . isAcceptableAsLastLine ( ) ) { throw new ExceptionParseException ( currentLine , "Invalid line type detected at the end: " + previousLineType ) ; } return Collections . unmodifiableCollection ( new LinkedList < > ( this . parsedLines ) ) ; }
Browsers through a random log and returns first exception stack trace it could find .
7,958
private LineType parseLine ( final LineType previousLineType , final String line ) throws ExceptionParseException { switch ( previousLineType ) { case PRE_START : return this . parseLine ( line , LineType . CAUSE , LineType . PRE_START ) ; case CAUSE : case SUB_CAUSE : case PRE_STACK_TRACE : return this . parseLine ( line , LineType . STACK_TRACE , LineType . PRE_STACK_TRACE ) ; case STACK_TRACE : return this . parseLine ( line , LineType . STACK_TRACE , LineType . STACK_TRACE_END , LineType . SUB_CAUSE ) ; case STACK_TRACE_END : return this . parseLine ( line , LineType . SUB_CAUSE , LineType . POST_END ) ; case POST_END : return this . parseLine ( line , LineType . POST_END ) ; default : throw new IllegalArgumentException ( "Unsupported line type: " + previousLineType ) ; } }
Parse one line in the log .
7,959
private LineType parseLine ( final String line , final LineType ... allowedLineTypes ) throws ExceptionParseException { for ( final LineType possibleType : allowedLineTypes ) { if ( ( possibleType == LineType . POST_END ) || ( possibleType == LineType . PRE_START ) ) { return possibleType ; } final ExceptionLine parsedLine = possibleType . parse ( line ) ; if ( parsedLine != null ) { if ( possibleType == LineType . PRE_STACK_TRACE ) { final ExceptionLine currentTop = this . parsedLines . remove ( this . parsedLines . size ( ) - 1 ) ; if ( ! ( ( currentTop instanceof CauseLine ) && ( parsedLine instanceof PlainTextLine ) ) ) { throw new IllegalStateException ( "Garbage in the exception message." ) ; } this . parsedLines . add ( new CauseLine ( ( CauseLine ) currentTop , ( PlainTextLine ) parsedLine ) ) ; } else { this . parsedLines . add ( parsedLine ) ; } return possibleType ; } } throw new ExceptionParseException ( line , "Line not any of the expected types: " + Arrays . toString ( allowedLineTypes ) ) ; }
Parse one line in the log when knowing the types of lines acceptable at this point in the log .
7,960
public boolean valueEquals ( ConcatVectorTable other , double tolerance ) { if ( ! Arrays . equals ( other . getDimensions ( ) , getDimensions ( ) ) ) return false ; for ( int [ ] assignment : this ) { if ( ! getAssignmentValue ( assignment ) . get ( ) . valueEquals ( other . getAssignmentValue ( assignment ) . get ( ) , tolerance ) ) { return false ; } } return true ; }
Deep comparison for equality of value plus tolerance for every concatvector in the table plus dimensional arrangement . This is mostly useful for testing .
7,961
public static Val of ( Object o ) { if ( o != null && o instanceof Val ) { return Cast . as ( o ) ; } return new Val ( o ) ; }
Convenience method for creating a Convertible Object
7,962
@ SuppressWarnings ( "unchecked" ) public < T > Class < T > asClass ( Class < T > defaultValue ) { return as ( Class . class , defaultValue ) ; }
As class .
7,963
@ SuppressWarnings ( "unchecked" ) public < T > List < T > asList ( Class < T > itemType ) { return asCollection ( List . class , itemType ) ; }
Converts the object to a List
7,964
public < T > Set < T > asSet ( Class < T > itemType ) { return asCollection ( Set . class , itemType ) ; }
Converts the object to a Set
7,965
public < T > T [ ] asArray ( Class < T > clazz ) { return Cast . as ( convert ( toConvert , Array . newInstance ( clazz , 0 ) . getClass ( ) ) ) ; }
Converts an object into an array of objects
7,966
public int precedence ( ParserToken token ) { if ( isInfix ( token ) ) { return infixHandlers . get ( token . type ) . precedence ( ) ; } return 0 ; }
Gets the precedence of the associated infix handler .
7,967
public boolean skip ( ParserToken token ) { if ( token == null ) { return false ; } if ( isPrefix ( token ) ) { if ( prefixHandlers . containsKey ( token . getType ( ) ) ) { return prefixHandlers . get ( token . getType ( ) ) instanceof PrefixSkipHandler ; } else { return prefixSkipHandler != null ; } } return false ; }
Determines if the given the token should be skipped or not
7,968
public Filter add ( String attribute , Operator op , Object value ) { return add ( new Predicate ( attribute , op , value ) ) ; }
Adds the given Predicate to the list of predicates .
7,969
private static void writeOutContent ( final byte [ ] data , final String filename , final String mime , final boolean asAttachment ) { try { final HttpServletResponse response = ( HttpServletResponse ) FacesContext . getCurrentInstance ( ) . getExternalContext ( ) . getResponse ( ) ; response . setContentType ( mime ) ; if ( asAttachment ) response . addHeader ( "Content-Disposition" , "attachment;filename=" + filename ) ; response . setContentLength ( data . length ) ; final OutputStream writer = response . getOutputStream ( ) ; writer . write ( data ) ; writer . flush ( ) ; writer . close ( ) ; FacesContext . getCurrentInstance ( ) . responseComplete ( ) ; } catch ( final Exception ex ) { LOG . error ( "Unable to write content to HTTP Output Stream" , ex ) ; } }
Used to send arbitrary to the user .
7,970
public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException , IOException { this . doProcess ( req , res ) ; }
Process an HTML get .
7,971
public void remove ( ) { if ( context == null ) { throw new IllegalStateException ( "link with href=" + getHref ( ) + " can not be removed, because it's not part of a HAL resource tree" ) ; } ListMultimap < String , Link > allLinks = context . getLinks ( ) ; for ( String relation : allLinks . keySet ( ) ) { List < Link > links = allLinks . get ( relation ) ; for ( int i = 0 ; i < links . size ( ) ; i ++ ) { if ( links . get ( i ) . getModel ( ) == model ) { context . removeLink ( relation , i ) ; context = null ; return ; } } } throw new IllegalStateException ( "the last known context resource of link with href=" + getHref ( ) + " no longer contains this link" ) ; }
Removes this link from its context resource s JSON representation
7,972
public final void addBin ( final BinClasspathEntry entry ) { Contract . requireArgNotNull ( "entry" , entry ) ; if ( binList == null ) { binList = new ArrayList < > ( ) ; } binList . add ( entry ) ; }
Adds a classes directory to the list . If the list does not exist it s created .
7,973
public ClassFinder addClasspath ( ) { try { String path = System . getProperty ( "java.class.path" ) ; StringTokenizer tok = new StringTokenizer ( path , File . pathSeparator ) ; while ( tok . hasMoreTokens ( ) ) add ( new File ( tok . nextToken ( ) ) ) ; } catch ( Exception ex ) { log . error ( "Unable to get class path" , ex ) ; } return this ; }
Add the contents of the system classpath for classes .
7,974
public ClassFinder add ( File file ) { log . info ( "Adding file to look into: " + file . getAbsolutePath ( ) ) ; if ( fileCanContainClasses ( file ) ) { String absPath = file . getAbsolutePath ( ) ; if ( placesToSearch . get ( absPath ) == null ) { placesToSearch . put ( absPath , file ) ; for ( AdditionalResourceLoader resourceLoader : resourceLoaders ) { if ( resourceLoader . canLoadAdditional ( file ) ) resourceLoader . loadAdditional ( file , this ) ; } } } else { log . info ( "The given path '" + file . getAbsolutePath ( ) + "' cannot contain classes!" ) ; } return this ; }
Add a jar file zip file or directory to the list of places to search for classes .
7,975
public int getCurrentStackSize ( ) { int stackSize = - 1 ; if ( this . tracingContextMap . containsKey ( Thread . currentThread ( ) ) ) stackSize = this . tracingContextMap . get ( Thread . currentThread ( ) ) . getMethodStack ( ) . size ( ) ; return stackSize ; }
Returns the stack size of the current thread . The value - 1 indicates that the current thread isn t registered .
7,976
public static void addNotification ( Notification n ) { NotificationManager . notifications . add ( n ) ; logger . fine ( "New notification added to notifications list. There is currently: " + notifications . size ( ) + " notifications\n Notification added: " + NotificationManager . notifications . get ( NotificationManager . notifications . size ( ) - 1 ) ) ; }
The user can use this method to add notifications manually .
7,977
@ SuppressWarnings ( "unchecked" ) public static void addNotification ( Event e , String interaction ) { NotificationManager . notifications . add ( new InteractionNotification ( getNotificationID ( ) , NotificationManager . sim . getSchedule ( ) . getSteps ( ) , e . getLauncher ( ) , interaction , ( List < Object > ) e . getAffected ( ) ) ) ; logger . fine ( "New notification added to notifications list. There is currently: " + notifications . size ( ) + " notifications\n Notification added: " + NotificationManager . notifications . get ( NotificationManager . notifications . size ( ) - 1 ) ) ; }
Whenever a new event triggers it will use this method to add the corresponding notification to the notification lists .
7,978
private static String getNotificationID ( ) { NotificationManager . ID_COUNTER = NotificationManager . ID_COUNTER + 1 ; logger . fine ( "Notifications identifier counter: " + ID_COUNTER ) ; return "Notification#" + ( NotificationManager . ID_COUNTER ) ; }
Each new notification needs a notification - ID . NotificationManager monitors the number of notifications and generates a unique identifier for each of them using this method to obtain it .
7,979
public Notification getByID ( String id ) { for ( Notification n : NotificationManager . notifications ) { if ( n . getId ( ) . equals ( id ) ) { logger . fine ( "...found a match for getByID query. With id: " + id ) ; return n ; } } logger . fine ( "There is no notification that match the given ID: " + id ) ; return null ; }
Search for a notification with the given id .
7,980
public List < Notification > getByStep ( int step ) { List < Notification > found = new ArrayList < Notification > ( ) ; for ( Notification n : NotificationManager . notifications ) if ( n . getWhen ( ) == step ) { logger . fine ( "...found a match for getByStep query. With step: " + step ) ; found . add ( n ) ; } if ( found . size ( ) > 0 ) return found ; return null ; }
Search for notifications saved on the given step .
7,981
public List < Notification > getBySource ( Object source ) { List < Notification > found = new ArrayList < Notification > ( ) ; for ( Notification n : NotificationManager . notifications ) if ( n . getSource ( ) . equals ( source ) ) { logger . fine ( "...found a match for getBySource query. With source: " + source ) ; found . add ( n ) ; } if ( found . size ( ) > 0 ) return found ; return null ; }
Search for notifications originated from the given source object .
7,982
public List < Notification > getByInteraction ( String interaction ) { List < Notification > found = new ArrayList < Notification > ( ) ; for ( Notification n : NotificationManager . notifications ) if ( ( ( InteractionNotification ) n ) . getInteraction ( ) . equals ( interaction ) ) { logger . fine ( "...found a match for getByInteraction query. With interaction: " + interaction ) ; found . add ( n ) ; } if ( found . size ( ) > 0 ) return found ; return null ; }
Search for notifications of interaction type that match the given class name .
7,983
public List < Notification > getByTarget ( Object target ) { List < Notification > found = new ArrayList < Notification > ( ) ; for ( Notification n : NotificationManager . notifications ) { for ( Object t : ( ( InteractionNotification ) n ) . getTarget ( ) ) { if ( t . equals ( target ) ) { logger . fine ( "...found a match for getByTarget query. With target: " + target ) ; found . add ( n ) ; } } } if ( found . size ( ) > 0 ) return found ; return null ; }
Search for notifications of interaction type that match the given target object .
7,984
public List < ValueNotification > getByElementID ( String elementID ) { if ( elementID == null ) return null ; List < ValueNotification > found = new ArrayList < ValueNotification > ( ) ; for ( Notification n : NotificationManager . notifications ) { try { if ( ( ( ValueNotification ) n ) . getElementID ( ) . equals ( elementID ) ) { logger . fine ( "...found a match for getByElementID query. With elementID: " + elementID ) ; found . add ( ( ValueNotification ) n ) ; } } catch ( ClassCastException e ) { } } if ( found . size ( ) > 0 ) return found ; return null ; }
Search for notifications of ElementValue type that match the given element identifier .
7,985
@ SuppressWarnings ( "unchecked" ) public ArrayList < Notification > getByType ( Class < ? > type ) { List < ? > byType = this . getByType ( ) ; if ( type . isAssignableFrom ( InteractionNotification . class ) ) return ( ArrayList < Notification > ) byType . get ( 0 ) ; if ( type . isAssignableFrom ( ValueNotification . class ) ) return ( ArrayList < Notification > ) byType . get ( 1 ) ; return null ; }
Search for notifications that match the corresponding notifications realization .
7,986
public void step ( SimState arg0 ) { logger . finest ( "Notifying each element of the notifable element list..." ) ; for ( Notifable n : NotificationManager . notifables ) { NotificationManager . addNotification ( n ) ; } }
When the setp of NotificationManager its called generates a notification for each notifable that has been added to it .
7,987
private static void addNotification ( Notifable n ) { NotificationManager . notifications . add ( new ValueNotification ( getNotificationID ( ) , NotificationManager . sim . getSchedule ( ) . getSteps ( ) , n . getSource ( ) , n . getID ( ) , n . getElementValue ( ) ) ) ; logger . fine ( "Notification added. Element: " + n . getID ( ) + ". Value =" + n . getElementValue ( ) ) ; }
Add a new notification of the ElementValueNotification type . The ones that are defined by the user .
7,988
public static String getStackTrace ( final Throwable ex ) { final StringWriter sw = new StringWriter ( ) ; final PrintWriter pw = new PrintWriter ( sw , true ) ; ex . printStackTrace ( pw ) ; pw . flush ( ) ; sw . flush ( ) ; return sw . toString ( ) ; }
A standard function to get the stack trace from a thrown Exception
7,989
public static void loadNetwork ( BayesianReasonerShanksAgent agent ) throws ShanksException { Network bn = ShanksAgentBayesianReasoningCapability . loadNetwork ( agent . getBayesianNetworkFilePath ( ) ) ; agent . setBayesianNetwork ( bn ) ; }
Load the Bayesian network of the agent
7,990
public static void addSoftEvidences ( Network bn , HashMap < String , HashMap < String , Double > > softEvidences ) throws ShanksException { for ( Entry < String , HashMap < String , Double > > softEvidence : softEvidences . entrySet ( ) ) { ShanksAgentBayesianReasoningCapability . addSoftEvidence ( bn , softEvidence . getKey ( ) , softEvidence . getValue ( ) ) ; } }
Add a set of soft - evidences to the Bayesian network to reason with it . It creates automatically the auxiliary nodes .
7,991
public long determineCurrentGeneration ( final AtomicLong generation , final long tick ) { if ( tick - lastScan >= scanTicks ) { lastScan = tick ; return generation . incrementAndGet ( ) ; } for ( ServiceDiscoveryTask visitor : visitors ) { visitor . determineGeneration ( generation , tick ) ; } return generation . get ( ) ; }
Trigger the loop every time enough ticks have been accumulated or whenever any of the visitors requests it .
7,992
public static void register ( Class < ? > clazz , Function < Object , ? > converter ) { if ( clazz == null || converter == null ) { log . warn ( "Trying to register either a null class ({0}) or a null converter ({1}). Ignoring!" , clazz , converter ) ; return ; } converters . put ( clazz , converter ) ; }
Register void .
7,993
public static < T > boolean hasConverter ( Class < T > clazz ) { if ( clazz == null ) { return false ; } else if ( converters . containsKey ( clazz ) ) { return true ; } return clazz . isArray ( ) && converters . containsKey ( clazz . getComponentType ( ) ) ; }
Has converter .
7,994
public static < T > Function < Object , T > getConverter ( final Class < T > clazz ) { return object -> Convert . convert ( object , clazz ) ; }
Gets a converter for a given class
7,995
@ SuppressWarnings ( "unchecked" ) public static < KEY , VALUE , MAP extends Map < KEY , VALUE > > MAP convert ( Object object , Class < ? > mapClass , Class < KEY > keyClass , Class < VALUE > valueClass ) { return Cast . as ( new MapConverter < KEY , VALUE , MAP > ( getConverter ( keyClass ) , getConverter ( valueClass ) , Cast . as ( mapClass ) ) . apply ( object ) ) ; }
Convert mAP .
7,996
@ SuppressWarnings ( "unchecked" ) public static < T , C extends Collection < T > > C convert ( Object object , Class < ? > collectionClass , Class < T > componentClass ) { if ( collectionClass == null || ! Collection . class . isAssignableFrom ( collectionClass ) ) { log . fine ( "{0} does not extend collection." , collectionClass ) ; return null ; } return Cast . as ( CollectionConverter . COLLECTION ( Cast . < Class < C > > as ( collectionClass ) , componentClass ) . apply ( object ) ) ; }
Convert c .
7,997
public static RealMatrix getColumRange ( RealMatrix matrix , int start , int end ) { return matrix . getSubMatrix ( 0 , matrix . getRowDimension ( ) - 1 , start , end ) ; }
Returns the column range from the matrix as a new matrix .
7,998
public static RealMatrix getRowRange ( RealMatrix matrix , int start , int end ) { return matrix . getSubMatrix ( start , end , 0 , matrix . getColumnDimension ( ) - 1 ) ; }
Returns the row range from the matrix as a new matrix .
7,999
public static double [ ] colSums ( RealMatrix matrix ) { double [ ] retval = new double [ matrix . getColumnDimension ( ) ] ; for ( int col = 0 ; col < matrix . getColumnDimension ( ) ; col ++ ) { for ( int row = 0 ; row < matrix . getRowDimension ( ) ; row ++ ) { retval [ col ] += matrix . getEntry ( row , col ) ; } } return retval ; }
Returns the sums of columns .