idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
29,400 | @ SuppressWarnings ( "unchecked" ) public < T extends Component > T createComponent ( final String name , final PropertyList properties , final ComponentList < ? extends Component > components ) { Component component ; ComponentFactory factory = getFactory ( name ) ; if ( factory != null ) { component = factory . createComponent ( properties , components ) ; } else { throw new IllegalArgumentException ( "Unsupported component [" + name + "]" ) ; } return ( T ) component ; } | Creates a component which contains sub - components . Currently the only such component is VTIMEZONE . |
29,401 | public Calendar build ( final InputStream in ) throws IOException , ParserException { return build ( new InputStreamReader ( in , DEFAULT_CHARSET ) ) ; } | Builds an iCalendar model from the specified input stream . |
29,402 | public Calendar build ( final UnfoldingReader uin ) throws IOException , ParserException { parser . parse ( uin , contentHandler ) ; return calendar ; } | Build an iCalendar model by parsing data from the specified reader . |
29,403 | public final boolean add ( final Date date ) { if ( ! this . isUtc ( ) && this . getTimeZone ( ) == null ) { if ( date instanceof DateTime ) { DateTime dateTime = ( DateTime ) date ; if ( dateTime . isUtc ( ) ) { this . setUtc ( true ) ; } else { this . setTimeZone ( dateTime . getTimeZone ( ) ) ; } } } if ( date instanceof DateTime ) { DateTime dateTime = ( DateTime ) date ; if ( isUtc ( ) ) { dateTime . setUtc ( true ) ; } else { dateTime . setTimeZone ( getTimeZone ( ) ) ; } } else if ( ! Value . DATE . equals ( getType ( ) ) ) { final DateTime dateTime = new DateTime ( date ) ; dateTime . setTimeZone ( getTimeZone ( ) ) ; return dates . add ( dateTime ) ; } return dates . add ( date ) ; } | Add a date to the list . The date will be updated to reflect the timezone of this list . |
29,404 | public VTimeZone loadVTimeZone ( String id ) throws IOException , ParserException , ParseException { Validate . notBlank ( id , "Invalid TimeZone ID: [%s]" , id ) ; if ( ! cache . containsId ( id ) ) { final URL resource = ResourceLoader . getResource ( resourcePrefix + id + ".ics" ) ; if ( resource != null ) { try ( InputStream in = resource . openStream ( ) ) { final CalendarBuilder builder = new CalendarBuilder ( ) ; final Calendar calendar = builder . build ( in ) ; final VTimeZone vTimeZone = ( VTimeZone ) calendar . getComponent ( Component . VTIMEZONE ) ; if ( ! "false" . equals ( Configurator . getProperty ( UPDATE_ENABLED ) . orElse ( "true" ) ) ) { return updateDefinition ( vTimeZone ) ; } if ( vTimeZone != null ) { cache . putIfAbsent ( id , vTimeZone ) ; } } } else { return generateTimezoneForId ( id ) ; } } return cache . getTimezone ( id ) ; } | Loads an existing VTimeZone from the classpath corresponding to the specified Java timezone . |
29,405 | public final < C extends CalendarComponent > ComponentList < C > getComponents ( final String name ) { return getComponents ( ) . getComponents ( name ) ; } | Convenience method for retrieving a list of named components . |
29,406 | public void assertOneOrLess ( final String paramName , final ParameterList parameters ) throws ValidationException { if ( parameters . getParameters ( paramName ) . size ( ) > 1 ) { throw new ValidationException ( ASSERT_ONE_OR_LESS_MESSAGE , new Object [ ] { paramName } ) ; } } | Ensure a parameter occurs no more than once . |
29,407 | public void assertOne ( final String paramName , final ParameterList parameters ) throws ValidationException { if ( parameters . getParameters ( paramName ) . size ( ) != 1 ) { throw new ValidationException ( ASSERT_ONE_MESSAGE , new Object [ ] { paramName } ) ; } } | Ensure a parameter occurs once . |
29,408 | public void assertNone ( final String paramName , final ParameterList parameters ) throws ValidationException { if ( parameters . getParameter ( paramName ) != null ) { throw new ValidationException ( ASSERT_NONE_MESSAGE , new Object [ ] { paramName } ) ; } } | Ensure a parameter doesn t occur in the specified list . |
29,409 | public PeriodList calculateRecurrenceSet ( final Period period ) { PeriodList periods = new PeriodList ( ) ; for ( Component component : getRevisions ( ) ) { periods = periods . add ( component . calculateRecurrenceSet ( period ) ) ; } return periods ; } | Calculate all recurring periods for the specified date range . This method will take all revisions into account when generating the set . |
29,410 | public final DateList getDates ( final Date periodStart , final Date periodEnd , final Value value ) { return getDates ( periodStart , periodStart , periodEnd , value , - 1 ) ; } | Returns a list of start dates in the specified period represented by this recur . Any date fields not specified by this recur are retained from the period start and as such you should ensure the period start is initialised correctly . |
29,411 | public final DateList getDates ( final Date seed , final Period period , final Value value ) { return getDates ( seed , period . getStart ( ) , period . getEnd ( ) , value , - 1 ) ; } | Convenience method for retrieving recurrences in a specified period . |
29,412 | public final Date getNextDate ( final Date seed , final Date startDate ) { final Calendar cal = getCalendarInstance ( seed , true ) ; final Calendar rootSeed = ( Calendar ) cal . clone ( ) ; if ( count == null ) { final Calendar seededCal = ( Calendar ) cal . clone ( ) ; while ( seededCal . getTime ( ) . before ( startDate ) ) { cal . setTime ( seededCal . getTime ( ) ) ; increment ( seededCal ) ; } } int invalidCandidateCount = 0 ; int noCandidateIncrementCount = 0 ; Date candidate = null ; final Value value = seed instanceof DateTime ? Value . DATE_TIME : Value . DATE ; while ( true ) { final Date candidateSeed = Dates . getInstance ( cal . getTime ( ) , value ) ; if ( getUntil ( ) != null && candidate != null && candidate . after ( getUntil ( ) ) ) { break ; } if ( getCount ( ) > 0 && invalidCandidateCount >= getCount ( ) ) { break ; } if ( Value . DATE_TIME . equals ( value ) ) { if ( ( ( DateTime ) seed ) . isUtc ( ) ) { ( ( DateTime ) candidateSeed ) . setUtc ( true ) ; } else { ( ( DateTime ) candidateSeed ) . setTimeZone ( ( ( DateTime ) seed ) . getTimeZone ( ) ) ; } } final DateList candidates = getCandidates ( rootSeed , candidateSeed , value ) ; if ( ! candidates . isEmpty ( ) ) { noCandidateIncrementCount = 0 ; Collections . sort ( candidates ) ; for ( Date candidate1 : candidates ) { candidate = candidate1 ; if ( ! candidate . before ( seed ) ) { if ( ! candidate . after ( startDate ) ) { invalidCandidateCount ++ ; } else if ( getCount ( ) > 0 && invalidCandidateCount >= getCount ( ) ) { break ; } else if ( ! ( getUntil ( ) != null && candidate . after ( getUntil ( ) ) ) ) { return candidate ; } } } } else { noCandidateIncrementCount ++ ; if ( ( maxIncrementCount > 0 ) && ( noCandidateIncrementCount > maxIncrementCount ) ) { break ; } } increment ( cal ) ; } return null ; } | Returns the the next date of this recurrence given a seed date and start date . The seed date indicates the start of the fist occurrence of this recurrence . The start date is the starting date to search for the next recurrence . Return null if there is no occurrence date after start date . |
29,413 | private void increment ( final Calendar cal ) { final int calInterval = ( getInterval ( ) >= 1 ) ? getInterval ( ) : 1 ; cal . add ( calIncField , calInterval ) ; } | Increments the specified calendar according to the frequency and interval specified in this recurrence rule . |
29,414 | public final void output ( final Calendar calendar , final OutputStream out ) throws IOException , ValidationException { output ( calendar , new OutputStreamWriter ( out , DEFAULT_CHARSET ) ) ; } | Outputs an iCalender string to the specified output stream . |
29,415 | public final void output ( final Calendar calendar , final Writer out ) throws IOException , ValidationException { if ( isValidating ( ) ) { calendar . validate ( ) ; } try ( FoldingWriter writer = new FoldingWriter ( out , foldLength ) ) { writer . write ( calendar . toString ( ) ) ; } } | Outputs an iCalender string to the specified writer . |
29,416 | private void parseCalendar ( final StreamTokenizer tokeniser , Reader in , final ContentHandler handler ) throws IOException , ParseException , URISyntaxException , ParserException { assertToken ( tokeniser , in , ':' ) ; assertToken ( tokeniser , in , Calendar . VCALENDAR , true , false ) ; assertToken ( tokeniser , in , StreamTokenizer . TT_EOL ) ; handler . startCalendar ( ) ; propertyListParser . parse ( tokeniser , in , handler ) ; componentListParser . parse ( tokeniser , in , handler ) ; assertToken ( tokeniser , in , ':' ) ; assertToken ( tokeniser , in , Calendar . VCALENDAR , true , false ) ; handler . endCalendar ( ) ; } | Parses an iCalendar VCALENDAR from the specified stream tokeniser . |
29,417 | private void parseCalendarList ( final StreamTokenizer tokeniser , Reader in , final ContentHandler handler ) throws IOException , ParseException , URISyntaxException , ParserException { int ntok = assertToken ( tokeniser , in , Calendar . BEGIN , false , true ) ; while ( ntok != StreamTokenizer . TT_EOF ) { parseCalendar ( tokeniser , in , handler ) ; ntok = absorbWhitespace ( tokeniser , in , true ) ; } } | Parses multiple VCALENDARs from the specified stream tokeniser . |
29,418 | private int assertToken ( final StreamTokenizer tokeniser , Reader in , final String token ) throws IOException , ParserException { return assertToken ( tokeniser , in , token , false , false ) ; } | Asserts that the next token in the stream matches the specified token . This method is case - sensitive . |
29,419 | private int skipNewLines ( StreamTokenizer tokeniser , Reader in , String token ) throws ParserException , IOException { for ( int i = 0 ; ; i ++ ) { try { return assertToken ( tokeniser , in , StreamTokenizer . TT_WORD ) ; } catch ( ParserException exc ) { if ( i == IGNORE_BEGINNING_NON_WORD_COUNT ) { throw exc ; } } } } | Skip newlines and linefeed at the beginning . |
29,420 | private String getSvalIgnoringBom ( StreamTokenizer tokeniser , Reader in , String token ) { if ( tokeniser . sval != null ) { if ( tokeniser . sval . contains ( token ) ) { return token ; } } return tokeniser . sval ; } | Ignore BOM character . |
29,421 | private int absorbWhitespace ( final StreamTokenizer tokeniser , Reader in , boolean ignoreEOF ) throws IOException , ParserException { int ntok ; while ( ( ntok = nextToken ( tokeniser , in , ignoreEOF ) ) == StreamTokenizer . TT_EOL ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Absorbing extra whitespace.." ) ; } } if ( log . isTraceEnabled ( ) ) { log . trace ( "Aborting: absorbing extra whitespace complete" ) ; } return ntok ; } | Absorbs extraneous newlines . |
29,422 | private int nextToken ( StreamTokenizer tokeniser , Reader in , boolean ignoreEOF ) throws IOException , ParserException { int token = tokeniser . nextToken ( ) ; if ( ! ignoreEOF && token == StreamTokenizer . TT_EOF ) { throw new ParserException ( "Unexpected end of file" , getLineNumber ( tokeniser , in ) ) ; } return token ; } | Reads the next token from the tokeniser . This method throws a ParseException when reading EOF . |
29,423 | public ComponentList < T > getComponents ( final String propertyValue ) { ComponentList < T > components = index . get ( propertyValue ) ; if ( components == null ) { components = EMPTY_LIST ; } return components ; } | Returns a list of components containing a property with the specified value . |
29,424 | public T getComponent ( final String propertyValue ) { final ComponentList < T > components = getComponents ( propertyValue ) ; if ( ! components . isEmpty ( ) ) { return components . get ( 0 ) ; } return null ; } | Returns the first component containing a property with the specified value . |
29,425 | public void setTimeZone ( final TimeZone timezone ) { if ( dates == null ) { throw new UnsupportedOperationException ( "TimeZone is not applicable to current value" ) ; } this . timeZone = timezone ; if ( timezone != null ) { if ( ! Value . DATE_TIME . equals ( getDates ( ) . getType ( ) ) ) { throw new UnsupportedOperationException ( "TimeZone is not applicable to current value" ) ; } dates . setTimeZone ( timezone ) ; getParameters ( ) . remove ( getParameter ( Parameter . TZID ) ) ; final TzId tzId = new TzId ( timezone . getID ( ) ) ; getParameters ( ) . replace ( tzId ) ; } else { setUtc ( false ) ; } } | Sets the timezone associated with this property . |
29,426 | public final Dur negate ( ) { final Dur negated = new Dur ( days , hours , minutes , seconds ) ; negated . weeks = weeks ; negated . negative = ! negative ; return negated ; } | Provides a negation of this instance . |
29,427 | public final Dur add ( final Dur duration ) { if ( ( ! isNegative ( ) && duration . isNegative ( ) ) || ( isNegative ( ) && ! duration . isNegative ( ) ) ) { throw new IllegalArgumentException ( "Cannot add a negative and a positive duration" ) ; } Dur sum ; if ( weeks > 0 && duration . weeks > 0 ) { sum = new Dur ( weeks + duration . weeks ) ; } else { int daySum = ( weeks > 0 ) ? weeks * DAYS_PER_WEEK + days : days ; int hourSum = hours ; int minuteSum = minutes ; int secondSum = seconds ; if ( ( secondSum + duration . seconds ) / SECONDS_PER_MINUTE > 0 ) { minuteSum += ( secondSum + duration . seconds ) / SECONDS_PER_MINUTE ; secondSum = ( secondSum + duration . seconds ) % SECONDS_PER_MINUTE ; } else { secondSum += duration . seconds ; } if ( ( minuteSum + duration . minutes ) / MINUTES_PER_HOUR > 0 ) { hourSum += ( minuteSum + duration . minutes ) / MINUTES_PER_HOUR ; minuteSum = ( minuteSum + duration . minutes ) % MINUTES_PER_HOUR ; } else { minuteSum += duration . minutes ; } if ( ( hourSum + duration . hours ) / HOURS_PER_DAY > 0 ) { daySum += ( hourSum + duration . hours ) / HOURS_PER_DAY ; hourSum = ( hourSum + duration . hours ) % HOURS_PER_DAY ; } else { hourSum += duration . hours ; } daySum += ( duration . weeks > 0 ) ? duration . weeks * DAYS_PER_WEEK + duration . days : duration . days ; sum = new Dur ( daySum , hourSum , minuteSum , secondSum ) ; } sum . negative = negative ; return sum ; } | Add two durations . Durations may only be added if they are both positive or both negative durations . |
29,428 | public final int compareTo ( final Dur arg0 ) { int result ; if ( isNegative ( ) != arg0 . isNegative ( ) ) { if ( isNegative ( ) ) { return Integer . MIN_VALUE ; } else { return Integer . MAX_VALUE ; } } else if ( getWeeks ( ) != arg0 . getWeeks ( ) ) { result = getWeeks ( ) - arg0 . getWeeks ( ) ; } else if ( getDays ( ) != arg0 . getDays ( ) ) { result = getDays ( ) - arg0 . getDays ( ) ; } else if ( getHours ( ) != arg0 . getHours ( ) ) { result = getHours ( ) - arg0 . getHours ( ) ; } else if ( getMinutes ( ) != arg0 . getMinutes ( ) ) { result = getMinutes ( ) - arg0 . getMinutes ( ) ; } else { result = getSeconds ( ) - arg0 . getSeconds ( ) ; } if ( isNegative ( ) ) { return - result ; } else { return result ; } } | Compares this duration with another acording to their length . |
29,429 | protected Calendar getCalendarInstance ( final Date date , final boolean lenient ) { Calendar cal = Dates . getCalendarInstance ( date ) ; cal . setMinimalDaysInFirstWeek ( 4 ) ; cal . setFirstDayOfWeek ( calendarWeekStartDay ) ; cal . setLenient ( lenient ) ; cal . setTime ( date ) ; return cal ; } | Construct a Calendar object and sets the time . |
29,430 | public final < C extends Property > PropertyList < C > getProperties ( final String name ) { return getProperties ( ) . getProperties ( name ) ; } | Convenience method for retrieving a list of named properties . |
29,431 | public final < T extends Property > T getProperty ( final String name ) { return ( T ) getProperties ( ) . getProperty ( name ) ; } | Convenience method for retrieving a named property . |
29,432 | protected final Property getRequiredProperty ( String name ) throws ConstraintViolationException { Property p = getProperties ( ) . getProperty ( name ) ; if ( p == null ) { throw new ConstraintViolationException ( String . format ( "Missing %s property" , name ) ) ; } return p ; } | Convenience method for retrieving a required named property . |
29,433 | public static WeekDay getWeekDay ( final Calendar cal ) { return new WeekDay ( getDay ( cal . get ( Calendar . DAY_OF_WEEK ) ) , 0 ) ; } | Returns a weekday representation of the specified calendar . |
29,434 | public static WeekDay getDay ( final int calDay ) { WeekDay day = null ; switch ( calDay ) { case Calendar . SUNDAY : day = SU ; break ; case Calendar . MONDAY : day = MO ; break ; case Calendar . TUESDAY : day = TU ; break ; case Calendar . WEDNESDAY : day = WE ; break ; case Calendar . THURSDAY : day = TH ; break ; case Calendar . FRIDAY : day = FR ; break ; case Calendar . SATURDAY : day = SA ; break ; default : break ; } return day ; } | Returns the corresponding day constant to the specified java . util . Calendar . DAY_OF_WEEK property . |
29,435 | @ SuppressWarnings ( "unchecked" ) public final Collection < T > filter ( final Collection < T > c ) { if ( getRules ( ) != null && getRules ( ) . length > 0 ) { Collection < T > filtered ; try { filtered = c . getClass ( ) . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { filtered = new ArrayList < T > ( ) ; } if ( type == MATCH_ALL ) { filtered . addAll ( matchAll ( c ) ) ; } else { filtered . addAll ( matchAny ( c ) ) ; } return filtered ; } return c ; } | Filter the given collection into a new collection . |
29,436 | @ SuppressWarnings ( "unchecked" ) public final T [ ] filter ( final T [ ] objects ) { final Collection < T > filtered = filter ( Arrays . asList ( objects ) ) ; try { return filtered . toArray ( ( T [ ] ) Array . newInstance ( objects . getClass ( ) , filtered . size ( ) ) ) ; } catch ( ArrayStoreException ase ) { Logger log = LoggerFactory . getLogger ( Filter . class ) ; log . warn ( "Error converting to array - using default approach" , ase ) ; } return ( T [ ] ) filtered . toArray ( ) ; } | Returns a filtered subset of the specified array . |
29,437 | private PeriodList getConsumedTime ( final ComponentList < CalendarComponent > components , final DateTime rangeStart , final DateTime rangeEnd ) { final PeriodList periods = new PeriodList ( ) ; for ( final Component event : components . getComponents ( Component . VEVENT ) ) { periods . addAll ( ( ( VEvent ) event ) . getConsumedTime ( rangeStart , rangeEnd , false ) ) ; } return periods . normalise ( ) ; } | Creates a list of periods representing the time consumed by the specified list of components . |
29,438 | private static InetAddress findNonLoopbackAddress ( ) throws SocketException { final Enumeration < NetworkInterface > enumInterfaceAddress = NetworkInterface . getNetworkInterfaces ( ) ; while ( enumInterfaceAddress . hasMoreElements ( ) ) { final NetworkInterface netIf = enumInterfaceAddress . nextElement ( ) ; final Enumeration < InetAddress > enumInetAdress = netIf . getInetAddresses ( ) ; while ( enumInetAdress . hasMoreElements ( ) ) { final InetAddress address = enumInetAdress . nextElement ( ) ; if ( ! address . isLoopbackAddress ( ) ) { return address ; } } } return null ; } | Find a non loopback address for this machine on which to start the server . |
29,439 | public final T getComponent ( final String aName ) { for ( final T c : this ) { if ( c . getName ( ) . equals ( aName ) ) { return c ; } } return null ; } | Returns the first component of specified name . |
29,440 | @ SuppressWarnings ( "unchecked" ) public final < C extends T > ComponentList < C > getComponents ( final String name ) { final ComponentList < C > components = new ComponentList < C > ( ) ; for ( final T c : this ) { if ( c . getName ( ) . equals ( name ) ) { components . add ( ( C ) c ) ; } } return components ; } | Returns a list containing all components with specified name . |
29,441 | private static DateTime uniqueTimestamp ( ) { long currentMillis ; synchronized ( FixedUidGenerator . class ) { currentMillis = System . currentTimeMillis ( ) ; if ( currentMillis < lastMillis ) { currentMillis = lastMillis ; } if ( currentMillis - lastMillis < Dates . MILLIS_PER_SECOND ) { currentMillis += Dates . MILLIS_PER_SECOND ; } lastMillis = currentMillis ; } final DateTime timestamp = new DateTime ( currentMillis ) ; timestamp . setUtc ( true ) ; return timestamp ; } | Generates a timestamp guaranteed to be unique for the current JVM instance . |
29,442 | public final boolean add ( final Period period ) { if ( isUtc ( ) ) { period . setUtc ( true ) ; } else { period . setTimeZone ( timezone ) ; } return periods . add ( period ) ; } | Add a period to the list . |
29,443 | public final PeriodList add ( final PeriodList periods ) { if ( periods != null ) { final PeriodList newList = new PeriodList ( ) ; newList . addAll ( this ) ; newList . addAll ( periods ) ; return newList . normalise ( ) ; } return this ; } | A convenience method that combines all the periods in the specified list to this list . The result returned is a new PeriodList instance except where no periods are specified in the arguments . In such cases this instance is returned . |
29,444 | public final PeriodList subtract ( final PeriodList subtractions ) { if ( subtractions == null || subtractions . isEmpty ( ) ) { return this ; } PeriodList result = this ; PeriodList tmpResult = new PeriodList ( ) ; for ( final Period subtraction : subtractions ) { for ( final Period period : result ) { tmpResult . addAll ( period . subtract ( subtraction ) ) ; } result = tmpResult ; tmpResult = new PeriodList ( ) ; } return result ; } | Subtracts the intersection of this list with the specified list of periods from this list and returns the results as a new period list . If no intersection is identified this list is returned . |
29,445 | public static FileFilter getFileFilter ( ) { return new FileFilter ( ) { public boolean accept ( File pathname ) { return ! pathname . isHidden ( ) && ( pathname . isFile ( ) && Engines . getRecognizedExtensions ( ) . contains ( fileExt ( pathname ) ) ) || ( directoryOnlyIfNotIgnored ( pathname ) ) ; } } ; } | Filters files based on their file extension . |
29,446 | public static File getRunningLocation ( ) throws Exception { String codePath = FileUtil . class . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . getPath ( ) ; String decodedPath = URLDecoder . decode ( codePath , "UTF-8" ) ; File codeFile = new File ( decodedPath ) ; if ( ! codeFile . exists ( ) ) { throw new Exception ( "Cannot locate running location of JBake!" ) ; } File codeFolder = codeFile . getParentFile ( ) . getParentFile ( ) ; if ( ! codeFolder . exists ( ) ) { throw new Exception ( "Cannot locate running location of JBake!" ) ; } return codeFolder ; } | Works out the folder where JBake is running from . |
29,447 | public static String sha1 ( File sourceFile ) throws Exception { byte [ ] buffer = new byte [ 1024 ] ; MessageDigest complete = MessageDigest . getInstance ( "SHA-1" ) ; updateDigest ( complete , sourceFile , buffer ) ; byte [ ] bytes = complete . digest ( ) ; StringBuilder sb = new StringBuilder ( ) ; for ( byte b : bytes ) { sb . append ( String . format ( "%02x" , b ) ) ; } return sb . toString ( ) ; } | Computes the hash of a file or directory . |
29,448 | public static boolean isFileInDirectory ( File file , File directory ) throws IOException { return ( file . exists ( ) && ! file . isHidden ( ) && directory . isDirectory ( ) && file . getCanonicalPath ( ) . startsWith ( directory . getCanonicalPath ( ) ) ) ; } | Utility method to determine if a given file is located somewhere in the directory provided . |
29,449 | private void crawl ( File path ) { File [ ] contents = path . listFiles ( FileUtil . getFileFilter ( ) ) ; if ( contents != null ) { Arrays . sort ( contents ) ; for ( File sourceFile : contents ) { if ( sourceFile . isFile ( ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Processing [" ) . append ( sourceFile . getPath ( ) ) . append ( "]... " ) ; String sha1 = buildHash ( sourceFile ) ; String uri = buildURI ( sourceFile ) ; boolean process = true ; DocumentStatus status = DocumentStatus . NEW ; for ( String docType : DocumentTypes . getDocumentTypes ( ) ) { status = findDocumentStatus ( docType , uri , sha1 ) ; if ( status == DocumentStatus . UPDATED ) { sb . append ( " : modified " ) ; db . deleteContent ( docType , uri ) ; } else if ( status == DocumentStatus . IDENTICAL ) { sb . append ( " : same " ) ; process = false ; } if ( ! process ) { break ; } } if ( DocumentStatus . NEW == status ) { sb . append ( " : new " ) ; } if ( process ) { crawlSourceFile ( sourceFile , sha1 , uri ) ; } LOGGER . info ( "{}" , sb ) ; } if ( sourceFile . isDirectory ( ) ) { crawl ( sourceFile ) ; } } } } | Crawl all files and folders looking for content . |
29,450 | private String createUri ( String uri ) { try { return FileUtil . URI_SEPARATOR_CHAR + FilenameUtils . getPath ( uri ) + URLEncoder . encode ( FilenameUtils . getBaseName ( uri ) , StandardCharsets . UTF_8 . name ( ) ) + config . getOutputExtension ( ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "Missing UTF-8 encoding??" , e ) ; } } | commons - codec s URLCodec could be used when we add that dependency . |
29,451 | public Map < String , Object > processFile ( File file ) { ParserEngine engine = Engines . get ( FileUtil . fileExt ( file ) ) ; if ( engine == null ) { LOGGER . error ( "Unable to find suitable markup engine for {}" , file ) ; return null ; } return engine . parse ( config , file ) ; } | Process the file by parsing the contents . |
29,452 | public Map < String , Object > parse ( JBakeConfiguration config , File file ) { this . configuration = config ; List < String > fileContents ; try ( InputStream is = new FileInputStream ( file ) ) { fileContents = IOUtils . readLines ( is , config . getRenderEncoding ( ) ) ; } catch ( IOException e ) { LOGGER . error ( "Error while opening file {}" , file , e ) ; return null ; } boolean hasHeader = hasHeader ( fileContents ) ; ParserContext context = new ParserContext ( file , fileContents , config , hasHeader ) ; if ( hasHeader ) { processDefaultHeader ( context ) ; } processHeader ( context ) ; setModelDefaultsIfNotSetInHeader ( context ) ; sanitizeTags ( context ) ; if ( context . getType ( ) . isEmpty ( ) || context . getStatus ( ) . isEmpty ( ) ) { LOGGER . warn ( "Parsing skipped (missing type or status value in header meta data) for file {}!" , file ) ; return null ; } processDefaultBody ( context ) ; if ( validate ( context ) ) { processBody ( context ) ; } else { LOGGER . error ( "Incomplete source file ({}) for markup engine: {}" , file , getClass ( ) . getSimpleName ( ) ) ; return null ; } return context . getDocumentModel ( ) ; } | Parse given file to extract as much infos as possible |
29,453 | private boolean hasHeader ( List < String > contents ) { boolean headerValid = true ; boolean statusFound = false ; boolean typeFound = false ; if ( ! headerSeparatorDemarcatesHeader ( contents ) ) { return false ; } for ( String line : contents ) { if ( hasHeaderSeparator ( line ) ) { LOGGER . debug ( "Header separator found" ) ; break ; } if ( isTypeProperty ( line ) ) { LOGGER . debug ( "Type property found" ) ; typeFound = true ; } if ( isStatusProperty ( line ) ) { LOGGER . debug ( "Status property found" ) ; statusFound = true ; } if ( ! line . isEmpty ( ) && ! line . contains ( "=" ) ) { LOGGER . error ( "Property found without assignment [{}]" , line ) ; headerValid = false ; } } return headerValid && ( statusFound || hasDefaultStatus ( ) ) && ( typeFound || hasDefaultType ( ) ) ; } | Checks if the file has a meta - data header . |
29,454 | private boolean headerSeparatorDemarcatesHeader ( List < String > contents ) { List < String > subContents = null ; int index = contents . indexOf ( configuration . getHeaderSeparator ( ) ) ; if ( index != - 1 ) { subContents = contents . subList ( 0 , index ) ; for ( String line : subContents ) { if ( ! line . contains ( "=" ) && ! line . isEmpty ( ) ) { return false ; } } return true ; } else { return false ; } } | Checks if header separator demarcates end of metadata header |
29,455 | private void processDefaultHeader ( ParserContext context ) { for ( String line : context . getFileLines ( ) ) { if ( hasHeaderSeparator ( line ) ) { break ; } processHeaderLine ( line , context . getDocumentModel ( ) ) ; } } | Process the header of the file . |
29,456 | private void processDefaultBody ( ParserContext context ) { StringBuilder body = new StringBuilder ( ) ; boolean inBody = false ; for ( String line : context . getFileLines ( ) ) { if ( inBody ) { body . append ( line ) . append ( "\n" ) ; } if ( line . equals ( configuration . getHeaderSeparator ( ) ) ) { inBody = true ; } } if ( body . length ( ) == 0 ) { for ( String line : context . getFileLines ( ) ) { body . append ( line ) . append ( "\n" ) ; } } context . setBody ( body . toString ( ) ) ; } | Process the body of the file . |
29,457 | public static void extract ( InputStream is , File outputFolder ) throws IOException { ZipInputStream zis = new ZipInputStream ( is ) ; ZipEntry entry ; byte [ ] buffer = new byte [ 1024 ] ; while ( ( entry = zis . getNextEntry ( ) ) != null ) { File outputFile = new File ( outputFolder . getCanonicalPath ( ) + File . separatorChar + entry . getName ( ) ) ; File outputParent = new File ( outputFile . getParent ( ) ) ; outputParent . mkdirs ( ) ; if ( entry . isDirectory ( ) ) { if ( ! outputFile . exists ( ) ) { outputFile . mkdir ( ) ; } } else { try ( FileOutputStream fos = new FileOutputStream ( outputFile ) ) { int len ; while ( ( len = zis . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } } } } } | Extracts content of Zip file to specified output path . |
29,458 | public void copy ( File path ) { FileFilter filter = new FileFilter ( ) { public boolean accept ( File file ) { return ( ! config . getAssetIgnoreHidden ( ) || ! file . isHidden ( ) ) && ( file . isFile ( ) || FileUtil . directoryOnlyIfNotIgnored ( file ) ) ; } } ; copy ( path , config . getDestinationFolder ( ) , filter ) ; } | Copy all files from supplied path . |
29,459 | public void copySingleFile ( File asset ) { try { if ( ! asset . isDirectory ( ) ) { String targetPath = config . getDestinationFolder ( ) . getCanonicalPath ( ) + File . separatorChar + assetSubPath ( asset ) ; LOGGER . info ( "Copying single asset file to [{}]" , targetPath ) ; copyFile ( asset , new File ( targetPath ) ) ; } else { LOGGER . info ( "Skip copying single asset file [{}]. Is a directory." , asset . getPath ( ) ) ; } } catch ( IOException io ) { LOGGER . error ( "Failed to copy the asset file." , io ) ; } } | Copy one asset file at a time . |
29,460 | public boolean isAssetFile ( File path ) { boolean isAsset = false ; try { if ( FileUtil . directoryOnlyIfNotIgnored ( path . getParentFile ( ) ) ) { if ( FileUtil . isFileInDirectory ( path , config . getAssetFolder ( ) ) ) { isAsset = true ; } else if ( FileUtil . isFileInDirectory ( path , config . getContentFolder ( ) ) && FileUtil . getNotContentFileFilter ( ) . accept ( path ) ) { isAsset = true ; } } } catch ( IOException ioe ) { LOGGER . error ( "Unable to determine the path to asset file {}" , path . getPath ( ) , ioe ) ; } return isAsset ; } | Determine if a given file is an asset file . |
29,461 | public void bake ( File fileToBake ) { Asset asset = utensils . getAsset ( ) ; if ( asset . isAssetFile ( fileToBake ) ) { LOGGER . info ( "Baking a change to an asset [" + fileToBake . getPath ( ) + "]" ) ; asset . copySingleFile ( fileToBake ) ; } else { LOGGER . info ( "Playing it safe and running a full bake..." ) ; bake ( ) ; } } | Responsible for incremental baking typically a single file at a time . |
29,462 | public void bake ( ) { ContentStore contentStore = utensils . getContentStore ( ) ; JBakeConfiguration config = utensils . getConfiguration ( ) ; Crawler crawler = utensils . getCrawler ( ) ; Asset asset = utensils . getAsset ( ) ; try { final long start = new Date ( ) . getTime ( ) ; LOGGER . info ( "Baking has started..." ) ; contentStore . startup ( ) ; updateDocTypesFromConfiguration ( ) ; contentStore . updateSchema ( ) ; contentStore . updateAndClearCacheIfNeeded ( config . getClearCache ( ) , config . getTemplateFolder ( ) ) ; crawler . crawl ( ) ; renderContent ( ) ; asset . copy ( ) ; asset . copyAssetsFromContent ( config . getContentFolder ( ) ) ; errors . addAll ( asset . getErrors ( ) ) ; LOGGER . info ( "Baking finished!" ) ; long end = new Date ( ) . getTime ( ) ; LOGGER . info ( "Baked {} items in {}ms" , renderedCount , end - start ) ; if ( ! errors . isEmpty ( ) ) { LOGGER . error ( "Failed to bake {} item(s)!" , errors . size ( ) ) ; } } finally { contentStore . close ( ) ; contentStore . shutdown ( ) ; } } | All the good stuff happens in here ... |
29,463 | private void updateDocTypesFromConfiguration ( ) { resetDocumentTypesAndExtractors ( ) ; JBakeConfiguration config = utensils . getConfiguration ( ) ; ModelExtractorsDocumentTypeListener listener = new ModelExtractorsDocumentTypeListener ( ) ; DocumentTypes . addListener ( listener ) ; for ( String docType : config . getDocumentTypes ( ) ) { DocumentTypes . addDocumentType ( docType ) ; } } | Iterates over the configuration searching for keys like template . index . file = ... in order to register new document types . |
29,464 | @ SuppressWarnings ( "unchecked" ) public static String [ ] toStringArray ( Object entry ) { if ( entry instanceof String [ ] ) { return ( String [ ] ) entry ; } else if ( entry instanceof OTrackedList ) { OTrackedList < String > list = ( OTrackedList < String > ) entry ; return list . toArray ( new String [ list . size ( ) ] ) ; } return new String [ 0 ] ; } | Converts a DB list into a String array |
29,465 | private Map < String , Object > getContentForNav ( Map < String , Object > document ) { Map < String , Object > navDocument = new HashMap < > ( ) ; navDocument . put ( Attributes . NO_EXTENSION_URI , document . get ( Attributes . NO_EXTENSION_URI ) ) ; navDocument . put ( Attributes . URI , document . get ( Attributes . URI ) ) ; navDocument . put ( Attributes . TITLE , document . get ( Attributes . TITLE ) ) ; return navDocument ; } | Creates a simple content model to use in individual post navigations . |
29,466 | public ODocument mergeDocument ( Map < String , ? extends Object > incomingDocMap ) { String sourceUri = ( String ) incomingDocMap . get ( DocumentAttributes . SOURCE_URI . toString ( ) ) ; if ( null == sourceUri ) throw new IllegalArgumentException ( "Document sourceUri is null." ) ; String docType = ( String ) incomingDocMap . get ( Crawler . Attributes . TYPE ) ; if ( null == docType ) throw new IllegalArgumentException ( "Document docType is null." ) ; String sql = "SELECT * FROM " + docType + " WHERE sourceuri=?" ; activateOnCurrentThread ( ) ; List < ODocument > results = db . command ( new OSQLSynchQuery < ODocument > ( sql ) ) . execute ( sourceUri ) ; if ( results . size ( ) == 0 ) throw new JBakeException ( "No document with sourceUri '" + sourceUri + "'." ) ; ODocument incomingDoc = new ODocument ( docType ) ; incomingDoc . fromMap ( incomingDocMap ) ; ODocument merged = results . get ( 0 ) . merge ( incomingDoc , true , false ) ; return merged ; } | Get a document by sourceUri and update it from the given map . |
29,467 | public void run ( File outputFolder , File templateLocationFolder , String templateType ) throws Exception { if ( ! outputFolder . canWrite ( ) ) { throw new Exception ( "Output folder is not writeable!" ) ; } File [ ] contents = outputFolder . listFiles ( ) ; boolean safe = true ; if ( contents != null ) { for ( File content : contents ) { if ( content . isDirectory ( ) ) { if ( content . getName ( ) . equalsIgnoreCase ( config . getTemplateFolderName ( ) ) ) { safe = false ; } if ( content . getName ( ) . equalsIgnoreCase ( config . getContentFolderName ( ) ) ) { safe = false ; } if ( content . getName ( ) . equalsIgnoreCase ( config . getAssetFolderName ( ) ) ) { safe = false ; } } } } if ( ! safe ) { throw new Exception ( String . format ( "Output folder '%s' already contains structure!" , outputFolder . getAbsolutePath ( ) ) ) ; } if ( config . getExampleProjectByType ( templateType ) != null ) { File templateFile = new File ( templateLocationFolder , config . getExampleProjectByType ( templateType ) ) ; if ( ! templateFile . exists ( ) ) { throw new Exception ( "Cannot find example project file: " + templateFile . getPath ( ) ) ; } ZipUtil . extract ( new FileInputStream ( templateFile ) , outputFolder ) ; } else { throw new Exception ( "Cannot locate example project type: " + templateType ) ; } } | Performs checks on output folder before extracting template file |
29,468 | public void run ( String path , String port ) { Server server = new Server ( ) ; ServerConnector connector = new ServerConnector ( server ) ; connector . setHost ( "localhost" ) ; connector . setPort ( Integer . parseInt ( port ) ) ; server . addConnector ( connector ) ; ResourceHandler resource_handler = new ResourceHandler ( ) ; resource_handler . setDirectoriesListed ( true ) ; resource_handler . setWelcomeFiles ( new String [ ] { "index.html" } ) ; resource_handler . setResourceBase ( path ) ; HandlerList handlers = new HandlerList ( ) ; handlers . setHandlers ( new Handler [ ] { resource_handler , new DefaultHandler ( ) } ) ; server . setHandler ( handlers ) ; LOGGER . info ( "Serving out contents of: [{}] on http://localhost:{}/" , path , port ) ; LOGGER . info ( "(To stop server hit CTRL-C)" ) ; try { server . start ( ) ; server . join ( ) ; } catch ( Exception e ) { LOGGER . error ( "unable to start server" , e ) ; } } | Run Jetty web server serving out supplied path on supplied port |
29,469 | public static void main ( final String [ ] args ) { try { new Main ( ) . run ( args ) ; } catch ( final JBakeException e ) { System . err . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; System . exit ( 1 ) ; } catch ( final Throwable e ) { System . err . println ( "An unexpected error occurred: " + e . getMessage ( ) ) ; e . printStackTrace ( ) ; System . exit ( 2 ) ; } } | Runs the app with the given arguments . |
29,470 | public void render ( Map < String , Object > content ) throws Exception { String docType = ( String ) content . get ( Crawler . Attributes . TYPE ) ; String outputFilename = config . getDestinationFolder ( ) . getPath ( ) + File . separatorChar + content . get ( Attributes . URI ) ; if ( outputFilename . lastIndexOf ( '.' ) > outputFilename . lastIndexOf ( File . separatorChar ) ) { outputFilename = outputFilename . substring ( 0 , outputFilename . lastIndexOf ( '.' ) ) ; } String outputExtension = config . getOutputExtensionByDocType ( docType ) ; File draftFile = new File ( outputFilename , config . getDraftSuffix ( ) + outputExtension ) ; if ( draftFile . exists ( ) ) { draftFile . delete ( ) ; } File publishedFile = new File ( outputFilename + outputExtension ) ; if ( publishedFile . exists ( ) ) { publishedFile . delete ( ) ; } if ( content . get ( Crawler . Attributes . STATUS ) . equals ( Crawler . Attributes . Status . DRAFT ) ) { outputFilename = outputFilename + config . getDraftSuffix ( ) ; } File outputFile = new File ( outputFilename + outputExtension ) ; Map < String , Object > model = new HashMap < String , Object > ( ) ; model . put ( "content" , content ) ; model . put ( "renderer" , renderingEngine ) ; try { try ( Writer out = createWriter ( outputFile ) ) { renderingEngine . renderDocument ( model , findTemplateName ( docType ) , out ) ; } LOGGER . info ( "Rendering [{}]... done!" , outputFile ) ; } catch ( Exception e ) { LOGGER . error ( "Rendering [{}]... failed!" , outputFile , e ) ; throw new Exception ( "Failed to render file " + outputFile . getAbsolutePath ( ) + ". Cause: " + e . getMessage ( ) , e ) ; } } | Render the supplied content to a file . |
29,471 | public int renderTags ( String tagPath ) throws Exception { int renderedCount = 0 ; final List < Throwable > errors = new LinkedList < > ( ) ; for ( String tag : db . getAllTags ( ) ) { try { Map < String , Object > model = new HashMap < > ( ) ; model . put ( "renderer" , renderingEngine ) ; model . put ( Attributes . TAG , tag ) ; Map < String , Object > map = buildSimpleModel ( Attributes . TAG ) ; model . put ( "content" , map ) ; File path = new File ( config . getDestinationFolder ( ) + File . separator + tagPath + File . separator + tag + config . getOutputExtension ( ) ) ; map . put ( Attributes . ROOTPATH , FileUtil . getUriPathToDestinationRoot ( config , path ) ) ; render ( new ModelRenderingConfig ( path , Attributes . TAG , model , findTemplateName ( Attributes . TAG ) ) ) ; renderedCount ++ ; } catch ( Exception e ) { errors . add ( e ) ; } } if ( config . getRenderTagsIndex ( ) ) { try { Map < String , Object > model = new HashMap < String , Object > ( ) ; model . put ( "renderer" , renderingEngine ) ; Map < String , Object > map = buildSimpleModel ( Attributes . TAGS ) ; model . put ( "content" , map ) ; File path = new File ( config . getDestinationFolder ( ) + File . separator + tagPath + File . separator + "index" + config . getOutputExtension ( ) ) ; map . put ( Attributes . ROOTPATH , FileUtil . getUriPathToDestinationRoot ( config , path ) ) ; render ( new ModelRenderingConfig ( path , "tagindex" , model , findTemplateName ( "tagsindex" ) ) ) ; renderedCount ++ ; } catch ( Exception e ) { errors . add ( e ) ; } } if ( ! errors . isEmpty ( ) ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Failed to render tags. Cause(s):" ) ; for ( Throwable error : errors ) { sb . append ( "\n" ) . append ( error . getMessage ( ) ) ; } throw new Exception ( sb . toString ( ) , errors . get ( 0 ) ) ; } else { return renderedCount ; } } | Render tag files using the supplied content . |
29,472 | static int darker ( int color , float factor ) { return Color . argb ( Color . alpha ( color ) , Math . max ( ( int ) ( Color . red ( color ) * factor ) , 0 ) , Math . max ( ( int ) ( Color . green ( color ) * factor ) , 0 ) , Math . max ( ( int ) ( Color . blue ( color ) * factor ) , 0 ) ) ; } | Darkens a color by a given factor . |
29,473 | static boolean isRtl ( Context context ) { return Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 && context . getResources ( ) . getConfiguration ( ) . getLayoutDirection ( ) == View . LAYOUT_DIRECTION_RTL ; } | Check if layout direction is RTL |
29,474 | public void setSelectedIndex ( int position ) { if ( adapter != null ) { if ( position >= 0 && position <= adapter . getCount ( ) ) { adapter . notifyItemSelected ( position ) ; selectedIndex = position ; setText ( adapter . get ( position ) . toString ( ) ) ; } else { throw new IllegalArgumentException ( "Position must be lower than adapter count!" ) ; } } } | Set the default spinner item using its index |
29,475 | public < T > void setAdapter ( MaterialSpinnerAdapter < T > adapter ) { this . adapter = adapter ; this . adapter . setTextColor ( textColor ) ; this . adapter . setBackgroundSelector ( backgroundSelector ) ; this . adapter . setPopupPadding ( popupPaddingLeft , popupPaddingTop , popupPaddingRight , popupPaddingBottom ) ; setAdapterInternal ( adapter ) ; } | Set the custom adapter for the dropdown items |
29,476 | public static Future doInBackground ( Callable callable ) { final ExecutorService executor = Executors . newSingleThreadExecutor ( ) ; Future future = executor . submit ( callable ) ; if ( executor . isTerminated ( ) ) { executor . shutdown ( ) ; } return future ; } | Submits a Callable object and returns a Future ready to use . |
29,477 | public static String toSQLNameDefault ( String camelCased ) { if ( camelCased . equalsIgnoreCase ( "_id" ) ) { return "_id" ; } StringBuilder sb = new StringBuilder ( ) ; char [ ] buf = camelCased . toCharArray ( ) ; for ( int i = 0 ; i < buf . length ; i ++ ) { char prevChar = ( i > 0 ) ? buf [ i - 1 ] : 0 ; char c = buf [ i ] ; char nextChar = ( i < buf . length - 1 ) ? buf [ i + 1 ] : 0 ; boolean isFirstChar = ( i == 0 ) ; if ( isFirstChar || Character . isLowerCase ( c ) || Character . isDigit ( c ) ) { sb . append ( Character . toUpperCase ( c ) ) ; } else if ( Character . isUpperCase ( c ) ) { if ( Character . isLetterOrDigit ( prevChar ) ) { if ( Character . isLowerCase ( prevChar ) ) { sb . append ( '_' ) . append ( c ) ; } else if ( nextChar > 0 && Character . isLowerCase ( nextChar ) ) { sb . append ( '_' ) . append ( c ) ; } else { sb . append ( c ) ; } } else { sb . append ( c ) ; } } } return sb . toString ( ) ; } | Converts a given CamelCasedString to UPPER_CASE_UNDER_SCORE . |
29,478 | public static String toColumnName ( Field field ) { if ( field . isAnnotationPresent ( Column . class ) ) { Column annotation = field . getAnnotation ( Column . class ) ; return annotation . name ( ) ; } return toSQLNameDefault ( field . getName ( ) ) ; } | Maps a Java Field object to the database s column name . |
29,479 | public static String toTableName ( Class < ? > table ) { if ( table . isAnnotationPresent ( Table . class ) ) { Table annotation = table . getAnnotation ( Table . class ) ; if ( "" . equals ( annotation . name ( ) ) ) { return NamingHelper . toSQLNameDefault ( table . getSimpleName ( ) ) ; } return annotation . name ( ) ; } return NamingHelper . toSQLNameDefault ( table . getSimpleName ( ) ) ; } | Maps a Java Class to the name of the class . |
29,480 | public static int getDatabaseVersion ( ) { Integer databaseVersion = getMetaDataInteger ( METADATA_VERSION ) ; if ( ( databaseVersion == null ) || ( databaseVersion == 0 ) ) { databaseVersion = 1 ; } return databaseVersion ; } | Grabs the database version from the manifest . |
29,481 | public static String getDomainPackageName ( ) { String domainPackageName = getMetaDataString ( METADATA_DOMAIN_PACKAGE_NAME ) ; if ( domainPackageName == null ) { domainPackageName = "" ; } return domainPackageName ; } | Grabs the domain name of the model classes from the manifest . |
29,482 | public static String getDatabaseName ( ) { String databaseName = getMetaDataString ( METADATA_DATABASE ) ; if ( databaseName == null ) { databaseName = DATABASE_DEFAULT_NAME ; } return databaseName ; } | Grabs the name of the database file specified in the manifest . |
29,483 | public void bulkInsert ( final List < T > objects , final SuccessCallback < List < Long > > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; checkNotNull ( objects ) ; final Callable < List < Long > > call = new Callable < List < Long > > ( ) { public List < Long > call ( ) throws Exception { List < Long > ids = new ArrayList < > ( objects . size ( ) ) ; for ( int i = 0 ; i < objects . size ( ) ; i ++ ) { Long id = SugarRecord . save ( objects . get ( i ) ) ; ids . add ( i , id ) ; } return ids ; } } ; final Future < List < Long > > future = doInBackground ( call ) ; List < Long > ids ; try { ids = future . get ( ) ; if ( null == ids || ids . isEmpty ( ) ) { errorCallback . onError ( new Exception ( "Error when performing bulk insert" ) ) ; } else { successCallback . onSuccess ( ids ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that performs a bulk insert . It works on top of SugarRecord class and executes the query asynchronously using Futures . |
29,484 | public void query ( final String whereClause , final String [ ] whereArgs , final String groupBy , final String orderBy , final String limit , final SuccessCallback < Cursor > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; final Callable < Cursor > call = new Callable < Cursor > ( ) { public Cursor call ( ) throws Exception { return SugarRecord . getCursor ( getSugarClass ( ) , whereClause , whereArgs , groupBy , orderBy , limit ) ; } } ; final Future < Cursor > future = doInBackground ( call ) ; Cursor cursor ; try { cursor = future . get ( ) ; if ( null == cursor ) { errorCallback . onError ( new Exception ( "Problem when trying to get the cursor" ) ) ; } else { successCallback . onSuccess ( cursor ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that provides you the ability of perform a custom query and retrieve a cursor . It works on top of SugarRecord class All the code is executed asynchronously with the usage of Futures and callbacks . |
29,485 | public void listAll ( final String orderBy , final SuccessCallback < List < T > > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; final Callable < List < T > > call = new Callable < List < T > > ( ) { public List < T > call ( ) throws Exception { return SugarRecord . listAll ( getSugarClass ( ) , orderBy ) ; } } ; final Future < List < T > > future = doInBackground ( call ) ; List < T > objects ; try { objects = future . get ( ) ; if ( null == objects || objects . isEmpty ( ) ) { errorCallback . onError ( new Exception ( "There are no objects in the database" ) ) ; } else { successCallback . onSuccess ( objects ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that list all elements . It run a SugarRecord . listAll but it s code is performed asynchronously with the usage of Futures and callbacks . |
29,486 | public void update ( final T object , final SuccessCallback < Long > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; checkNotNull ( object ) ; final Callable < Long > call = new Callable < Long > ( ) { public Long call ( ) throws Exception { return SugarRecord . update ( object ) ; } } ; final Future < Long > future = doInBackground ( call ) ; Long id ; try { id = future . get ( ) ; if ( null == id ) { errorCallback . onError ( new Exception ( "Error when performing update of " + object . toString ( ) ) ) ; } else { successCallback . onSuccess ( id ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that works on top of SugarRecord . update and runs the code asynchronously via Futures and callbacks . |
29,487 | public void delete ( final T object , final SuccessCallback < Boolean > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; checkNotNull ( object ) ; final Callable < Boolean > call = new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { return SugarRecord . delete ( object ) ; } } ; final Future < Boolean > future = doInBackground ( call ) ; Boolean isDeleted ; try { isDeleted = future . get ( ) ; if ( null == isDeleted || ! isDeleted ) { errorCallback . onError ( new Exception ( "Error when performing delete of " + object . toString ( ) ) ) ; } else { successCallback . onSuccess ( isDeleted ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | This method works on top of SugarRecord and provides asynchronous code execution via the usage of Futures and callbacks to handle success result and error . |
29,488 | public void delete ( final String whereClause , final String [ ] whereArgs , final SuccessCallback < Integer > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; final Callable < Integer > call = new Callable < Integer > ( ) { public Integer call ( ) throws Exception { return SugarRecord . deleteAll ( getSugarClass ( ) , whereClause , whereArgs ) ; } } ; final Future < Integer > future = doInBackground ( call ) ; Integer count ; try { count = future . get ( ) ; if ( null == count ) { errorCallback . onError ( new Exception ( "Error when performing delete of all elements" ) ) ; } else { successCallback . onSuccess ( count ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that performs a selective delete . The code is executed asynchronously via the usage of Futures and result callbacks |
29,489 | public void deleteAll ( final SuccessCallback < Integer > successCallback , final ErrorCallback errorCallback ) { delete ( null , null , successCallback , errorCallback ) ; } | Method that deletes all data in a SQLite table . |
29,490 | public void count ( final SuccessCallback < Long > successCallback , final ErrorCallback errorCallback ) { checkNotNull ( successCallback ) ; checkNotNull ( errorCallback ) ; final Callable < Long > call = new Callable < Long > ( ) { public Long call ( ) throws Exception { return SugarRecord . count ( getSugarClass ( ) ) ; } } ; final Future < Long > future = doInBackground ( call ) ; Long count ; try { count = future . get ( ) ; if ( null == count ) { errorCallback . onError ( new Exception ( "Error when trying to get count" ) ) ; } else { successCallback . onSuccess ( count ) ; } } catch ( Exception e ) { errorCallback . onError ( e ) ; } } | Method that performs a count |
29,491 | private static int calcCombinedIntensity ( final int element ) { final Color color = new Color ( element ) ; return Math . min ( 255 , ( color . getRed ( ) + color . getGreen ( ) + color . getRed ( ) ) / 3 ) ; } | Calculate the combined intensity of a pixel and normalizes it to a value of at most 255 . |
29,492 | public static FilterAdapter buildAdapter ( ) { FilterAdapter adapter = new FilterAdapter ( ) ; adapter . addFilterAdapter ( ColumnPrefixFilter . class , new ColumnPrefixFilterAdapter ( ) ) ; adapter . addFilterAdapter ( ColumnRangeFilter . class , new ColumnRangeFilterAdapter ( ) ) ; adapter . addFilterAdapter ( KeyOnlyFilter . class , new KeyOnlyFilterAdapter ( ) ) ; adapter . addFilterAdapter ( MultipleColumnPrefixFilter . class , new MultipleColumnPrefixFilterAdapter ( ) ) ; adapter . addFilterAdapter ( TimestampsFilter . class , new TimestampsFilterAdapter ( ) ) ; adapter . addFilterAdapter ( TimestampRangeFilter . class , new TimestampRangeFilterAdapter ( ) ) ; ValueFilterAdapter valueFilterAdapter = new ValueFilterAdapter ( ) ; adapter . addFilterAdapter ( ValueFilter . class , valueFilterAdapter ) ; SingleColumnValueFilterAdapter scvfa = new SingleColumnValueFilterAdapter ( valueFilterAdapter ) ; adapter . addFilterAdapter ( SingleColumnValueFilter . class , scvfa ) ; adapter . addFilterAdapter ( SingleColumnValueExcludeFilter . class , new SingleColumnValueExcludeFilterAdapter ( scvfa ) ) ; adapter . addFilterAdapter ( ColumnPaginationFilter . class , new ColumnPaginationFilterAdapter ( ) ) ; adapter . addFilterAdapter ( FirstKeyOnlyFilter . class , new FirstKeyOnlyFilterAdapter ( ) ) ; adapter . addFilterAdapter ( ColumnCountGetFilter . class , new ColumnCountGetFilterAdapter ( ) ) ; adapter . addFilterAdapter ( RandomRowFilter . class , new RandomRowFilterAdapter ( ) ) ; adapter . addFilterAdapter ( PrefixFilter . class , new PrefixFilterAdapter ( ) ) ; adapter . addFilterAdapter ( QualifierFilter . class , new QualifierFilterAdapter ( ) ) ; adapter . addFilterAdapter ( PageFilter . class , new PageFilterAdapter ( ) ) ; adapter . addFilterAdapter ( WhileMatchFilter . class , new WhileMatchFilterAdapter ( adapter ) ) ; adapter . addFilterAdapter ( org . apache . hadoop . hbase . filter . RowFilter . class , new RowFilterAdapter ( ) ) ; adapter . addFilterAdapter ( FuzzyRowFilter . class , new FuzzyRowFilterAdapter ( ) ) ; adapter . addFilterAdapter ( FamilyFilter . class , new FamilyFilterAdapter ( ) ) ; adapter . addFilterAdapter ( BigtableFilter . class , new BigtableFilterAdapter ( ) ) ; try { adapter . addFilterAdapter ( org . apache . hadoop . hbase . filter . MultiRowRangeFilter . class , new MultiRowRangeFilterAdapter ( ) ) ; } catch ( NoClassDefFoundError ignored ) { } FilterListAdapter filterListAdapter = new FilterListAdapter ( adapter ) ; adapter . addFilterAdapter ( FilterList . class , filterListAdapter , filterListAdapter ) ; return adapter ; } | Create a new FilterAdapter |
29,493 | public Optional < Filters . Filter > adaptFilter ( FilterAdapterContext context , Filter filter ) throws IOException { SingleFilterAdapter < ? > adapter = getAdapterForFilterOrThrow ( filter ) ; return Optional . fromNullable ( adapter . adapt ( context , filter ) ) ; } | Adapt an HBase filter into a Cloud Bigtable Rowfilter . |
29,494 | public void throwIfUnsupportedFilter ( Scan scan , Filter filter ) { List < FilterSupportStatus > filterSupportStatuses = new ArrayList < > ( ) ; FilterAdapterContext context = new FilterAdapterContext ( scan , null ) ; collectUnsupportedStatuses ( context , filter , filterSupportStatuses ) ; if ( ! filterSupportStatuses . isEmpty ( ) ) { throw new UnsupportedFilterException ( filterSupportStatuses ) ; } } | Throw a new UnsupportedFilterException if the given filter cannot be adapted to bigtable reader expressions . |
29,495 | protected SingleFilterAdapter < ? > getAdapterForFilterOrThrow ( Filter filter ) { if ( adapterMap . containsKey ( filter . getClass ( ) ) ) { return adapterMap . get ( filter . getClass ( ) ) ; } else { throw new UnsupportedFilterException ( ImmutableList . of ( FilterSupportStatus . newUnknownFilterType ( filter ) ) ) ; } } | Get the adapter for the given Filter or throw an UnsupportedFilterException if one is not available . |
29,496 | private Filter createChain ( ColumnPaginationFilter filter , Filter intermediate ) { ChainFilter chain = FILTERS . chain ( ) ; chain . filter ( FILTERS . limit ( ) . cellsPerColumn ( 1 ) ) ; if ( intermediate != null ) { chain . filter ( intermediate ) ; } chain . filter ( FILTERS . limit ( ) . cellsPerRow ( filter . getLimit ( ) ) ) ; return chain ; } | Create a filter chain that allows the latest values for each qualifier those cells that pass an option intermediate filter and are less than the limit per row . |
29,497 | public static Filter hbaseToTimestampRangeFilter ( long hbaseStartTimestamp , long hbaseEndTimestamp ) { return toTimestampRangeFilter ( TimestampConverter . hbase2bigtable ( hbaseStartTimestamp ) , TimestampConverter . hbase2bigtable ( hbaseEndTimestamp ) ) ; } | Converts a [ startMs endMs ) timestamps to a Cloud Bigtable [ startMicros endMicros ) filter . |
29,498 | public static Filter toTimestampRangeFilter ( long bigtableStartTimestamp , long bigtableEndTimestamp ) { return FILTERS . timestamp ( ) . range ( ) . of ( bigtableStartTimestamp , bigtableEndTimestamp ) ; } | Converts a [ startMicros endNons ) timestamps to a Cloud Bigtable [ startMicros endMicros ) filter . |
29,499 | public static FilterSupportStatus newUnknownFilterType ( Filter unknownFilterType ) { return new FilterSupportStatus ( false , String . format ( "Don't know how to adapt Filter class '%s'" , unknownFilterType . getClass ( ) ) ) ; } | Static helper to construct not support adaptations due to no adapter being available for the given Filter type . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.