idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
23,500 | static URL tryToGetValidUrl ( String workingDir , String path , String filename ) { try { if ( new File ( filename ) . exists ( ) ) return new File ( filename ) . toURI ( ) . toURL ( ) ; if ( new File ( path + File . separator + filename ) . exists ( ) ) return new File ( path + File . separator + filename ) . toURI ( ) . toURL ( ) ; if ( new File ( workingDir + File . separator + filename ) . exists ( ) ) return new File ( workingDir + File . separator + filename ) . toURI ( ) . toURL ( ) ; if ( new File ( new URL ( filename ) . getFile ( ) ) . exists ( ) ) return new File ( new URL ( filename ) . getFile ( ) ) . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { } return null ; } | a little bit cryptic ... |
23,501 | public FilterBuilder includePackage ( final String ... prefixes ) { for ( String prefix : prefixes ) { add ( new Include ( prefix ( prefix ) ) ) ; } return this ; } | include packages of given prefixes |
23,502 | public Optional < Metadata > getRefinedBy ( Metadata meta ) { return Optional . fromNullable ( refines . get ( meta ) ) ; } | Returns an optional metadata expression refined by the given metadata expression . |
23,503 | public static Messages getInstance ( Locale locale , Class < ? > cls ) { Messages instance = null ; locale = ( locale == null ) ? Locale . getDefault ( ) : locale ; String bundleKey = ( cls == null ) ? BUNDLE_NAME : getBundleName ( cls ) ; String localeKey = locale . getLanguage ( ) ; if ( messageTable . contains ( bundleKey , localeKey ) ) { instance = messageTable . get ( bundleKey , localeKey ) ; } else { synchronized ( Messages . class ) { if ( instance == null ) { instance = new Messages ( locale , bundleKey ) ; messageTable . put ( bundleKey , localeKey , instance ) ; } } } return instance ; } | Get a Messages instance that has been localized for the given locale or the default locale if locale is null . Note that passing an unknown locale returns the default messages . |
23,504 | public static Vocab of ( Vocab ... vocabs ) { return new AggregateVocab ( new ImmutableList . Builder < Vocab > ( ) . add ( vocabs ) . build ( ) ) ; } | Returns a vocabulary composed of the union of the vocabularies given as parameter . The given vocabularies must have the same base URI . |
23,505 | public static Optional < Property > parseProperty ( String value , Map < String , Vocab > vocabs , ValidationContext context , EPUBLocation location ) { return Optional . fromNullable ( Iterables . get ( parseProperties ( value , vocabs , false , context , location ) , 0 , null ) ) ; } | Parses a single property value and report validation errors on the fly . |
23,506 | public static Set < Property > parsePropertyList ( String value , Map < String , ? extends Vocab > vocabs , ValidationContext context , EPUBLocation location ) { return parseProperties ( value , vocabs , true , context , location ) ; } | Parses a space - separated list of property values and report validation errors on the fly . |
23,507 | public static Map < String , Vocab > parsePrefixDeclaration ( String value , Map < String , ? extends Vocab > predefined , Map < String , ? extends Vocab > known , Set < String > forbidden , Report report , EPUBLocation location ) { Map < String , Vocab > vocabs = Maps . newHashMap ( predefined ) ; Map < String , String > mappings = PrefixDeclarationParser . parsePrefixMappings ( value , report , location ) ; for ( Entry < String , String > mapping : mappings . entrySet ( ) ) { String prefix = mapping . getKey ( ) ; String uri = mapping . getValue ( ) ; if ( "_" . equals ( prefix ) ) { report . message ( MessageId . OPF_007a , location ) ; } else if ( forbidden . contains ( uri ) ) { report . message ( MessageId . OPF_007b , location , prefix ) ; } else { if ( predefined . containsKey ( prefix ) && ! Strings . nullToEmpty ( predefined . get ( prefix ) . getURI ( ) ) . equals ( uri ) ) { report . message ( MessageId . OPF_007 , location , prefix ) ; } Vocab vocab = known . get ( uri ) ; vocabs . put ( mapping . getKey ( ) , ( vocab == null ) ? new UncheckedVocab ( uri , prefix ) : vocab ) ; } } return ImmutableMap . copyOf ( vocabs ) ; } | Parses a prefix attribute value and returns a map of prefixes to vocabularies given a pre - existing set of reserved prefixes known vocabularies and default vocabularies that cannot be re - declared . |
23,508 | public Optional < LinkedResource > getById ( String id ) { return Optional . fromNullable ( resourcesById . get ( id ) ) ; } | Search the linked resource with the given ID . |
23,509 | private void _dashmatch ( ) throws IOException { if ( debug ) { checkState ( reader . curChar == '|' ) ; } builder . type = Type . DASHMATCH ; builder . append ( "|=" ) ; reader . next ( ) ; if ( debug ) { checkState ( reader . curChar == '=' ) ; } } | DASHMATCH | = |
23,510 | private void _includes ( ) throws IOException { if ( debug ) { checkState ( reader . curChar == '~' ) ; } builder . type = Type . INCLUDES ; builder . append ( "~=" ) ; reader . next ( ) ; if ( debug ) { checkState ( reader . curChar == '=' ) ; } } | INCLUDES ~ = |
23,511 | private void _prefixmatch ( ) throws IOException { if ( debug ) { checkState ( reader . curChar == '^' ) ; } builder . type = Type . PREFIXMATCH ; builder . append ( "^=" ) ; reader . next ( ) ; if ( debug ) { checkState ( reader . curChar == '=' ) ; } } | PREFIXMATCH ^ = |
23,512 | private void _comment ( ) throws IOException , CssException { if ( debug ) { checkState ( reader . curChar == '/' && reader . peek ( ) == '*' ) ; } builder . type = Type . COMMENT ; reader . next ( ) ; while ( true ) { Mark mark = reader . mark ( ) ; int ch = reader . next ( ) ; if ( ch == - 1 ) { builder . error ( SCANNER_PREMATURE_EOF , reader ) ; reader . unread ( ch , mark ) ; break ; } else if ( ch == '*' && reader . peek ( ) == '/' ) { reader . next ( ) ; break ; } else { builder . append ( ch ) ; } } if ( debug && builder . errors . size ( ) < 1 ) { checkState ( '/' == reader . curChar && '*' == reader . prevChar ) ; } } | Builds a comment token excluding the leading and trailing comment tokens . |
23,513 | private void _quantity ( ) throws IOException , CssException { if ( debug ) { int ch = reader . peek ( ) ; checkState ( QNTSTART . matches ( ( char ) ch ) || isNextEscape ( ) ) ; checkState ( builder . getLength ( ) > 0 && NUM . matches ( builder . getLast ( ) ) ) ; } builder . type = Type . QNTY_DIMEN ; TokenBuilder suffix = new TokenBuilder ( reader , errHandler , locale ) ; append ( QNTSTART , suffix ) ; if ( suffix . getLast ( ) != '%' ) { append ( NMCHAR , suffix ) ; } if ( suffix . getLength ( ) > QNT_TOKEN_MAXLENGTH ) { builder . append ( suffix . toString ( ) ) ; return ; } final int [ ] ident = suffix . toArray ( ) ; int [ ] match = null ; for ( int [ ] test : quantities . keySet ( ) ) { if ( equals ( ident , test , true ) ) { builder . type = quantities . get ( test ) ; match = test ; break ; } } if ( builder . type == Type . QNTY_DIMEN ) { builder . append ( ident ) ; } else { if ( debug ) { checkState ( match != null ) ; } builder . append ( match ) ; } } | With incoming builder containing a valid NUMBER and next char being a valid QNTSTART modify the type and append to the builder |
23,514 | private void _urange ( ) throws IOException , CssException { if ( debug ) { checkArgument ( ( reader . curChar == 'U' || reader . curChar == 'u' ) && reader . peek ( ) == '+' ) ; } builder . type = Type . URANGE ; reader . next ( ) ; List < Integer > cbuf = Lists . newArrayList ( ) ; int count = 0 ; while ( true ) { Mark mark = reader . mark ( ) ; int ch = reader . next ( ) ; if ( ch == - 1 ) { reader . unread ( ch , mark ) ; break ; } if ( URANGECHAR . matches ( ( char ) ch ) ) { count = ch == '-' ? 0 : count + 1 ; if ( count == 7 ) { builder . error ( CssErrorCode . SCANNER_ILLEGAL_URANGE , reader , "U+" + toString ( cbuf ) + ( char ) ch ) ; } cbuf . add ( ch ) ; } else { reader . unread ( ch , mark ) ; break ; } } builder . append ( "U+" ) ; builder . append ( Ints . toArray ( cbuf ) ) ; } | Builds a UNICODE_RANGE token . |
23,515 | private void append ( CharMatcher matcher , TokenBuilder builder ) throws IOException , CssException { while ( true ) { Mark mark = reader . mark ( ) ; int ch = reader . next ( ) ; if ( ch > - 1 && matcher . matches ( ( char ) ch ) ) { builder . append ( ch ) ; } else if ( ch == '\\' ) { Optional < CssEscape > escape = new CssEscape ( reader , builder ) . create ( ) ; if ( escape . isPresent ( ) ) { reader . forward ( escape . get ( ) . render ( builder , matcher ) ) ; } else { reader . unread ( ch , mark ) ; break ; } } else { reader . unread ( ch , mark ) ; break ; } } } | Parse forward and append to the supplied builder all characters that match matcher or until the next character is EOF . Escapes are included verbatim if they don t match matcher else literal . |
23,516 | private boolean forwardMatch ( String match , boolean ignoreCase , boolean resetOnTrue ) throws IOException { Mark mark = reader . mark ( ) ; List < Integer > cbuf = Lists . newArrayList ( ) ; StringBuilder builder = new StringBuilder ( ) ; boolean result = true ; boolean seenChar = false ; while ( true ) { cbuf . add ( reader . next ( ) ) ; char ch = ( char ) reader . curChar ; if ( reader . curChar == - 1 ) { result = false ; break ; } else if ( WHITESPACE . matches ( ch ) ) { if ( seenChar ) { builder . append ( ch ) ; } } else { if ( builder . length ( ) == 0 ) { seenChar = true ; } builder . append ( ch ) ; int index = builder . length ( ) - 1 ; if ( ! ignoreCase && ( builder . charAt ( index ) == match . charAt ( index ) ) ) { result = false ; break ; } if ( ignoreCase && ( Ascii . toLowerCase ( builder . charAt ( index ) ) != Ascii . toLowerCase ( match . charAt ( index ) ) ) ) { result = false ; break ; } } if ( builder . length ( ) == match . length ( ) ) { if ( ! match . equalsIgnoreCase ( builder . toString ( ) ) ) { result = false ; } break ; } } if ( ! result || resetOnTrue ) { reader . unread ( cbuf , mark ) ; } return result ; } | Check if a forward scan will equal given match string |
23,517 | static int isNewLine ( int [ ] chars ) { checkArgument ( chars . length > 1 ) ; if ( chars [ 0 ] == '\r' && chars [ 1 ] == '\n' ) { return 2 ; } else if ( chars [ 0 ] == '\n' || chars [ 0 ] == '\r' || chars [ 0 ] == '\f' ) { return 1 ; } return 0 ; } | Determine whether a sequence of chars begin with a CSS newline . |
23,518 | public Optional < OPFItem > getItemById ( String id ) { return ( items != null ) ? items . getItemById ( id ) : Optional . < OPFItem > absent ( ) ; } | Search the list of item by ID . |
23,519 | public Optional < OPFItem > getItemByPath ( String path ) { return ( items != null ) ? items . getItemByPath ( path ) : Optional . < OPFItem > absent ( ) ; } | Search the list of item by path . |
23,520 | private void buildItems ( ) { Preconditions . checkState ( items == null ) ; items = OPFItems . build ( itemBuilders . values ( ) , spineIDs ) ; for ( OPFItem item : items . getItems ( ) ) { reportItem ( item ) ; } } | Build the final items from the item builders |
23,521 | protected void reportItem ( OPFItem item ) { if ( item . isInSpine ( ) ) { report . info ( item . getPath ( ) , FeatureEnum . IS_SPINEITEM , "true" ) ; report . info ( item . getPath ( ) , FeatureEnum . IS_LINEAR , String . valueOf ( item . isLinear ( ) ) ) ; } if ( item . isNcx ( ) ) { report . info ( item . getPath ( ) , FeatureEnum . HAS_NCX , "true" ) ; if ( ! item . getMimeType ( ) . equals ( "application/x-dtbncx+xml" ) ) { report . message ( MessageId . OPF_050 , EPUBLocation . create ( path , item . getLineNumber ( ) , item . getColumnNumber ( ) ) ) ; } } } | Report features or messages for a given item . |
23,522 | int render ( TokenBuilder builder , CharMatcher asLiteral ) { char ch = ( char ) character ; if ( asLiteral . matches ( ch ) ) { builder . append ( ch ) ; } else { builder . append ( sequence ) ; } return sequence . length ( ) - 1 ; } | Render this escape . |
23,523 | public void parseStyleAttribute ( final Reader reader , String systemID , final CssErrorHandler err , final CssContentHandler doc ) throws IOException , CssException { CssTokenIterator iter = scan ( reader , systemID , err ) ; doc . startDocument ( ) ; while ( iter . hasNext ( ) ) { CssToken tk = iter . next ( ) ; if ( MATCH_SEMI . apply ( tk ) ) { continue ; } try { CssDeclaration decl = handleDeclaration ( tk , iter , doc , err , true ) ; if ( decl != null ) { doc . declaration ( decl ) ; } else { return ; } } catch ( PrematureEOFException te ) { break ; } } doc . endDocument ( ) ; } | Parse a CSS style attribute . |
23,524 | private void handleRuleSet ( CssToken start , final CssTokenIterator iter , final CssContentHandler doc , CssErrorHandler err ) throws CssException { char errChar = '{' ; try { List < CssSelector > selectors = handleSelectors ( start , iter , err ) ; errChar = '}' ; if ( selectors == null ) { iter . next ( MATCH_CLOSEBRACE ) ; return ; } if ( debug ) { checkState ( iter . last . getChar ( ) == '{' ) ; checkState ( ! selectors . isEmpty ( ) ) ; } doc . selectors ( selectors ) ; handleDeclarationBlock ( iter . next ( ) , iter , doc , err ) ; doc . endSelectors ( selectors ) ; } catch ( NoSuchElementException nse ) { err . error ( new CssGrammarException ( GRAMMAR_PREMATURE_EOF , iter . last . location , messages . getLocale ( ) , "'" + errChar + "'" ) ) ; throw new PrematureEOFException ( ) ; } if ( debug ) { checkState ( iter . last . getChar ( ) == '}' ) ; } } | With the start token expected to be the first token of a selector group create and issue the group then invoke handleDeclarationBlock . At exit the last token returned from the iterator is expected to be } . |
23,525 | private void handleDeclarationBlock ( CssToken start , CssTokenIterator iter , final CssContentHandler doc , CssErrorHandler err ) throws CssException { while ( true ) { if ( MATCH_CLOSEBRACE . apply ( start ) ) { return ; } CssDeclaration decl = handleDeclaration ( start , iter , doc , err , false ) ; try { if ( decl != null ) { doc . declaration ( decl ) ; if ( debug ) { checkState ( MATCH_SEMI_CLOSEBRACE . apply ( iter . last ) ) ; } if ( MATCH_CLOSEBRACE . apply ( iter . last ) ) { return ; } else if ( MATCH_SEMI . apply ( iter . last ) && MATCH_CLOSEBRACE . apply ( iter . peek ( ) ) ) { iter . next ( ) ; return ; } else { if ( debug ) { checkState ( MATCH_SEMI . apply ( iter . last ) ) ; } start = iter . next ( ) ; } } else { start = iter . next ( MATCH_SEMI_CLOSEBRACE ) ; if ( MATCH_SEMI . apply ( start ) ) { start = iter . next ( ) ; } } } catch ( NoSuchElementException nse ) { err . error ( new CssGrammarException ( GRAMMAR_PREMATURE_EOF , iter . last . location , messages . getLocale ( ) , "';' " + messages . get ( "or" ) + " '}'" ) ) ; throw new PrematureEOFException ( ) ; } } } | With start token being the first non - ignorable token inside the declaration block iterate issuing CssDeclaration objects until the block ends . |
23,526 | private CssDeclaration handleDeclaration ( CssToken name , CssTokenIterator iter , CssContentHandler doc , CssErrorHandler err , boolean isStyleAttribute ) throws CssException { if ( name . type != CssToken . Type . IDENT ) { err . error ( new CssGrammarException ( GRAMMAR_EXPECTING_TOKEN , name . location , messages . getLocale ( ) , name . getChars ( ) , messages . get ( "a_property_name" ) ) ) ; return null ; } CssDeclaration declaration = new CssDeclaration ( name . getChars ( ) , name . location ) ; try { if ( ! MATCH_COLON . apply ( iter . next ( ) ) ) { err . error ( new CssGrammarException ( GRAMMAR_EXPECTING_TOKEN , name . location , messages . getLocale ( ) , iter . last . getChars ( ) , ":" ) ) ; return null ; } } catch ( NoSuchElementException nse ) { err . error ( new CssGrammarException ( GRAMMAR_PREMATURE_EOF , iter . last . location , messages . getLocale ( ) , ":" ) ) ; throw new PrematureEOFException ( ) ; } try { while ( true ) { CssToken value = iter . next ( ) ; if ( MATCH_SEMI_CLOSEBRACE . apply ( value ) ) { if ( declaration . components . size ( ) < 1 ) { err . error ( new CssGrammarException ( GRAMMAR_EXPECTING_TOKEN , iter . last . location , messages . getLocale ( ) , value . getChar ( ) , messages . get ( "a_property_value" ) ) ) ; return null ; } else { return declaration ; } } else { if ( ! handlePropertyValue ( declaration , value , iter , isStyleAttribute ) ) { err . error ( new CssGrammarException ( GRAMMAR_UNEXPECTED_TOKEN , iter . last . location , messages . getLocale ( ) , iter . last . getChars ( ) ) ) ; return null ; } else { if ( isStyleAttribute && ! iter . hasNext ( ) ) { return declaration ; } } } } } catch ( NoSuchElementException nse ) { err . error ( new CssGrammarException ( GRAMMAR_PREMATURE_EOF , iter . last . location , messages . getLocale ( ) , "';' " + messages . get ( "or" ) + " '}'" ) ) ; throw new PrematureEOFException ( ) ; } } | With start expected to be an IDENT token representing the property name build the declaration and return after hitting ; or } . On error issue to errhandler return null caller forwards . |
23,527 | private boolean handlePropertyValue ( CssDeclaration declaration , CssToken start , CssTokenIterator iter , boolean isStyleAttribute ) { while ( true ) { if ( start . type == CssToken . Type . IMPORTANT ) { declaration . important = true ; } else { CssConstruct cc = CssConstructFactory . create ( start , iter , MATCH_SEMI_CLOSEBRACE , ContextRestrictions . PROPERTY_VALUE ) ; if ( cc == null ) { return false ; } else { declaration . components . add ( cc ) ; } } if ( ( isStyleAttribute && ! iter . hasNext ( ) ) || ( MATCH_SEMI . apply ( iter . peek ( ) ) ) || ( ! isStyleAttribute && MATCH_CLOSEBRACE . apply ( iter . peek ( ) ) ) ) { return declaration . components . size ( ) > 0 ; } else { start = iter . next ( ) ; } } } | Append property value components to declaration . value return false if fail with iter . last at the the token which caused the fail . |
23,528 | private CssConstruct handleAtRuleParam ( CssToken start , CssTokenIterator iter , CssContentHandler doc , CssErrorHandler err ) { return CssConstructFactory . create ( start , iter , MATCH_SEMI_OPENBRACE , ContextRestrictions . ATRULE_PARAM ) ; } | With inparam token being the first token of an atrule param create the construct and return it . |
23,529 | private boolean checkValueAndNext ( StringTokenizer st , String token ) throws InvalidDateException { if ( ! st . hasMoreTokens ( ) ) { return false ; } String t = st . nextToken ( ) ; if ( ! t . equals ( token ) ) { throw new InvalidDateException ( "Unexpected: " + t ) ; } if ( ! st . hasMoreTokens ( ) ) { throw new InvalidDateException ( "Incomplete date." ) ; } return true ; } | Check if the next token if exists has a given value and that the provided string tokenizer has more tokens after that . It consumes the token checked against the expected value from the string tokenizer . |
23,530 | protected void checkDependentCondition ( MessageId id , boolean condition1 , boolean condition2 , EPUBLocation location ) { if ( condition1 && ! condition2 ) { report . message ( id , location ) ; } } | condition2 is false . |
23,531 | public String getName ( P property ) { Preconditions . checkNotNull ( property ) ; return converter . convert ( property ) ; } | Returns the property name for the given enum item contained in this vocabulary . |
23,532 | public Collection < String > getNames ( Collection < P > properties ) { Preconditions . checkNotNull ( properties ) ; return Collections2 . transform ( properties , new Function < P , String > ( ) { public String apply ( P property ) { return converter . convert ( property ) ; } } ) ; } | Returns the property names of the given enum items contained in this vocabulary . |
23,533 | public static LocalizedMessages getInstance ( Locale locale ) { LocalizedMessages instance = null ; if ( locale == null ) { locale = Locale . getDefault ( ) ; } String localeKey = locale . getLanguage ( ) ; if ( localizedMessages . containsKey ( localeKey ) ) { instance = localizedMessages . get ( localeKey ) ; } else { synchronized ( LocalizedMessages . class ) { if ( instance == null ) { instance = new LocalizedMessages ( locale ) ; localizedMessages . put ( localeKey , instance ) ; } } } return instance ; } | Provides messages for the given locale . |
23,534 | public Message getMessage ( MessageId id ) { Message message ; if ( cachedMessages . containsKey ( id ) ) { message = cachedMessages . get ( id ) ; } else { message = new Message ( id , defaultSeverities . get ( id ) , getMessageAsString ( id ) , getSuggestion ( id ) ) ; cachedMessages . put ( id , message ) ; } return message ; } | Gets the message for the given id . |
23,535 | public String getSuggestion ( MessageId id , String key ) { String messageKey = id . name ( ) + "_SUG." + key ; String messageDefaultKey = id . name ( ) + "_SUG.default" ; return bundle . containsKey ( messageKey ) ? getStringFromBundle ( messageKey ) : ( bundle . containsKey ( messageDefaultKey ) ? getStringFromBundle ( messageDefaultKey ) : getSuggestion ( id ) ) ; } | Returns the suggestion message for the given message ID and key . In other words for a message ID of XXX_NNN and a key key returns the bundle message named XXX_NNN_SUG . key . If the suggestion key is not found returns the bundle message named XXX_NNN_SUG . default . If this latter is not found returns the bundle message nameed XXX_NNN_SUG . |
23,536 | public Optional < OPFItem > getItemById ( String id ) { return Optional . fromNullable ( itemsById . get ( id ) ) ; } | Search the item with the given ID . |
23,537 | public Optional < OPFItem > getItemByPath ( String path ) { return Optional . fromNullable ( itemsByPath . get ( path ) ) ; } | Search the item with the given path . |
23,538 | int next ( ) throws IOException { prevChar = curChar ; checkState ( prevChar > - 1 ) ; if ( pos < buf . length ) { curChar = buf [ pos ++ ] ; } else { curChar = in . read ( ) ; } offset ++ ; if ( curChar == '\r' || curChar == '\n' ) { if ( curChar == '\n' && prevChar == '\r' ) { } else { prevLine = line ; line ++ ; } } else if ( prevLine < line ) { col = 1 ; prevLine = line ; } else { if ( prevChar != 0 ) { col ++ ; } } return curChar ; } | Returns the next character in the stream and advances the readers position . If there are no more characters - 1 is returned the first time this method is invoked in that state ; multiple invocations at EOF will yield an IllegalStateException . |
23,539 | int peek ( ) throws IOException { Mark m = mark ( ) ; int ch = next ( ) ; unread ( ch , m ) ; return ch ; } | Returns the next character in the stream without advancing the readers position . If there are no more characters - 1 is returned . |
23,540 | int [ ] peek ( int n ) throws IOException { int [ ] buf = new int [ n ] ; Mark m = mark ( ) ; boolean seenEOF = false ; for ( int i = 0 ; i < buf . length ; i ++ ) { if ( ! seenEOF ) { buf [ i ] = next ( ) ; } else { buf [ i ] = - 1 ; } if ( buf [ i ] == - 1 ) { seenEOF = true ; } } if ( ! seenEOF ) { unread ( buf , m ) ; } else { List < Integer > ints = Lists . newArrayList ( ) ; for ( int aBuf : buf ) { ints . add ( aBuf ) ; if ( aBuf == - 1 ) { break ; } } unread ( ints , m ) ; } return buf ; } | Returns the the next n characters in the stream without advancing the readers position . |
23,541 | int at ( int n ) throws IOException { Mark mark = mark ( ) ; List < Integer > cbuf = Lists . newArrayList ( ) ; for ( int i = 0 ; i < n ; i ++ ) { cbuf . add ( next ( ) ) ; if ( curChar == - 1 ) { break ; } } unread ( cbuf , mark ) ; return cbuf . get ( cbuf . size ( ) - 1 ) ; } | Peek and return the character at position n from current position or - 1 if EOF is reached before or at that position . |
23,542 | CssReader forward ( CharMatcher matcher ) throws IOException { while ( true ) { Mark mark = mark ( ) ; next ( ) ; if ( curChar == - 1 || ( matcher . matches ( ( char ) curChar ) && prevChar != '\\' ) ) { unread ( curChar , mark ) ; break ; } } return this ; } | Read forward until the next non - escaped character matches the given CharMatcher or is EOF . |
23,543 | CssReader forward ( int n ) throws IOException { for ( int i = 0 ; i < n ; i ++ ) { Mark mark = mark ( ) ; next ( ) ; if ( curChar == - 1 ) { unread ( curChar , mark ) ; break ; } } return this ; } | Read forward n characters or until the next character is EOF . |
23,544 | private URI checkURI ( String uri ) { try { return new URI ( Preconditions . checkNotNull ( uri ) . trim ( ) ) ; } catch ( URISyntaxException e ) { parser . getReport ( ) . message ( MessageId . RSC_020 , parser . getLocation ( ) , uri ) ; return null ; } } | should be in a URI utils class |
23,545 | protected static String correctToUtf8 ( String inputString ) { final StringBuilder result = new StringBuilder ( inputString . length ( ) ) ; final StringCharacterIterator it = new StringCharacterIterator ( inputString ) ; char ch = it . current ( ) ; boolean modified = false ; while ( ch != CharacterIterator . DONE ) { if ( Character . isISOControl ( ch ) ) { if ( ch == '\r' || ch == '\n' ) { result . append ( ch ) ; } else { modified = true ; result . append ( String . format ( "0x%x" , ( int ) ch ) ) ; } } else { result . append ( ch ) ; } ch = it . next ( ) ; } if ( ! modified ) return inputString ; return result . toString ( ) ; } | Make sure the string contains valid UTF - 8 characters |
23,546 | protected static String fromTime ( final long time ) { Date date = new Date ( time ) ; String formatted = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssZ" ) . format ( date ) ; return formatted . substring ( 0 , 22 ) + ":" + formatted . substring ( 22 ) ; } | Transform time into ISO 8601 string . |
23,547 | public List < ResourceCollection > getByRole ( Roles role ) { return role == null ? ImmutableList . < ResourceCollection > of ( ) : getByRole ( role . toString ( ) ) ; } | Returns the list of collections in this set with the given IDPF - reserved role . |
23,548 | public static Property newFrom ( String name , String base , String prefix ) { return new Property ( name , base , prefix , null ) ; } | Creates a new instance from a short name a prefix and a stem URI . |
23,549 | protected void validateParameters ( ) { super . validateParameters ( ) ; parameters . put ( OPT_NOPREVIEW , "" ) ; parameters . put ( OPT_RAW , "-" ) ; parameters . put ( OPT_RAW_FORMAT , "rgb" ) ; parameters . put ( OPT_CAMSELECT , Integer . toString ( this . camSelect ) ) ; parameters . put ( OPT_OUTPUT , "/dev/null" ) ; } | raspivid - rf rgb - r file . rgb will output YUV whilst raspivid - r file . rgb - rf rgb Somewhat yucky but that s the way it was written . |
23,550 | public boolean close ( ) { if ( open . compareAndSet ( true , false ) ) { LOG . debug ( "Closing webcam {}" , getName ( ) ) ; assert lock != null ; WebcamCloseTask task = new WebcamCloseTask ( driver , device ) ; try { task . close ( ) ; } catch ( InterruptedException e ) { open . set ( true ) ; LOG . debug ( "Thread has been interrupted before webcam was closed!" , e ) ; return false ; } catch ( WebcamException e ) { open . set ( true ) ; throw e ; } if ( asynchronous ) { updater . stop ( ) ; } removeShutdownHook ( ) ; lock . unlock ( ) ; WebcamEvent we = new WebcamEvent ( WebcamEventType . CLOSED , this ) ; Iterator < WebcamListener > wli = listeners . iterator ( ) ; WebcamListener l = null ; while ( wli . hasNext ( ) ) { l = wli . next ( ) ; try { l . webcamClosed ( we ) ; } catch ( Exception e ) { LOG . error ( String . format ( "Notify webcam closed, exception when calling %s listener" , l . getClass ( ) ) , e ) ; } } notificator . shutdown ( ) ; while ( ! notificator . isTerminated ( ) ) { try { notificator . awaitTermination ( 100 , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { return false ; } } LOG . debug ( "Webcam {} has been closed" , getName ( ) ) ; } else { LOG . debug ( "Webcam {} is already closed" , getName ( ) ) ; } return true ; } | Close the webcam . |
23,551 | protected void dispose ( ) { assert disposed != null ; assert open != null ; assert driver != null ; assert device != null ; assert listeners != null ; if ( ! disposed . compareAndSet ( false , true ) ) { return ; } open . set ( false ) ; LOG . info ( "Disposing webcam {}" , getName ( ) ) ; WebcamDisposeTask task = new WebcamDisposeTask ( driver , device ) ; try { task . dispose ( ) ; } catch ( InterruptedException e ) { LOG . error ( "Processor has been interrupted before webcam was disposed!" , e ) ; return ; } WebcamEvent we = new WebcamEvent ( WebcamEventType . DISPOSED , this ) ; Iterator < WebcamListener > wli = listeners . iterator ( ) ; WebcamListener l = null ; while ( wli . hasNext ( ) ) { l = wli . next ( ) ; try { l . webcamClosed ( we ) ; l . webcamDisposed ( we ) ; } catch ( Exception e ) { LOG . error ( String . format ( "Notify webcam disposed, exception when calling %s listener" , l . getClass ( ) ) , e ) ; } } removeShutdownHook ( ) ; LOG . debug ( "Webcam disposed {}" , getName ( ) ) ; } | Completely dispose capture device . After this operation webcam cannot be used any more and full reinstantiation is required . |
23,552 | protected BufferedImage transform ( BufferedImage image ) { if ( image != null ) { WebcamImageTransformer tr = getImageTransformer ( ) ; if ( tr != null ) { return tr . transform ( image ) ; } } return image ; } | TRansform image using image transformer . If image transformer has not been set this method return instance passed in the argument without any modifications . |
23,553 | public void setCustomViewSizes ( Dimension ... sizes ) { assert customSizes != null ; if ( sizes == null ) { customSizes . clear ( ) ; return ; } customSizes = Arrays . asList ( sizes ) ; } | Set custom resolution . If you are using this method you have to make sure that your webcam device can support this specific resolution . |
23,554 | public void setViewSize ( Dimension size ) { if ( size == null ) { throw new IllegalArgumentException ( "Resolution cannot be null!" ) ; } if ( open . get ( ) ) { throw new IllegalStateException ( "Cannot change resolution when webcam is open, please close it first" ) ; } Dimension current = getViewSize ( ) ; if ( current != null && current . width == size . width && current . height == size . height ) { return ; } Dimension [ ] predefined = getViewSizes ( ) ; Dimension [ ] custom = getCustomViewSizes ( ) ; assert predefined != null ; assert custom != null ; boolean ok = false ; for ( Dimension d : predefined ) { if ( d . width == size . width && d . height == size . height ) { ok = true ; break ; } } if ( ! ok ) { for ( Dimension d : custom ) { if ( d . width == size . width && d . height == size . height ) { ok = true ; break ; } } } if ( ! ok ) { StringBuilder sb = new StringBuilder ( "Incorrect dimension [" ) ; sb . append ( size . width ) . append ( "x" ) . append ( size . height ) . append ( "] " ) ; sb . append ( "possible ones are " ) ; for ( Dimension d : predefined ) { sb . append ( "[" ) . append ( d . width ) . append ( "x" ) . append ( d . height ) . append ( "] " ) ; } for ( Dimension d : custom ) { sb . append ( "[" ) . append ( d . width ) . append ( "x" ) . append ( d . height ) . append ( "] " ) ; } throw new IllegalArgumentException ( sb . toString ( ) ) ; } LOG . debug ( "Setting new resolution {}x{}" , size . width , size . height ) ; device . setResolution ( size ) ; } | Set new view size . New size has to exactly the same as one of the default sized or exactly the same as one of the custom ones . |
23,555 | public void setParameters ( Map < String , ? > parameters ) { WebcamDevice device = getDevice ( ) ; if ( device instanceof Configurable ) { ( ( Configurable ) device ) . setParameters ( parameters ) ; } else { LOG . debug ( "Webcam device {} is not configurable" , device ) ; } } | If the underlying device implements Configurable interface specified parameters are passed to it . May be called before the open method or later in dependence of the device implementation . |
23,556 | private boolean isReady ( ) { assert disposed != null ; assert open != null ; if ( disposed . get ( ) ) { LOG . warn ( "Cannot get image, webcam has been already disposed" ) ; return false ; } if ( ! open . get ( ) ) { if ( autoOpen ) { open ( ) ; } else { return false ; } } return true ; } | Is webcam ready to be read . |
23,557 | public static List < Webcam > getWebcams ( ) throws WebcamException { try { return getWebcams ( Long . MAX_VALUE ) ; } catch ( TimeoutException e ) { throw new RuntimeException ( e ) ; } } | Get list of webcams to use . This method will wait predefined time interval for webcam devices to be discovered . By default this time is set to 1 minute . |
23,558 | public static List < Webcam > getWebcams ( long timeout ) throws TimeoutException , WebcamException { if ( timeout < 0 ) { throw new IllegalArgumentException ( String . format ( "Timeout cannot be negative (%d)" , timeout ) ) ; } return getWebcams ( timeout , TimeUnit . MILLISECONDS ) ; } | Get list of webcams to use . This method will wait given time interval for webcam devices to be discovered . Time argument is given in milliseconds . |
23,559 | public static synchronized List < Webcam > getWebcams ( long timeout , TimeUnit tunit ) throws TimeoutException , WebcamException { if ( timeout < 0 ) { throw new IllegalArgumentException ( String . format ( "Timeout cannot be negative (%d)" , timeout ) ) ; } if ( tunit == null ) { throw new IllegalArgumentException ( "Time unit cannot be null!" ) ; } WebcamDiscoveryService discovery = getDiscoveryService ( ) ; assert discovery != null ; List < Webcam > webcams = discovery . getWebcams ( timeout , tunit ) ; if ( ! discovery . isRunning ( ) ) { discovery . start ( ) ; } return webcams ; } | Get list of webcams to use . This method will wait given time interval for webcam devices to be discovered . |
23,560 | public boolean addWebcamListener ( WebcamListener l ) { if ( l == null ) { throw new IllegalArgumentException ( "Webcam listener cannot be null!" ) ; } assert listeners != null ; return listeners . add ( l ) ; } | Add webcam listener . |
23,561 | public static void registerDriver ( Class < ? extends WebcamDriver > clazz ) { if ( clazz == null ) { throw new IllegalArgumentException ( "Webcam driver class to register cannot be null!" ) ; } DRIVERS_CLASS_LIST . add ( clazz ) ; registerDriver ( clazz . getCanonicalName ( ) ) ; } | Register new webcam video driver . |
23,562 | private static VideoDevice getVideoDevice ( File file ) { LOG . debug ( "Creating V4L4J device from file {}" , file ) ; try { return new VideoDevice ( file . getAbsolutePath ( ) ) ; } catch ( V4L4JException e ) { throw new WebcamException ( "Cannot instantiate V4L4J device from " + file , e ) ; } } | Create video device from file . |
23,563 | protected static void initialize ( boolean load ) { if ( load && initialized . compareAndSet ( false , true ) ) { boolean nativeFound = getNativeDiscovery ( ) . discover ( ) ; if ( ! nativeFound ) { throw new IllegalStateException ( "The libvlc native library has not been found" ) ; } } } | Initialize natives . If argument is true the natives are being loaded . In case of false this method do nothing . It s used mostly in unit tests . |
23,564 | public void setParameters ( Map < String , ? > map ) { if ( isOpen ) { throw new UnsupportedOperationException ( MSG_CANNOT_CHANGE_PROP ) ; } for ( Entry < String , ? > entry : map . entrySet ( ) ) { if ( this . driver . getOptions ( ) . hasOption ( entry . getKey ( ) ) ) { String longKey = this . driver . getOptions ( ) . getOption ( entry . getKey ( ) ) . getLongOpt ( ) ; this . parameters . put ( longKey , entry . getValue ( ) == null ? "" : entry . getValue ( ) . toString ( ) ) ; } else { throw new UnsupportedOperationException ( MSG_WRONG_ARGUMENT ) ; } } } | support change FPS at runtime . |
23,565 | public static final ByteBuffer getImageByteBuffer ( Webcam webcam , String format ) { return ByteBuffer . wrap ( getImageBytes ( webcam , format ) ) ; } | Capture image as BYteBuffer . |
23,566 | public static final ResourceBundle loadRB ( Class < ? > clazz , Locale locale ) { String pkg = WebcamUtils . class . getPackage ( ) . getName ( ) . replaceAll ( "\\." , "/" ) ; return PropertyResourceBundle . getBundle ( String . format ( "%s/i18n/%s" , pkg , clazz . getSimpleName ( ) ) ) ; } | Get resource bundle for specific class . |
23,567 | private Thread startFramesRefresher ( ) { Thread refresher = new Thread ( this , String . format ( "frames-refresher-[%s]" , id ) ) ; refresher . setUncaughtExceptionHandler ( WebcamExceptionHandler . getInstance ( ) ) ; refresher . setDaemon ( true ) ; refresher . start ( ) ; return refresher ; } | Start underlying frames refresher . |
23,568 | private void updateFrameBuffer ( ) { LOG . trace ( "Next frame" ) ; if ( t1 == - 1 || t2 == - 1 ) { t1 = System . currentTimeMillis ( ) ; t2 = System . currentTimeMillis ( ) ; } int result = new NextFrameTask ( this ) . nextFrame ( ) ; t1 = t2 ; t2 = System . currentTimeMillis ( ) ; fps = ( 4 * fps + 1000 / ( t2 - t1 + 1 ) ) / 5 ; if ( result == - 1 ) { LOG . error ( "Timeout when requesting image!" ) ; } else if ( result < - 1 ) { LOG . error ( "Error requesting new frame!" ) ; } } | Update underlying memory buffer and fetch new frame . |
23,569 | private boolean isInDoNotEngageZone ( final int x , final int y ) { for ( final Rectangle zone : doNotEnganeZones ) { if ( zone . contains ( x , y ) ) { return true ; } } return false ; } | Return true if point identified by x and y coordinates is in one of the do - not - engage zones . Return false otherwise . |
23,570 | private void notifyMotionListeners ( BufferedImage currentOriginal ) { WebcamMotionEvent wme = new WebcamMotionEvent ( this , previousOriginal , currentOriginal , algorithm . getArea ( ) , algorithm . getCog ( ) , algorithm . getPoints ( ) ) ; for ( WebcamMotionListener l : listeners ) { try { l . motionDetected ( wme ) ; } catch ( Exception e ) { WebcamExceptionHandler . handle ( e ) ; } } } | Will notify all attached motion listeners . |
23,571 | public Point getMotionCog ( ) { Point cog = algorithm . getCog ( ) ; if ( cog == null ) { int w = webcam . getViewSize ( ) . width ; int h = webcam . getViewSize ( ) . height ; cog = new Point ( w / 2 , h / 2 ) ; } return cog ; } | Get motion center of gravity . When no motion is detected this value points to the image center . |
23,572 | public void process ( ) throws InterruptedException { boolean alreadyInSync = Thread . currentThread ( ) instanceof WebcamProcessor . ProcessorThread ; if ( alreadyInSync ) { handle ( ) ; } else { if ( doSync ) { if ( processor == null ) { throw new RuntimeException ( "Driver should be synchronized, but processor is null" ) ; } processor . process ( this ) ; } else { handle ( ) ; } } } | Process task by processor thread . |
23,573 | private static List < WebcamDevice > getDevices ( List < Webcam > webcams ) { List < WebcamDevice > devices = new ArrayList < WebcamDevice > ( ) ; for ( Webcam webcam : webcams ) { devices . add ( webcam . getDevice ( ) ) ; } return devices ; } | Get list of devices used by webcams . |
23,574 | public void scan ( ) { WebcamDiscoveryListener [ ] listeners = Webcam . getDiscoveryListeners ( ) ; List < WebcamDevice > tmpnew = driver . getDevices ( ) ; List < WebcamDevice > tmpold = null ; try { tmpold = getDevices ( getWebcams ( Long . MAX_VALUE , TimeUnit . MILLISECONDS ) ) ; } catch ( TimeoutException e ) { throw new WebcamException ( e ) ; } List < WebcamDevice > oldones = new LinkedList < WebcamDevice > ( tmpold ) ; List < WebcamDevice > newones = new LinkedList < WebcamDevice > ( tmpnew ) ; Iterator < WebcamDevice > oi = oldones . iterator ( ) ; Iterator < WebcamDevice > ni = null ; WebcamDevice od = null ; WebcamDevice nd = null ; while ( oi . hasNext ( ) ) { od = oi . next ( ) ; ni = newones . iterator ( ) ; while ( ni . hasNext ( ) ) { nd = ni . next ( ) ; if ( nd . getName ( ) . equals ( od . getName ( ) ) ) { ni . remove ( ) ; oi . remove ( ) ; break ; } } } if ( oldones . size ( ) > 0 ) { List < Webcam > notified = new ArrayList < Webcam > ( ) ; for ( WebcamDevice device : oldones ) { for ( Webcam webcam : webcams ) { if ( webcam . getDevice ( ) . getName ( ) . equals ( device . getName ( ) ) ) { notified . add ( webcam ) ; break ; } } } setCurrentWebcams ( tmpnew ) ; for ( Webcam webcam : notified ) { notifyWebcamGone ( webcam , listeners ) ; webcam . dispose ( ) ; } } if ( newones . size ( ) > 0 ) { setCurrentWebcams ( tmpnew ) ; for ( WebcamDevice device : newones ) { for ( Webcam webcam : webcams ) { if ( webcam . getDevice ( ) . getName ( ) . equals ( device . getName ( ) ) ) { notifyWebcamFound ( webcam , listeners ) ; break ; } } } } } | Scan for newly added or already removed webcams . |
23,575 | public void stop ( ) { if ( ! running . compareAndSet ( true , false ) ) { return ; } try { runner . join ( ) ; } catch ( InterruptedException e ) { throw new WebcamException ( "Joint interrupted" ) ; } LOG . debug ( "Discovery service has been stopped" ) ; runner = null ; } | Stop discovery service . |
23,576 | public void start ( ) { if ( ! enabled . get ( ) ) { LOG . info ( "Discovery service has been disabled and thus it will not be started" ) ; return ; } if ( support == null ) { LOG . info ( "Discovery will not run - driver {} does not support this feature" , driver . getClass ( ) . getSimpleName ( ) ) ; return ; } if ( ! running . compareAndSet ( false , true ) ) { return ; } runner = new Thread ( this , "webcam-discovery-service" ) ; runner . setUncaughtExceptionHandler ( WebcamExceptionHandler . getInstance ( ) ) ; runner . setDaemon ( true ) ; runner . start ( ) ; } | Start discovery service . |
23,577 | public void start ( ) { if ( running . compareAndSet ( false , true ) ) { image . set ( new WebcamGetImageTask ( Webcam . getDriver ( ) , webcam . getDevice ( ) ) . getImage ( ) ) ; executor = Executors . newSingleThreadScheduledExecutor ( THREAD_FACTORY ) ; executor . execute ( this ) ; LOG . debug ( "Webcam updater has been started" ) ; } else { LOG . debug ( "Webcam updater is already started" ) ; } } | Start updater . |
23,578 | public void stop ( ) { if ( running . compareAndSet ( true , false ) ) { executor . shutdown ( ) ; while ( ! executor . isTerminated ( ) ) { try { executor . awaitTermination ( 100 , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { return ; } } LOG . debug ( "Webcam updater has been stopped" ) ; } else { LOG . debug ( "Webcam updater is already stopped" ) ; } } | Stop updater . |
23,579 | public BufferedImage getImage ( ) { int i = 0 ; while ( image . get ( ) == null ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } if ( i ++ > 100 ) { LOG . error ( "Image has not been found for more than 10 seconds" ) ; return null ; } } imageNew = false ; return image . get ( ) ; } | Return currently available image . This method will return immediately while it was been called after camera has been open . In case when there are parallel threads running and there is a possibility to call this method in the opening time or before camera has been open at all this method will block until webcam return first image . Maximum blocking time will be 10 seconds after this time method will return null . |
23,580 | private synchronized void init ( ) { if ( ! initialized . compareAndSet ( false , true ) ) { return ; } LOG . debug ( "GStreamer webcam device initialization" ) ; pipe = new Pipeline ( getName ( ) ) ; source = ElementFactory . make ( GStreamerDriver . getSourceBySystem ( ) , "source" ) ; if ( Platform . isWindows ( ) ) { source . set ( "device-index" , deviceIndex ) ; } else if ( Platform . isLinux ( ) ) { source . set ( "device" , videoFile . getAbsolutePath ( ) ) ; } else if ( Platform . isMacOSX ( ) ) { throw new IllegalStateException ( "not yet implemented" ) ; } sink = new RGBDataSink ( getName ( ) , this ) ; sink . setPassDirectBuffer ( true ) ; sink . getSinkElement ( ) . setMaximumLateness ( LATENESS , TimeUnit . MILLISECONDS ) ; sink . getSinkElement ( ) . setQOSEnabled ( true ) ; filter = ElementFactory . make ( "capsfilter" , "capsfilter" ) ; jpegdec = ElementFactory . make ( "jpegdec" , "jpegdec" ) ; pipelineReady ( ) ; resolutions = parseResolutions ( source . getPads ( ) . get ( 0 ) ) ; pipelineStop ( ) ; } | Initialize webcam device . |
23,581 | private Dimension [ ] parseResolutions ( Pad pad ) { Caps caps = pad . getCaps ( ) ; format = findPreferredFormat ( caps ) ; LOG . debug ( "Best format is {}" , format ) ; Dimension r = null ; Structure s = null ; String mime = null ; final int n = caps . size ( ) ; int i = 0 ; Map < String , Dimension > map = new HashMap < String , Dimension > ( ) ; do { s = caps . getStructure ( i ++ ) ; LOG . debug ( "Found format structure {}" , s ) ; mime = s . getName ( ) ; if ( mime . equals ( format ) ) { if ( ( r = capStructToResolution ( s ) ) != null ) { map . put ( r . width + "x" + r . height , r ) ; } } } while ( i < n ) ; final Dimension [ ] resolutions = new ArrayList < Dimension > ( map . values ( ) ) . toArray ( new Dimension [ 0 ] ) ; if ( LOG . isDebugEnabled ( ) ) { for ( Dimension d : resolutions ) { LOG . debug ( "Resolution detected {} with format {}" , d , format ) ; } } return resolutions ; } | Use GStreamer to get all possible resolutions . |
23,582 | private Control getControl ( String name ) { Control control = player . getControl ( name ) ; if ( control == null ) { throw new RuntimeException ( "Cannot find format control " + name ) ; } return control ; } | Get player control . |
23,583 | private VideoFormat getSizedVideoFormat ( Dimension size ) { Format [ ] formats = device . getFormats ( ) ; VideoFormat format = null ; for ( Format f : formats ) { if ( ! "RGB" . equalsIgnoreCase ( f . getEncoding ( ) ) || ! ( f instanceof VideoFormat ) ) { continue ; } Dimension d = ( ( VideoFormat ) f ) . getSize ( ) ; if ( d . width == size . width && d . height == size . height ) { format = ( VideoFormat ) f ; break ; } } return format ; } | Get video format for size . |
23,584 | public static void premultiply ( int [ ] p , int offset , int length ) { length += offset ; for ( int i = offset ; i < length ; i ++ ) { int rgb = p [ i ] ; int a = ( rgb >> 24 ) & 0xff ; int r = ( rgb >> 16 ) & 0xff ; int g = ( rgb >> 8 ) & 0xff ; int b = rgb & 0xff ; float f = a * ( 1.0f / 255.0f ) ; r *= f ; g *= f ; b *= f ; p [ i ] = ( a << 24 ) | ( r << 16 ) | ( g << 8 ) | b ; } } | Premultiply a block of pixels |
23,585 | public static int clamp ( int x , int a , int b ) { return ( x < a ) ? a : ( x > b ) ? b : x ; } | Clamp a value to an interval . |
23,586 | public boolean isOnline ( ) { LOG . debug ( "Checking online status for {} at {}" , getName ( ) , getURL ( ) ) ; try { return client . execute ( new HttpHead ( toURI ( getURL ( ) ) ) ) . getStatusLine ( ) . getStatusCode ( ) != 404 ; } catch ( Exception e ) { return false ; } } | This method will send HTTP HEAD request to the camera URL to check whether it s online or offline . It s online when this request succeed and it s offline if any exception occurs or response code is 404 Not Found . |
23,587 | public void lock ( ) { if ( disabled . get ( ) ) { return ; } if ( isLocked ( ) ) { throw new WebcamLockException ( String . format ( "Webcam %s has already been locked" , webcam . getName ( ) ) ) ; } if ( ! locked . compareAndSet ( false , true ) ) { return ; } LOG . debug ( "Lock {}" , webcam ) ; update ( ) ; updater = new LockUpdater ( ) ; updater . start ( ) ; } | Lock webcam . |
23,588 | public void disable ( ) { if ( disabled . compareAndSet ( false , true ) ) { LOG . info ( "Locking mechanism has been disabled in {}" , webcam ) ; if ( updater != null ) { updater . interrupt ( ) ; } } } | Completely disable locking mechanism . After this method is invoked the lock will not have any effect on the webcam runtime . |
23,589 | public void unlock ( ) { if ( disabled . get ( ) ) { return ; } if ( ! locked . compareAndSet ( true , false ) ) { return ; } LOG . debug ( "Unlock {}" , webcam ) ; updater . interrupt ( ) ; write ( - 1 ) ; if ( ! lock . delete ( ) ) { lock . deleteOnExit ( ) ; } } | Unlock webcam . |
23,590 | public boolean isLocked ( ) { if ( disabled . get ( ) ) { return false ; } if ( locked . get ( ) ) { return true ; } if ( ! lock . exists ( ) ) { return false ; } long now = System . currentTimeMillis ( ) ; long tsp = read ( ) ; LOG . trace ( "Lock timestamp {} now {} for {}" , tsp , now , webcam ) ; if ( tsp > now - INTERVAL * 2 ) { return true ; } return false ; } | Check if webcam is locked . |
23,591 | public final BufferedImage decode ( ) throws IOException { if ( ! validPNG ) { return null ; } ColorModel cmodel = new ComponentColorModel ( COLOR_SPACE , BITS , false , false , Transparency . OPAQUE , DATA_TYPE ) ; SampleModel smodel = new ComponentSampleModel ( DATA_TYPE , width , height , 3 , width * 3 , BAND_OFFSETS ) ; byte [ ] bytes = new byte [ width * height * 3 ] ; byte [ ] [ ] data = new byte [ ] [ ] { bytes } ; ByteBuffer buffer = ByteBuffer . wrap ( bytes ) ; decode ( buffer , TextureFormat . RGB ) ; DataBufferByte dbuf = new DataBufferByte ( data , bytes . length , OFFSET ) ; WritableRaster raster = Raster . createWritableRaster ( smodel , dbuf , null ) ; BufferedImage bi = new BufferedImage ( cmodel , raster , false , null ) ; bi . flush ( ) ; return bi ; } | read just one png file if invalid return null |
23,592 | protected void parseArguments ( final Options options , String [ ] cmdArray ) { CommandLineParser parser = new PosixParser ( ) ; try { CommandLine cmd = parser . parse ( options , cmdArray ) ; Option [ ] opts = cmd . getOptions ( ) ; for ( Option o : opts ) { arguments . put ( o . getLongOpt ( ) , o . getValue ( ) == null ? "" : o . getValue ( ) ) ; } } catch ( ParseException e ) { if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( MSG_WRONG_ARGUMENT ) ; } e . printStackTrace ( ) ; } } | parse arguments and add to arguments |
23,593 | public void setPreferredFormats ( List < String > preferredFormats ) { if ( preferredFormats . isEmpty ( ) ) { throw new IllegalArgumentException ( "Preferred formats list must not be empty" ) ; } this . preferredFormats = new ArrayList < > ( preferredFormats ) ; } | Set preferred video formats for this driver . First formats from the list are better and will be selected if available . |
23,594 | protected static WebcamDriver findDriver ( List < String > names , List < Class < ? > > classes ) { for ( String name : names ) { LOG . info ( "Searching driver {}" , name ) ; Class < ? > clazz = null ; for ( Class < ? > c : classes ) { if ( c . getCanonicalName ( ) . equals ( name ) ) { clazz = c ; break ; } } if ( clazz == null ) { try { clazz = Class . forName ( name ) ; } catch ( ClassNotFoundException e ) { LOG . trace ( "Class not found {}, fall thru" , name ) ; } } if ( clazz == null ) { LOG . debug ( "Driver {} not found" , name ) ; continue ; } LOG . info ( "Webcam driver {} has been found" , name ) ; try { return ( WebcamDriver ) clazz . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } return null ; } | Find webcam driver . Scan packages to search drivers specified in the argument . |
23,595 | private static List < Class < ? > > findClasses ( File dir , String pkgname , boolean flat ) throws ClassNotFoundException { List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; if ( ! dir . exists ( ) ) { return classes ; } File [ ] files = dir . listFiles ( ) ; for ( File file : files ) { if ( file . isDirectory ( ) && ! flat ) { classes . addAll ( findClasses ( file , pkgname + "." + file . getName ( ) , flat ) ) ; } else if ( file . getName ( ) . endsWith ( ".class" ) ) { classes . add ( Class . forName ( pkgname + '.' + file . getName ( ) . substring ( 0 , file . getName ( ) . length ( ) - 6 ) ) ) ; } } return classes ; } | Recursive method used to find all classes in a given directory and subdirectories . |
23,596 | public void process ( WebcamTask task ) throws InterruptedException { if ( started . compareAndSet ( false , true ) ) { runner = Executors . newSingleThreadExecutor ( new ProcessorThreadFactory ( ) ) ; runner . execute ( processor ) ; } if ( ! runner . isShutdown ( ) ) { processor . process ( task ) ; } else { throw new RejectedExecutionException ( "Cannot process because processor runner has been already shut down" ) ; } } | Process single webcam task . |
23,597 | public static IpCamDevice register ( IpCamDevice ipcam ) { for ( WebcamDevice d : DEVICES ) { String name = ipcam . getName ( ) ; if ( d . getName ( ) . equals ( name ) ) { throw new WebcamException ( String . format ( "Webcam with name '%s' is already registered" , name ) ) ; } } DEVICES . add ( ipcam ) ; rescan ( ) ; return ipcam ; } | Register IP camera . |
23,598 | public static boolean isRegistered ( IpCamDevice ipcam ) { if ( ipcam == null ) { throw new IllegalArgumentException ( "IP camera device cannot be null" ) ; } Iterator < IpCamDevice > di = DEVICES . iterator ( ) ; while ( di . hasNext ( ) ) { if ( di . next ( ) . getName ( ) . equals ( ipcam . getName ( ) ) ) { return true ; } } return false ; } | Is device registered? |
23,599 | public static boolean isRegistered ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "Device name cannot be null" ) ; } Iterator < IpCamDevice > di = DEVICES . iterator ( ) ; while ( di . hasNext ( ) ) { if ( di . next ( ) . getName ( ) . equals ( name ) ) { return true ; } } return false ; } | Is device with given name registered? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.